diff --git a/src/addons/badges/badges-lazy.module.ts b/src/addons/badges/badges-lazy.module.ts index d37f29cf1..e23e2d26c 100644 --- a/src/addons/badges/badges-lazy.module.ts +++ b/src/addons/badges/badges-lazy.module.ts @@ -48,8 +48,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; @NgModule({ diff --git a/src/addons/badges/badges.module.ts b/src/addons/badges/badges.module.ts index 285282783..fecca7062 100644 --- a/src/addons/badges/badges.module.ts +++ b/src/addons/badges/badges.module.ts @@ -41,10 +41,10 @@ const mainMenuRoutes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreContentLinksDelegate.instance.registerHandler(AddonBadgesMyBadgesLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonBadgesBadgeLinkHandler.instance); - CoreUserDelegate.instance.registerHandler(AddonBadgesUserHandler.instance); - CorePushNotificationsDelegate.instance.registerClickHandler(AddonBadgesPushClickHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonBadgesMyBadgesLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonBadgesBadgeLinkHandler.instance); + CoreUserDelegate.registerHandler(AddonBadgesUserHandler.instance); + CorePushNotificationsDelegate.registerClickHandler(AddonBadgesPushClickHandler.instance); }, }, ], diff --git a/src/addons/badges/pages/issued-badge/issued-badge.ts b/src/addons/badges/pages/issued-badge/issued-badge.ts index d146376e7..0fb6b4ddf 100644 --- a/src/addons/badges/pages/issued-badge/issued-badge.ts +++ b/src/addons/badges/pages/issued-badge/issued-badge.ts @@ -54,9 +54,9 @@ export class AddonBadgesIssuedBadgePage implements OnInit { this.route.queryParams.subscribe(() => { this.badgeLoaded = false; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || this.courseId; // Use 0 for site badges. - this.userId = CoreNavigator.instance.getRouteNumberParam('userId') || CoreSites.instance.getCurrentSite()!.getUserId(); - this.badgeHash = CoreNavigator.instance.getRouteParam('badgeHash') || ''; + this.courseId = CoreNavigator.getRouteNumberParam('courseId') || this.courseId; // Use 0 for site badges. + this.userId = CoreNavigator.getRouteNumberParam('userId') || CoreSites.getCurrentSite()!.getUserId(); + this.badgeHash = CoreNavigator.getRouteParam('badgeHash') || ''; this.fetchIssuedBadge().finally(() => { this.badgeLoaded = true; @@ -70,12 +70,12 @@ export class AddonBadgesIssuedBadgePage implements OnInit { * @return Promise resolved when done. */ async fetchIssuedBadge(): Promise { - this.currentTime = CoreTimeUtils.instance.timestamp(); + this.currentTime = CoreTimeUtils.timestamp(); - this.user = await CoreUser.instance.getProfile(this.userId, this.courseId, true); + this.user = await CoreUser.getProfile(this.userId, this.courseId, true); try { - const badges = await AddonBadges.instance.getUserBadges(this.courseId, this.userId); + const badges = await AddonBadges.getUserBadges(this.courseId, this.userId); const badge = badges.find((badge) => this.badgeHash == badge.uniquehash); if (!badge) { @@ -85,14 +85,14 @@ export class AddonBadgesIssuedBadgePage implements OnInit { this.badge = badge; if (badge.courseid) { try { - this.course = await CoreCourses.instance.getUserCourse(badge.courseid, true); + this.course = await CoreCourses.getUserCourse(badge.courseid, true); } catch { // Maybe an old deleted course. this.course = undefined; } } } catch (message) { - CoreDomUtils.instance.showErrorModalDefault(message, 'Error getting badge data.'); + CoreDomUtils.showErrorModalDefault(message, 'Error getting badge data.'); } } @@ -102,11 +102,11 @@ export class AddonBadgesIssuedBadgePage implements OnInit { * @param refresher Refresher. */ async refreshBadges(refresher?: CustomEvent): Promise { - await CoreUtils.instance.ignoreErrors(Promise.all([ - AddonBadges.instance.invalidateUserBadges(this.courseId, this.userId), + await CoreUtils.ignoreErrors(Promise.all([ + AddonBadges.invalidateUserBadges(this.courseId, this.userId), ])); - await CoreUtils.instance.ignoreErrors(Promise.all([ + await CoreUtils.ignoreErrors(Promise.all([ this.fetchIssuedBadge(), ])); diff --git a/src/addons/badges/pages/user-badges/user-badges.ts b/src/addons/badges/pages/user-badges/user-badges.ts index 5114df908..13b36bb52 100644 --- a/src/addons/badges/pages/user-badges/user-badges.ts +++ b/src/addons/badges/pages/user-badges/user-badges.ts @@ -40,7 +40,7 @@ export class AddonBadgesUserBadgesPage implements AfterViewInit, OnDestroy { constructor(route: ActivatedRoute) { const courseId = parseInt(route.snapshot.queryParams.courseId ?? 0); // Use 0 for site badges. - const userId = parseInt(route.snapshot.queryParams.userId ?? CoreSites.instance.getCurrentSiteUserId()); + const userId = parseInt(route.snapshot.queryParams.userId ?? CoreSites.getCurrentSiteUserId()); this.badges = new AddonBadgesUserBadgesManager(AddonBadgesUserBadgesPage, courseId, userId); } @@ -67,8 +67,8 @@ export class AddonBadgesUserBadgesPage implements AfterViewInit, OnDestroy { * @param refresher Refresher. */ async refreshBadges(refresher?: IonRefresher): Promise { - await CoreUtils.instance.ignoreErrors(AddonBadges.instance.invalidateUserBadges(this.badges.courseId, this.badges.userId)); - await CoreUtils.instance.ignoreErrors(this.fetchBadges()); + await CoreUtils.ignoreErrors(AddonBadges.invalidateUserBadges(this.badges.courseId, this.badges.userId)); + await CoreUtils.ignoreErrors(this.fetchBadges()); refresher?.complete(); } @@ -77,12 +77,12 @@ export class AddonBadgesUserBadgesPage implements AfterViewInit, OnDestroy { * Obtain the initial list of badges. */ private async fetchInitialBadges(): Promise { - this.currentTime = CoreTimeUtils.instance.timestamp(); + this.currentTime = CoreTimeUtils.timestamp(); try { await this.fetchBadges(); } catch (message) { - CoreDomUtils.instance.showErrorModalDefault(message, 'Error loading badges'); + CoreDomUtils.showErrorModalDefault(message, 'Error loading badges'); this.badges.setItems([]); } @@ -92,7 +92,7 @@ export class AddonBadgesUserBadgesPage implements AfterViewInit, OnDestroy { * Update the list of badges. */ private async fetchBadges(): Promise { - const badges = await AddonBadges.instance.getUserBadges(this.badges.courseId, this.badges.userId); + const badges = await AddonBadges.getUserBadges(this.badges.courseId, this.badges.userId); this.badges.setItems(badges); } diff --git a/src/addons/badges/services/badges.ts b/src/addons/badges/services/badges.ts index 2488e5a85..a807534a7 100644 --- a/src/addons/badges/services/badges.ts +++ b/src/addons/badges/services/badges.ts @@ -37,7 +37,7 @@ export class AddonBadgesProvider { * @return Promise resolved with true if enabled, false otherwise. */ async isPluginEnabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.canUseAdvancedFeature('enablebadges') && site.wsAvailable('core_course_get_user_navigation_options'); } @@ -63,7 +63,7 @@ export class AddonBadgesProvider { */ async getUserBadges(courseId: number, userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data: AddonBadgesGetUserBadgesWSParams = { courseid: courseId, userid: userId, @@ -101,14 +101,14 @@ export class AddonBadgesProvider { * @return Promise resolved when data is invalidated. */ async invalidateUserBadges(courseId: number, userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getBadgesCacheKey(courseId, userId)); } } -export class AddonBadges extends makeSingleton(AddonBadgesProvider) {} +export const AddonBadges = makeSingleton(AddonBadgesProvider); /** * Params of core_badges_get_user_badges WS. diff --git a/src/addons/badges/services/handlers/badge-link.ts b/src/addons/badges/services/handlers/badge-link.ts index 7d2ffb80f..4b7b4eb1d 100644 --- a/src/addons/badges/services/handlers/badge-link.ts +++ b/src/addons/badges/services/handlers/badge-link.ts @@ -43,7 +43,7 @@ export class AddonBadgesBadgeLinkHandlerService extends CoreContentLinksHandlerB return [{ action: (siteId: string): void => { - CoreNavigator.instance.navigateToSitePath(`/badges/${params.hash}`, { siteId }); + CoreNavigator.navigateToSitePath(`/badges/${params.hash}`, { siteId }); }, }]; } @@ -59,9 +59,9 @@ export class AddonBadgesBadgeLinkHandlerService extends CoreContentLinksHandlerB * @return Whether the handler is enabled for the URL and site. */ isEnabled(siteId: string): Promise { - return AddonBadges.instance.isPluginEnabled(siteId); + return AddonBadges.isPluginEnabled(siteId); } } -export class AddonBadgesBadgeLinkHandler extends makeSingleton(AddonBadgesBadgeLinkHandlerService) {} +export const AddonBadgesBadgeLinkHandler = makeSingleton(AddonBadgesBadgeLinkHandlerService); diff --git a/src/addons/badges/services/handlers/mybadges-link.ts b/src/addons/badges/services/handlers/mybadges-link.ts index aab4b9a01..2de022feb 100644 --- a/src/addons/badges/services/handlers/mybadges-link.ts +++ b/src/addons/badges/services/handlers/mybadges-link.ts @@ -37,7 +37,7 @@ export class AddonBadgesMyBadgesLinkHandlerService extends CoreContentLinksHandl getActions(): CoreContentLinksAction[] { return [{ action: (siteId: string): void => { - CoreNavigator.instance.navigateToSitePath('/badges', { siteId }); + CoreNavigator.navigateToSitePath('/badges', { siteId }); }, }]; } @@ -50,9 +50,9 @@ export class AddonBadgesMyBadgesLinkHandlerService extends CoreContentLinksHandl * @return Whether the handler is enabled for the URL and site. */ async isEnabled(siteId: string): Promise { - return AddonBadges.instance.isPluginEnabled(siteId); + return AddonBadges.isPluginEnabled(siteId); } } -export class AddonBadgesMyBadgesLinkHandler extends makeSingleton(AddonBadgesMyBadgesLinkHandlerService) {} +export const AddonBadgesMyBadgesLinkHandler = makeSingleton(AddonBadgesMyBadgesLinkHandlerService); diff --git a/src/addons/badges/services/handlers/push-click.ts b/src/addons/badges/services/handlers/push-click.ts index 28e829f64..1d6e41ad6 100644 --- a/src/addons/badges/services/handlers/push-click.ts +++ b/src/addons/badges/services/handlers/push-click.ts @@ -40,9 +40,9 @@ export class AddonBadgesPushClickHandlerService implements CorePushNotifications async handles(notification: CorePushNotificationsNotificationBasicData): Promise { const data = notification.customdata || {}; - if (CoreUtils.instance.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'moodle' && + if (CoreUtils.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'moodle' && (notification.name == 'badgerecipientnotice' || (notification.name == 'badgecreatornotice' && data.hash))) { - return AddonBadges.instance.isPluginEnabled(notification.site); + return AddonBadges.isPluginEnabled(notification.site); } return false; @@ -59,7 +59,7 @@ export class AddonBadgesPushClickHandlerService implements CorePushNotifications if (data.hash) { // We have the hash, open the badge directly. - await CoreNavigator.instance.navigateToSitePath(`/badges/${data.hash}`, { + await CoreNavigator.navigateToSitePath(`/badges/${data.hash}`, { siteId: notification.site, }); @@ -67,17 +67,17 @@ export class AddonBadgesPushClickHandlerService implements CorePushNotifications } // No hash, open the list of user badges. - await CoreUtils.instance.ignoreErrors( - AddonBadges.instance.invalidateUserBadges( + await CoreUtils.ignoreErrors( + AddonBadges.invalidateUserBadges( 0, Number(notification.usertoid), notification.site, ), ); - await CoreNavigator.instance.navigateToSitePath('/badges', { siteId: notification.site }); + await CoreNavigator.navigateToSitePath('/badges', { siteId: notification.site }); } } -export class AddonBadgesPushClickHandler extends makeSingleton(AddonBadgesPushClickHandlerService) {} +export const AddonBadgesPushClickHandler = makeSingleton(AddonBadgesPushClickHandlerService); diff --git a/src/addons/badges/services/handlers/user.ts b/src/addons/badges/services/handlers/user.ts index 0c422af21..a574f3917 100644 --- a/src/addons/badges/services/handlers/user.ts +++ b/src/addons/badges/services/handlers/user.ts @@ -37,7 +37,7 @@ export class AddonBadgesUserHandlerService implements CoreUserProfileHandler { * @return Always enabled. */ isEnabled(): Promise { - return AddonBadges.instance.isPluginEnabled(); + return AddonBadges.isPluginEnabled(); } /** @@ -73,7 +73,7 @@ export class AddonBadgesUserHandlerService implements CoreUserProfileHandler { action: (event, user, courseId): void => { event.preventDefault(); event.stopPropagation(); - CoreNavigator.instance.navigateToSitePath('/badges', { + CoreNavigator.navigateToSitePath('/badges', { params: CoreObject.withoutEmpty({ courseId, userId: user.id }), }); }, @@ -82,4 +82,4 @@ export class AddonBadgesUserHandlerService implements CoreUserProfileHandler { } -export class AddonBadgesUserHandler extends makeSingleton(AddonBadgesUserHandlerService) {} +export const AddonBadgesUserHandler = makeSingleton(AddonBadgesUserHandlerService); diff --git a/src/addons/block/activitymodules/activitymodules.module.ts b/src/addons/block/activitymodules/activitymodules.module.ts index a94a20a03..a9f7a7faa 100644 --- a/src/addons/block/activitymodules/activitymodules.module.ts +++ b/src/addons/block/activitymodules/activitymodules.module.ts @@ -30,7 +30,7 @@ import { AddonBlockActivityModulesComponentsModule } from './components/componen provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockActivityModulesHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockActivityModulesHandler.instance); }, }, ], diff --git a/src/addons/block/activitymodules/components/activitymodules/activitymodules.ts b/src/addons/block/activitymodules/components/activitymodules/activitymodules.ts index edcb45111..dc01fdf70 100644 --- a/src/addons/block/activitymodules/components/activitymodules/activitymodules.ts +++ b/src/addons/block/activitymodules/components/activitymodules/activitymodules.ts @@ -45,7 +45,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i * @return Resolved when done. */ protected async invalidateContent(): Promise { - await CoreCourse.instance.invalidateSections(this.instanceId); + await CoreCourse.invalidateSections(this.instanceId); } /** @@ -54,7 +54,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i * @return Promise resolved when done. */ protected async fetchContent(): Promise { - const sections = await CoreCourse.instance.getSections(this.getCourseId(), false, true); + const sections = await CoreCourse.getSections(this.getCourseId(), false, true); this.entries = []; const archetypes: Record = {}; @@ -66,7 +66,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i } section.modules.forEach((mod) => { - if (mod.uservisible === false || !CoreCourse.instance.moduleHasView(mod) || + if (mod.uservisible === false || !CoreCourse.moduleHasView(mod) || typeof modFullNames[mod.modname] != 'undefined') { // Ignore this module. return; @@ -74,7 +74,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i // Get the archetype of the module type. if (typeof archetypes[mod.modname] == 'undefined') { - archetypes[mod.modname] = CoreCourseModuleDelegate.instance.supportsFeature( + archetypes[mod.modname] = CoreCourseModuleDelegate.supportsFeature( mod.modname, CoreConstants.FEATURE_MOD_ARCHETYPE, CoreConstants.MOD_ARCHETYPE_OTHER, @@ -85,7 +85,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i if (archetypes[mod.modname] == CoreConstants.MOD_ARCHETYPE_RESOURCE) { // All resources are gathered in a single "Resources" option. if (!modFullNames['resources']) { - modFullNames['resources'] = Translate.instance.instant('core.resources'); + modFullNames['resources'] = Translate.instant('core.resources'); } } else { modFullNames[mod.modname] = mod.modplural; @@ -94,14 +94,14 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i }); }); // Sort the modnames alphabetically. - modFullNames = CoreUtils.instance.sortValues(modFullNames); + modFullNames = CoreUtils.sortValues(modFullNames); for (const modName in modFullNames) { let icon: string; if (modName === 'resources') { - icon = CoreCourse.instance.getModuleIconSrc('page', modIcons['page']); + icon = CoreCourse.getModuleIconSrc('page', modIcons['page']); } else { - icon = CoreCourseModuleDelegate.instance.getModuleIconSrc(modName, modIcons[modName]); + icon = CoreCourseModuleDelegate.getModuleIconSrc(modName, modIcons[modName]); } this.entries.push({ @@ -122,7 +122,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i return this.instanceId; } - return CoreSites.instance.getCurrentSiteHomeId(); + return CoreSites.getCurrentSiteHomeId(); } /** @@ -131,7 +131,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i * @param entry Selected entry. */ gotoCoureListModType(entry: AddonBlockActivityModuleEntry): void { - CoreNavigator.instance.navigateToSitePath('course/list-mod-type', { + CoreNavigator.navigateToSitePath('course/list-mod-type', { params: { courseId: this.getCourseId(), modName: entry.modName, diff --git a/src/addons/block/activitymodules/services/block-handler.ts b/src/addons/block/activitymodules/services/block-handler.ts index a6f7885a2..1e34c7419 100644 --- a/src/addons/block/activitymodules/services/block-handler.ts +++ b/src/addons/block/activitymodules/services/block-handler.ts @@ -43,4 +43,4 @@ export class AddonBlockActivityModulesHandlerService extends CoreBlockBaseHandle } -export class AddonBlockActivityModulesHandler extends makeSingleton(AddonBlockActivityModulesHandlerService) {} +export const AddonBlockActivityModulesHandler = makeSingleton(AddonBlockActivityModulesHandlerService); diff --git a/src/addons/block/activityresults/activityresults.module.ts b/src/addons/block/activityresults/activityresults.module.ts index 0d3341953..66b745514 100644 --- a/src/addons/block/activityresults/activityresults.module.ts +++ b/src/addons/block/activityresults/activityresults.module.ts @@ -30,7 +30,7 @@ import { AddonBlockActivityResultsComponentsModule } from './components/componen provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockActivityResultsHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockActivityResultsHandler.instance); }, }, ], diff --git a/src/addons/block/activityresults/services/block-handler.ts b/src/addons/block/activityresults/services/block-handler.ts index cdcb3cb1e..4b65e2572 100644 --- a/src/addons/block/activityresults/services/block-handler.ts +++ b/src/addons/block/activityresults/services/block-handler.ts @@ -44,4 +44,4 @@ export class AddonBlockActivityResultsHandlerService extends CoreBlockBaseHandle } -export class AddonBlockActivityResultsHandler extends makeSingleton(AddonBlockActivityResultsHandlerService) {} +export const AddonBlockActivityResultsHandler = makeSingleton(AddonBlockActivityResultsHandlerService); diff --git a/src/addons/block/badges/badges.module.ts b/src/addons/block/badges/badges.module.ts index 0fcd2dbe7..0c221fa10 100644 --- a/src/addons/block/badges/badges.module.ts +++ b/src/addons/block/badges/badges.module.ts @@ -30,7 +30,7 @@ import { AddonBlockBadgesComponentsModule } from './components/components.module provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockBadgesHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockBadgesHandler.instance); }, }, ], diff --git a/src/addons/block/badges/services/block-handler.ts b/src/addons/block/badges/services/block-handler.ts index 85f7bc760..2b8335d51 100644 --- a/src/addons/block/badges/services/block-handler.ts +++ b/src/addons/block/badges/services/block-handler.ts @@ -44,4 +44,4 @@ export class AddonBlockBadgesHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockBadgesHandler extends makeSingleton(AddonBlockBadgesHandlerService) {} +export const AddonBlockBadgesHandler = makeSingleton(AddonBlockBadgesHandlerService); diff --git a/src/addons/block/blogmenu/blogmenu.module.ts b/src/addons/block/blogmenu/blogmenu.module.ts index 3d5a1af95..ba8442c9f 100644 --- a/src/addons/block/blogmenu/blogmenu.module.ts +++ b/src/addons/block/blogmenu/blogmenu.module.ts @@ -30,7 +30,7 @@ import { AddonBlockBlogMenuComponentsModule } from './components/components.modu provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockBlogMenuHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockBlogMenuHandler.instance); }, }, ], diff --git a/src/addons/block/blogmenu/services/block-handler.ts b/src/addons/block/blogmenu/services/block-handler.ts index 718a29245..8d01c81bf 100644 --- a/src/addons/block/blogmenu/services/block-handler.ts +++ b/src/addons/block/blogmenu/services/block-handler.ts @@ -44,4 +44,4 @@ export class AddonBlockBlogMenuHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockBlogMenuHandler extends makeSingleton(AddonBlockBlogMenuHandlerService) {} +export const AddonBlockBlogMenuHandler = makeSingleton(AddonBlockBlogMenuHandlerService); diff --git a/src/addons/block/blogrecent/blogrecent.module.ts b/src/addons/block/blogrecent/blogrecent.module.ts index 5048ade0f..f870ccac2 100644 --- a/src/addons/block/blogrecent/blogrecent.module.ts +++ b/src/addons/block/blogrecent/blogrecent.module.ts @@ -30,7 +30,7 @@ import { AddonBlockBlogRecentComponentsModule } from './components/components.mo provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockBlogRecentHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockBlogRecentHandler.instance); }, }, ], diff --git a/src/addons/block/blogrecent/services/block-handler.ts b/src/addons/block/blogrecent/services/block-handler.ts index 816ec71bf..b59d438f5 100644 --- a/src/addons/block/blogrecent/services/block-handler.ts +++ b/src/addons/block/blogrecent/services/block-handler.ts @@ -44,4 +44,4 @@ export class AddonBlockBlogRecentHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockBlogRecentHandler extends makeSingleton(AddonBlockBlogRecentHandlerService) {} +export const AddonBlockBlogRecentHandler = makeSingleton(AddonBlockBlogRecentHandlerService); diff --git a/src/addons/block/blogtags/blogtags.module.ts b/src/addons/block/blogtags/blogtags.module.ts index 08103a679..11236ff57 100644 --- a/src/addons/block/blogtags/blogtags.module.ts +++ b/src/addons/block/blogtags/blogtags.module.ts @@ -30,7 +30,7 @@ import { AddonBlockBlogTagsComponentsModule } from './components/components.modu provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockBlogTagsHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockBlogTagsHandler.instance); }, }, ], diff --git a/src/addons/block/blogtags/services/block-handler.ts b/src/addons/block/blogtags/services/block-handler.ts index 41bb68f27..808745941 100644 --- a/src/addons/block/blogtags/services/block-handler.ts +++ b/src/addons/block/blogtags/services/block-handler.ts @@ -44,4 +44,4 @@ export class AddonBlockBlogTagsHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockBlogTagsHandler extends makeSingleton(AddonBlockBlogTagsHandlerService) {} +export const AddonBlockBlogTagsHandler = makeSingleton(AddonBlockBlogTagsHandlerService); diff --git a/src/addons/block/calendarmonth/calendarmonth.module.ts b/src/addons/block/calendarmonth/calendarmonth.module.ts index c432e4d0e..34cf9c783 100644 --- a/src/addons/block/calendarmonth/calendarmonth.module.ts +++ b/src/addons/block/calendarmonth/calendarmonth.module.ts @@ -28,7 +28,7 @@ import { AddonBlockCalendarMonthHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockCalendarMonthHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockCalendarMonthHandler.instance); }, }, ], diff --git a/src/addons/block/calendarmonth/services/block-handler.ts b/src/addons/block/calendarmonth/services/block-handler.ts index d73fc8895..a2149dfde 100644 --- a/src/addons/block/calendarmonth/services/block-handler.ts +++ b/src/addons/block/calendarmonth/services/block-handler.ts @@ -45,11 +45,11 @@ export class AddonBlockCalendarMonthHandlerService extends CoreBlockBaseHandler title: 'addon.block_calendarmonth.pluginname', class: 'addon-block-calendar-month', component: CoreBlockOnlyTitleComponent, - link: AddonCalendar.instance.getMainCalendarPagePath(), + link: AddonCalendar.getMainCalendarPagePath(), linkParams: linkParams, }; } } -export class AddonBlockCalendarMonthHandler extends makeSingleton(AddonBlockCalendarMonthHandlerService) {} +export const AddonBlockCalendarMonthHandler = makeSingleton(AddonBlockCalendarMonthHandlerService); diff --git a/src/addons/block/calendarupcoming/calendarupcoming.module.ts b/src/addons/block/calendarupcoming/calendarupcoming.module.ts index 08884ab7a..92e5d1017 100644 --- a/src/addons/block/calendarupcoming/calendarupcoming.module.ts +++ b/src/addons/block/calendarupcoming/calendarupcoming.module.ts @@ -28,7 +28,7 @@ import { AddonBlockCalendarUpcomingHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockCalendarUpcomingHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockCalendarUpcomingHandler.instance); }, }, ], diff --git a/src/addons/block/calendarupcoming/services/block-handler.ts b/src/addons/block/calendarupcoming/services/block-handler.ts index 2fa351eb0..a965176a4 100644 --- a/src/addons/block/calendarupcoming/services/block-handler.ts +++ b/src/addons/block/calendarupcoming/services/block-handler.ts @@ -45,11 +45,11 @@ export class AddonBlockCalendarUpcomingHandlerService extends CoreBlockBaseHandl title: 'addon.block_calendarupcoming.pluginname', class: 'addon-block-calendar-upcoming', component: CoreBlockOnlyTitleComponent, - link: AddonCalendar.instance.getMainCalendarPagePath(), + link: AddonCalendar.getMainCalendarPagePath(), linkParams: linkParams, }; } } -export class AddonBlockCalendarUpcomingHandler extends makeSingleton(AddonBlockCalendarUpcomingHandlerService) {} +export const AddonBlockCalendarUpcomingHandler = makeSingleton(AddonBlockCalendarUpcomingHandlerService); diff --git a/src/addons/block/comments/comments.module.ts b/src/addons/block/comments/comments.module.ts index 678abdbbb..7f15120bc 100644 --- a/src/addons/block/comments/comments.module.ts +++ b/src/addons/block/comments/comments.module.ts @@ -28,7 +28,7 @@ import { AddonBlockCommentsHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockCommentsHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockCommentsHandler.instance); }, }, ], diff --git a/src/addons/block/comments/services/block-handler.ts b/src/addons/block/comments/services/block-handler.ts index eb99fe5f9..6d7544b9f 100644 --- a/src/addons/block/comments/services/block-handler.ts +++ b/src/addons/block/comments/services/block-handler.ts @@ -50,4 +50,4 @@ export class AddonBlockCommentsHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockCommentsHandler extends makeSingleton(AddonBlockCommentsHandlerService) {} +export const AddonBlockCommentsHandler = makeSingleton(AddonBlockCommentsHandlerService); diff --git a/src/addons/block/completionstatus/completionstatus.module.ts b/src/addons/block/completionstatus/completionstatus.module.ts index a57bc8fcc..63f278c79 100644 --- a/src/addons/block/completionstatus/completionstatus.module.ts +++ b/src/addons/block/completionstatus/completionstatus.module.ts @@ -28,7 +28,7 @@ import { AddonBlockCompletionStatusHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockCompletionStatusHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockCompletionStatusHandler.instance); }, }, ], diff --git a/src/addons/block/completionstatus/services/block-handler.ts b/src/addons/block/completionstatus/services/block-handler.ts index 00458928d..b62f94926 100644 --- a/src/addons/block/completionstatus/services/block-handler.ts +++ b/src/addons/block/completionstatus/services/block-handler.ts @@ -52,4 +52,4 @@ export class AddonBlockCompletionStatusHandlerService extends CoreBlockBaseHandl } -export class AddonBlockCompletionStatusHandler extends makeSingleton(AddonBlockCompletionStatusHandlerService) {} +export const AddonBlockCompletionStatusHandler = makeSingleton(AddonBlockCompletionStatusHandlerService); diff --git a/src/addons/block/glossaryrandom/glossaryrandom.module.ts b/src/addons/block/glossaryrandom/glossaryrandom.module.ts index 75723df8a..c08c28f20 100644 --- a/src/addons/block/glossaryrandom/glossaryrandom.module.ts +++ b/src/addons/block/glossaryrandom/glossaryrandom.module.ts @@ -28,7 +28,7 @@ import { AddonBlockGlossaryRandomHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockGlossaryRandomHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockGlossaryRandomHandler.instance); }, }, ], diff --git a/src/addons/block/glossaryrandom/services/block-handler.ts b/src/addons/block/glossaryrandom/services/block-handler.ts index 94096e488..d0cce231f 100644 --- a/src/addons/block/glossaryrandom/services/block-handler.ts +++ b/src/addons/block/glossaryrandom/services/block-handler.ts @@ -45,4 +45,4 @@ export class AddonBlockGlossaryRandomHandlerService extends CoreBlockBaseHandler } -export class AddonBlockGlossaryRandomHandler extends makeSingleton(AddonBlockGlossaryRandomHandlerService) {} +export const AddonBlockGlossaryRandomHandler = makeSingleton(AddonBlockGlossaryRandomHandlerService); diff --git a/src/addons/block/html/html.module.ts b/src/addons/block/html/html.module.ts index 418b406df..9ae5778fd 100644 --- a/src/addons/block/html/html.module.ts +++ b/src/addons/block/html/html.module.ts @@ -22,7 +22,7 @@ import { AddonBlockHtmlHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockHtmlHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockHtmlHandler.instance); }, }, ], diff --git a/src/addons/block/html/services/block-handler.ts b/src/addons/block/html/services/block-handler.ts index d77fd2deb..a040407f0 100644 --- a/src/addons/block/html/services/block-handler.ts +++ b/src/addons/block/html/services/block-handler.ts @@ -46,4 +46,4 @@ export class AddonBlockHtmlHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockHtmlHandler extends makeSingleton(AddonBlockHtmlHandlerService) {} +export const AddonBlockHtmlHandler = makeSingleton(AddonBlockHtmlHandlerService); diff --git a/src/addons/block/learningplans/learningplans.module.ts b/src/addons/block/learningplans/learningplans.module.ts index acf5d32e7..f461b1dec 100644 --- a/src/addons/block/learningplans/learningplans.module.ts +++ b/src/addons/block/learningplans/learningplans.module.ts @@ -30,7 +30,7 @@ import { CoreBlockComponentsModule } from '@features/block/components/components provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockLearningPlansHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockLearningPlansHandler.instance); }, }, ], diff --git a/src/addons/block/learningplans/services/block-handler.ts b/src/addons/block/learningplans/services/block-handler.ts index 3340be569..8cdaf501f 100644 --- a/src/addons/block/learningplans/services/block-handler.ts +++ b/src/addons/block/learningplans/services/block-handler.ts @@ -45,4 +45,4 @@ export class AddonBlockLearningPlansHandlerService extends CoreBlockBaseHandler } -export class AddonBlockLearningPlansHandler extends makeSingleton(AddonBlockLearningPlansHandlerService) {} +export const AddonBlockLearningPlansHandler = makeSingleton(AddonBlockLearningPlansHandlerService); diff --git a/src/addons/block/myoverview/components/myoverview/myoverview.ts b/src/addons/block/myoverview/components/myoverview/myoverview.ts index c4b8eae72..44624701f 100644 --- a/src/addons/block/myoverview/components/myoverview/myoverview.ts +++ b/src/addons/block/myoverview/components/myoverview/myoverview.ts @@ -148,15 +148,15 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem */ async ngOnInit(): Promise { // Refresh the enabled flags if enabled. - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); // Refresh the enabled flags if site is updated. this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); this.coursesObserver = CoreEvents.on( CoreCoursesProvider.EVENT_MY_COURSES_UPDATED, @@ -166,10 +166,10 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem this.refreshCourseList(); } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); - this.currentSite = CoreSites.instance.getCurrentSite(); + this.currentSite = CoreSites.getCurrentSite(); const promises: Promise[] = []; if (this.currentSite) { @@ -209,16 +209,16 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem const promises: Promise[] = []; // Invalidate course completion data. - promises.push(CoreCourses.instance.invalidateUserCourses().finally(() => - CoreUtils.instance.allPromises(this.courseIds.map((courseId) => - AddonCourseCompletion.instance.invalidateCourseCompletion(courseId))))); + promises.push(CoreCourses.invalidateUserCourses().finally(() => + CoreUtils.allPromises(this.courseIds.map((courseId) => + AddonCourseCompletion.invalidateCourseCompletion(courseId))))); - promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions()); + promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions()); if (this.courseIds.length > 0) { - promises.push(CoreCourses.instance.invalidateCoursesByField('ids', this.courseIds.join(','))); + promises.push(CoreCourses.invalidateCoursesByField('ids', this.courseIds.join(','))); } - await CoreUtils.instance.allPromises(promises).finally(() => { + await CoreUtils.allPromises(promises).finally(() => { this.prefetchIconsInitialized = false; }); } @@ -233,7 +233,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem const showCategories = config?.displaycategories?.value == '1'; - const courses = await CoreCoursesHelper.instance.getUserCoursesWithOptions(this.sort, undefined, undefined, showCategories); + const courses = await CoreCoursesHelper.getUserCoursesWithOptions(this.sort, undefined, undefined, showCategories); // Check to show sort by short name only if the text is visible. if (courses.length > 0) { @@ -300,7 +300,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem false, ); if (this.showFilters.custom == 'show') { - this.customFilter = CoreTextUtils.instance.parseJSON(config?.customfieldsexport?.value, []); + this.customFilter = CoreTextUtils.parseJSON(config?.customfieldsexport?.value, []); } else { this.customFilter = []; } @@ -372,7 +372,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem Object.keys(this.prefetchCoursesData).forEach(async (filter) => { this.prefetchCoursesData[filter] = - await CoreCourseHelper.instance.initPrefetchCoursesIcons(this.courses[filter], this.prefetchCoursesData[filter]); + await CoreCourseHelper.initPrefetchCoursesIcons(this.courses[filter], this.prefetchCoursesData[filter]); }); } @@ -386,10 +386,10 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem const initialIcon = this.prefetchCoursesData[selected].icon; try { - await CoreCourseHelper.instance.prefetchCourses(this.courses[selected], this.prefetchCoursesData[selected]); + await CoreCourseHelper.prefetchCourses(this.courses[selected], this.prefetchCoursesData[selected]); } catch (error) { if (!this.isDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); this.prefetchCoursesData[selected].icon = initialIcon; } } @@ -404,7 +404,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_REFRESHED); try { - await CoreCourses.instance.invalidateUserCourses(); + await CoreCourses.invalidateUserCourses(); } catch (error) { // Ignore errors. } @@ -435,7 +435,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem this.loaded = false; try { - const courses = await CoreCourses.instance.getEnrolledCoursesByCustomField(filterName, filterValue); + const courses = await CoreCourses.getEnrolledCoursesByCustomField(filterName, filterValue); // Get the courses information from allincludinghidden to get the max info about the course. const courseIds = courses.map((course) => course.id); @@ -443,7 +443,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem this.filteredCourses = this.courses.allincludinghidden.filter((allCourse) => courseIds.indexOf(allCourse.id) !== -1); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, this.fetchContentDefaultError); + CoreDomUtils.showErrorModalDefault(error, this.fetchContentDefaultError); } finally { this.loaded = true; } @@ -500,7 +500,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem this.courses.favourite = []; this.courses.hidden = []; - const today = CoreTimeUtils.instance.timestamp(); + const today = CoreTimeUtils.timestamp(); courses.forEach((course) => { if (course.hidden) { this.courses.hidden.push(course); diff --git a/src/addons/block/myoverview/myoverview.module.ts b/src/addons/block/myoverview/myoverview.module.ts index 483e1e36e..b168d1b69 100644 --- a/src/addons/block/myoverview/myoverview.module.ts +++ b/src/addons/block/myoverview/myoverview.module.ts @@ -30,7 +30,7 @@ import { AddonBlockMyOverviewHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockMyOverviewHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockMyOverviewHandler.instance); }, }, ], diff --git a/src/addons/block/myoverview/services/block-handler.ts b/src/addons/block/myoverview/services/block-handler.ts index e95e322f9..9d076c38e 100644 --- a/src/addons/block/myoverview/services/block-handler.ts +++ b/src/addons/block/myoverview/services/block-handler.ts @@ -35,8 +35,8 @@ export class AddonBlockMyOverviewHandlerService extends CoreBlockBaseHandler { * @return Whether or not the handler is enabled on a site level. */ async isEnabled(): Promise { - return (CoreSites.instance.getCurrentSite()?.isVersionGreaterEqualThan('3.6')) || - !CoreCourses.instance.isMyCoursesDisabledInSite(); + return (CoreSites.getCurrentSite()?.isVersionGreaterEqualThan('3.6')) || + !CoreCourses.isMyCoursesDisabledInSite(); } /** @@ -55,4 +55,4 @@ export class AddonBlockMyOverviewHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockMyOverviewHandler extends makeSingleton(AddonBlockMyOverviewHandlerService) {} +export const AddonBlockMyOverviewHandler = makeSingleton(AddonBlockMyOverviewHandlerService); diff --git a/src/addons/block/newsitems/newsitems.module.ts b/src/addons/block/newsitems/newsitems.module.ts index b328ad276..b7822c552 100644 --- a/src/addons/block/newsitems/newsitems.module.ts +++ b/src/addons/block/newsitems/newsitems.module.ts @@ -30,7 +30,7 @@ import { AddonBlockNewsItemsComponentsModule } from './components/components.mod provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockNewsItemsHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockNewsItemsHandler.instance); }, }, ], diff --git a/src/addons/block/newsitems/services/block-handler.ts b/src/addons/block/newsitems/services/block-handler.ts index 04f1ceac5..ff6fa09e1 100644 --- a/src/addons/block/newsitems/services/block-handler.ts +++ b/src/addons/block/newsitems/services/block-handler.ts @@ -44,4 +44,4 @@ export class AddonBlockNewsItemsHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockNewsItemsHandler extends makeSingleton(AddonBlockNewsItemsHandlerService) {} +export const AddonBlockNewsItemsHandler = makeSingleton(AddonBlockNewsItemsHandlerService); diff --git a/src/addons/block/onlineusers/onlineusers.module.ts b/src/addons/block/onlineusers/onlineusers.module.ts index 6eef61477..9cfb819dc 100644 --- a/src/addons/block/onlineusers/onlineusers.module.ts +++ b/src/addons/block/onlineusers/onlineusers.module.ts @@ -30,7 +30,7 @@ import { AddonBlockOnlineUsersComponentsModule } from './components/components.m provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockOnlineUsersHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockOnlineUsersHandler.instance); }, }, ], diff --git a/src/addons/block/onlineusers/services/block-handler.ts b/src/addons/block/onlineusers/services/block-handler.ts index 813dfaae0..c9e19ae3e 100644 --- a/src/addons/block/onlineusers/services/block-handler.ts +++ b/src/addons/block/onlineusers/services/block-handler.ts @@ -43,4 +43,4 @@ export class AddonBlockOnlineUsersHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockOnlineUsersHandler extends makeSingleton(AddonBlockOnlineUsersHandlerService) {} +export const AddonBlockOnlineUsersHandler = makeSingleton(AddonBlockOnlineUsersHandlerService); diff --git a/src/addons/block/privatefiles/privatefiles.module.ts b/src/addons/block/privatefiles/privatefiles.module.ts index a19075e8f..55d4316ac 100644 --- a/src/addons/block/privatefiles/privatefiles.module.ts +++ b/src/addons/block/privatefiles/privatefiles.module.ts @@ -28,7 +28,7 @@ import { AddonBlockPrivateFilesHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockPrivateFilesHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockPrivateFilesHandler.instance); }, }, ], diff --git a/src/addons/block/privatefiles/services/block-handler.ts b/src/addons/block/privatefiles/services/block-handler.ts index 8b2071b7b..6774dd018 100644 --- a/src/addons/block/privatefiles/services/block-handler.ts +++ b/src/addons/block/privatefiles/services/block-handler.ts @@ -46,4 +46,4 @@ export class AddonBlockPrivateFilesHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockPrivateFilesHandler extends makeSingleton(AddonBlockPrivateFilesHandlerService) {} +export const AddonBlockPrivateFilesHandler = makeSingleton(AddonBlockPrivateFilesHandlerService); diff --git a/src/addons/block/recentactivity/recentactivity.module.ts b/src/addons/block/recentactivity/recentactivity.module.ts index 97ae712df..e461c2e01 100644 --- a/src/addons/block/recentactivity/recentactivity.module.ts +++ b/src/addons/block/recentactivity/recentactivity.module.ts @@ -30,7 +30,7 @@ import { AddonBlockRecentActivityComponentsModule } from './components/component provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockRecentActivityHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockRecentActivityHandler.instance); }, }, ], diff --git a/src/addons/block/recentactivity/services/block-handler.ts b/src/addons/block/recentactivity/services/block-handler.ts index a2e35f24b..0686b6d82 100644 --- a/src/addons/block/recentactivity/services/block-handler.ts +++ b/src/addons/block/recentactivity/services/block-handler.ts @@ -44,4 +44,4 @@ export class AddonBlockRecentActivityHandlerService extends CoreBlockBaseHandler } -export class AddonBlockRecentActivityHandler extends makeSingleton(AddonBlockRecentActivityHandlerService) {} +export const AddonBlockRecentActivityHandler = makeSingleton(AddonBlockRecentActivityHandlerService); diff --git a/src/addons/block/recentlyaccessedcourses/components/recentlyaccessedcourses/recentlyaccessedcourses.ts b/src/addons/block/recentlyaccessedcourses/components/recentlyaccessedcourses/recentlyaccessedcourses.ts index ffb1f3f22..8ed2d001e 100644 --- a/src/addons/block/recentlyaccessedcourses/components/recentlyaccessedcourses/recentlyaccessedcourses.ts +++ b/src/addons/block/recentlyaccessedcourses/components/recentlyaccessedcourses/recentlyaccessedcourses.ts @@ -64,15 +64,15 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom async ngOnInit(): Promise { // Refresh the enabled flags if enabled. - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); // Refresh the enabled flags if site is updated. this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); this.coursesObserver = CoreEvents.on( CoreCoursesProvider.EVENT_MY_COURSES_UPDATED, @@ -83,7 +83,7 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); super.ngOnInit(); @@ -107,17 +107,17 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom protected async invalidateContent(): Promise { const promises: Promise[] = []; - promises.push(CoreCourses.instance.invalidateUserCourses().finally(() => + promises.push(CoreCourses.invalidateUserCourses().finally(() => // Invalidate course completion data. - CoreUtils.instance.allPromises(this.courseIds.map((courseId) => - AddonCourseCompletion.instance.invalidateCourseCompletion(courseId))))); + CoreUtils.allPromises(this.courseIds.map((courseId) => + AddonCourseCompletion.invalidateCourseCompletion(courseId))))); - promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions()); + promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions()); if (this.courseIds.length > 0) { - promises.push(CoreCourses.instance.invalidateCoursesByField('ids', this.courseIds.join(','))); + promises.push(CoreCourses.invalidateCoursesByField('ids', this.courseIds.join(','))); } - await CoreUtils.instance.allPromises(promises).finally(() => { + await CoreUtils.allPromises(promises).finally(() => { this.prefetchIconsInitialized = false; }); } @@ -131,7 +131,7 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom const showCategories = this.block.configsRecord && this.block.configsRecord.displaycategories && this.block.configsRecord.displaycategories.value == '1'; - this.courses = await CoreCoursesHelper.instance.getUserCoursesWithOptions('lastaccess', 10, undefined, showCategories); + this.courses = await CoreCoursesHelper.getUserCoursesWithOptions('lastaccess', 10, undefined, showCategories); this.initPrefetchCoursesIcons(); } @@ -144,7 +144,7 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_REFRESHED); try { - await CoreCourses.instance.invalidateUserCourses(); + await CoreCourses.invalidateUserCourses(); } catch (error) { // Ignore errors. } @@ -163,7 +163,7 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom this.prefetchIconsInitialized = true; - this.prefetchCoursesData = await CoreCourseHelper.instance.initPrefetchCoursesIcons(this.courses, this.prefetchCoursesData); + this.prefetchCoursesData = await CoreCourseHelper.initPrefetchCoursesIcons(this.courses, this.prefetchCoursesData); } /** @@ -178,7 +178,7 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom return true; } - if (data.action == CoreCoursesProvider.ACTION_VIEW && data.courseId != CoreSites.instance.getCurrentSiteHomeId() && + if (data.action == CoreCoursesProvider.ACTION_VIEW && data.courseId != CoreSites.getCurrentSiteHomeId() && this.courses[0] && data.courseId != this.courses[0].id) { // Update list if user viewed a course that isn't the most recent one and isn't site home. return true; @@ -216,10 +216,10 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom const initialIcon = this.prefetchCoursesData.icon; try { - return CoreCourseHelper.instance.prefetchCourses(this.courses, this.prefetchCoursesData); + return CoreCourseHelper.prefetchCourses(this.courses, this.prefetchCoursesData); } catch (error) { if (!this.isDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); this.prefetchCoursesData.icon = initialIcon; } } diff --git a/src/addons/block/recentlyaccessedcourses/recentlyaccessedcourses.module.ts b/src/addons/block/recentlyaccessedcourses/recentlyaccessedcourses.module.ts index 7e305ed8f..fa26dc333 100644 --- a/src/addons/block/recentlyaccessedcourses/recentlyaccessedcourses.module.ts +++ b/src/addons/block/recentlyaccessedcourses/recentlyaccessedcourses.module.ts @@ -28,7 +28,7 @@ import { AddonBlockRecentlyAccessedCoursesHandler } from './services/block-handl provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockRecentlyAccessedCoursesHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockRecentlyAccessedCoursesHandler.instance); }, }, ], diff --git a/src/addons/block/recentlyaccessedcourses/services/block-handler.ts b/src/addons/block/recentlyaccessedcourses/services/block-handler.ts index a104adf90..935bcf9f2 100644 --- a/src/addons/block/recentlyaccessedcourses/services/block-handler.ts +++ b/src/addons/block/recentlyaccessedcourses/services/block-handler.ts @@ -43,4 +43,4 @@ export class AddonBlockRecentlyAccessedCoursesHandlerService extends CoreBlockBa } -export class AddonBlockRecentlyAccessedCoursesHandler extends makeSingleton(AddonBlockRecentlyAccessedCoursesHandlerService) {} +export const AddonBlockRecentlyAccessedCoursesHandler = makeSingleton(AddonBlockRecentlyAccessedCoursesHandlerService); diff --git a/src/addons/block/recentlyaccesseditems/components/recentlyaccesseditems/recentlyaccesseditems.ts b/src/addons/block/recentlyaccesseditems/components/recentlyaccesseditems/recentlyaccesseditems.ts index 65c55f24e..848dc6692 100644 --- a/src/addons/block/recentlyaccesseditems/components/recentlyaccesseditems/recentlyaccesseditems.ts +++ b/src/addons/block/recentlyaccesseditems/components/recentlyaccesseditems/recentlyaccesseditems.ts @@ -48,7 +48,7 @@ export class AddonBlockRecentlyAccessedItemsComponent extends CoreBlockBaseCompo * @return Resolved when done. */ protected async invalidateContent(): Promise { - await AddonBlockRecentlyAccessedItems.instance.invalidateRecentItems(); + await AddonBlockRecentlyAccessedItems.invalidateRecentItems(); } /** @@ -57,7 +57,7 @@ export class AddonBlockRecentlyAccessedItemsComponent extends CoreBlockBaseCompo * @return Promise resolved when done. */ protected async fetchContent(): Promise { - this.items = await AddonBlockRecentlyAccessedItems.instance.getRecentItems(); + this.items = await AddonBlockRecentlyAccessedItems.getRecentItems(); } /** @@ -70,13 +70,13 @@ export class AddonBlockRecentlyAccessedItemsComponent extends CoreBlockBaseCompo e.preventDefault(); e.stopPropagation(); - const url = CoreTextUtils.instance.decodeHTMLEntities(item.viewurl); - const modal = await CoreDomUtils.instance.showModalLoading(); + const url = CoreTextUtils.decodeHTMLEntities(item.viewurl); + const modal = await CoreDomUtils.showModalLoading(); try { - const treated = await CoreContentLinksHelper.instance.handleLink(url); + const treated = await CoreContentLinksHelper.handleLink(url); if (!treated) { - return CoreSites.instance.getCurrentSite()?.openInBrowserWithAutoLoginIfSameSite(url); + return CoreSites.getCurrentSite()?.openInBrowserWithAutoLoginIfSameSite(url); } } finally { modal.dismiss(); diff --git a/src/addons/block/recentlyaccesseditems/recentlyaccesseditems.module.ts b/src/addons/block/recentlyaccesseditems/recentlyaccesseditems.module.ts index 57359e0bc..0ab91b252 100644 --- a/src/addons/block/recentlyaccesseditems/recentlyaccesseditems.module.ts +++ b/src/addons/block/recentlyaccesseditems/recentlyaccesseditems.module.ts @@ -28,7 +28,7 @@ import { AddonBlockRecentlyAccessedItemsHandler } from './services/block-handler provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockRecentlyAccessedItemsHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockRecentlyAccessedItemsHandler.instance); }, }, ], diff --git a/src/addons/block/recentlyaccesseditems/services/block-handler.ts b/src/addons/block/recentlyaccesseditems/services/block-handler.ts index 747f672ad..0ceec5d43 100644 --- a/src/addons/block/recentlyaccesseditems/services/block-handler.ts +++ b/src/addons/block/recentlyaccesseditems/services/block-handler.ts @@ -46,4 +46,4 @@ export class AddonBlockRecentlyAccessedItemsHandlerService extends CoreBlockBase } -export class AddonBlockRecentlyAccessedItemsHandler extends makeSingleton(AddonBlockRecentlyAccessedItemsHandlerService) {} +export const AddonBlockRecentlyAccessedItemsHandler = makeSingleton(AddonBlockRecentlyAccessedItemsHandlerService); diff --git a/src/addons/block/recentlyaccesseditems/services/recentlyaccesseditems.ts b/src/addons/block/recentlyaccesseditems/services/recentlyaccesseditems.ts index 42376d2c5..41c0c501c 100644 --- a/src/addons/block/recentlyaccesseditems/services/recentlyaccesseditems.ts +++ b/src/addons/block/recentlyaccesseditems/services/recentlyaccesseditems.ts @@ -43,7 +43,7 @@ export class AddonBlockRecentlyAccessedItemsProvider { * @return Promise resolved when the info is retrieved. */ async getRecentItems(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { cacheKey: this.getRecentItemsCacheKey(), @@ -53,9 +53,9 @@ export class AddonBlockRecentlyAccessedItemsProvider { await site.read('block_recentlyaccesseditems_get_recent_items', undefined, preSets); return items.map((item) => { - const modicon = item.icon && CoreDomUtils.instance.getHTMLElementAttribute(item.icon, 'src'); + const modicon = item.icon && CoreDomUtils.getHTMLElementAttribute(item.icon, 'src'); - item.iconUrl = CoreCourse.instance.getModuleIconSrc(item.modname, modicon || undefined); + item.iconUrl = CoreCourse.getModuleIconSrc(item.modname, modicon || undefined); return item; }); @@ -68,13 +68,13 @@ export class AddonBlockRecentlyAccessedItemsProvider { * @return Promise resolved when the data is invalidated. */ async invalidateRecentItems(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getRecentItemsCacheKey()); } } -export class AddonBlockRecentlyAccessedItems extends makeSingleton(AddonBlockRecentlyAccessedItemsProvider) {} +export const AddonBlockRecentlyAccessedItems = makeSingleton(AddonBlockRecentlyAccessedItemsProvider); /** diff --git a/src/addons/block/rssclient/rssclient.module.ts b/src/addons/block/rssclient/rssclient.module.ts index c572d8925..72bcc39e8 100644 --- a/src/addons/block/rssclient/rssclient.module.ts +++ b/src/addons/block/rssclient/rssclient.module.ts @@ -30,7 +30,7 @@ import { AddonBlockRssClientComponentsModule } from './components/components.mod provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockRssClientHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockRssClientHandler.instance); }, }, ], diff --git a/src/addons/block/rssclient/services/block-handler.ts b/src/addons/block/rssclient/services/block-handler.ts index 15368c908..eb079eaef 100644 --- a/src/addons/block/rssclient/services/block-handler.ts +++ b/src/addons/block/rssclient/services/block-handler.ts @@ -46,4 +46,4 @@ export class AddonBlockRssClientHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockRssClientHandler extends makeSingleton(AddonBlockRssClientHandlerService) {} +export const AddonBlockRssClientHandler = makeSingleton(AddonBlockRssClientHandlerService); diff --git a/src/addons/block/selfcompletion/selfcompletion.module.ts b/src/addons/block/selfcompletion/selfcompletion.module.ts index 13d8e0712..42fb3ce44 100644 --- a/src/addons/block/selfcompletion/selfcompletion.module.ts +++ b/src/addons/block/selfcompletion/selfcompletion.module.ts @@ -28,7 +28,7 @@ import { AddonBlockSelfCompletionHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockSelfCompletionHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockSelfCompletionHandler.instance); }, }, ], diff --git a/src/addons/block/selfcompletion/services/block-handler.ts b/src/addons/block/selfcompletion/services/block-handler.ts index ff046df7b..e8a8e6783 100644 --- a/src/addons/block/selfcompletion/services/block-handler.ts +++ b/src/addons/block/selfcompletion/services/block-handler.ts @@ -50,4 +50,4 @@ export class AddonBlockSelfCompletionHandlerService extends CoreBlockBaseHandler } -export class AddonBlockSelfCompletionHandler extends makeSingleton(AddonBlockSelfCompletionHandlerService) {} +export const AddonBlockSelfCompletionHandler = makeSingleton(AddonBlockSelfCompletionHandlerService); diff --git a/src/addons/block/sitemainmenu/components/sitemainmenu/sitemainmenu.ts b/src/addons/block/sitemainmenu/components/sitemainmenu/sitemainmenu.ts index 5f8c2a85b..c0aad05ef 100644 --- a/src/addons/block/sitemainmenu/components/sitemainmenu/sitemainmenu.ts +++ b/src/addons/block/sitemainmenu/components/sitemainmenu/sitemainmenu.ts @@ -45,7 +45,7 @@ export class AddonBlockSiteMainMenuComponent extends CoreBlockBaseComponent impl * Component being initialized. */ async ngOnInit(): Promise { - this.siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); + this.siteHomeId = CoreSites.getCurrentSiteHomeId(); super.ngOnInit(); } @@ -58,12 +58,12 @@ export class AddonBlockSiteMainMenuComponent extends CoreBlockBaseComponent impl protected async invalidateContent(): Promise { const promises: Promise[] = []; - promises.push(CoreCourse.instance.invalidateSections(this.siteHomeId)); - promises.push(CoreSiteHome.instance.invalidateNewsForum(this.siteHomeId)); + promises.push(CoreCourse.invalidateSections(this.siteHomeId)); + promises.push(CoreSiteHome.invalidateNewsForum(this.siteHomeId)); if (this.mainMenuBlock && this.mainMenuBlock.modules) { // Invalidate modules prefetch data. - promises.push(CoreCourseModulePrefetchDelegate.instance.invalidateModules(this.mainMenuBlock.modules, this.siteHomeId)); + promises.push(CoreCourseModulePrefetchDelegate.invalidateModules(this.mainMenuBlock.modules, this.siteHomeId)); } await Promise.all(promises); @@ -75,14 +75,14 @@ export class AddonBlockSiteMainMenuComponent extends CoreBlockBaseComponent impl * @return Promise resolved when done. */ protected async fetchContent(): Promise { - const sections = await CoreCourse.instance.getSections(this.siteHomeId, false, true); + const sections = await CoreCourse.getSections(this.siteHomeId, false, true); const mainMenuBlock = sections.find((section) => section.section == 0); if (!mainMenuBlock) { return; } - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); const config = currentSite ? currentSite.getStoredConfig() || {} : {}; if (!config.frontpageloggedin) { return; @@ -91,7 +91,7 @@ export class AddonBlockSiteMainMenuComponent extends CoreBlockBaseComponent impl const items = config.frontpageloggedin.split(','); const hasNewsItem = items.find((item) => parseInt(item, 10) == FrontPageItemNames['NEWS_ITEMS']); - const result = CoreCourseHelper.instance.addHandlerDataForModules( + const result = CoreCourseHelper.addHandlerDataForModules( [mainMenuBlock], this.siteHomeId, undefined, @@ -107,7 +107,7 @@ export class AddonBlockSiteMainMenuComponent extends CoreBlockBaseComponent impl // Remove forum activity (news one only) from the main menu block to prevent duplicates. try { - const forum = await CoreSiteHome.instance.getNewsForum(this.siteHomeId); + const forum = await CoreSiteHome.getNewsForum(this.siteHomeId); // Search the module that belongs to site news. const forumIndex = this.mainMenuBlock.modules.findIndex((mod) => mod.modname == 'forum' && mod.instance == forum.id); diff --git a/src/addons/block/sitemainmenu/services/block-handler.ts b/src/addons/block/sitemainmenu/services/block-handler.ts index 876822ec5..db1a203ae 100644 --- a/src/addons/block/sitemainmenu/services/block-handler.ts +++ b/src/addons/block/sitemainmenu/services/block-handler.ts @@ -43,4 +43,4 @@ export class AddonBlockSiteMainMenuHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockSiteMainMenuHandler extends makeSingleton(AddonBlockSiteMainMenuHandlerService) {} +export const AddonBlockSiteMainMenuHandler = makeSingleton(AddonBlockSiteMainMenuHandlerService); diff --git a/src/addons/block/sitemainmenu/sitemainmenu.module.ts b/src/addons/block/sitemainmenu/sitemainmenu.module.ts index 80abc29da..cf01b58e2 100644 --- a/src/addons/block/sitemainmenu/sitemainmenu.module.ts +++ b/src/addons/block/sitemainmenu/sitemainmenu.module.ts @@ -28,7 +28,7 @@ import { AddonBlockSiteMainMenuHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockSiteMainMenuHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockSiteMainMenuHandler.instance); }, }, ], diff --git a/src/addons/block/starredcourses/components/starredcourses/starredcourses.ts b/src/addons/block/starredcourses/components/starredcourses/starredcourses.ts index d7a848b96..fb105df7a 100644 --- a/src/addons/block/starredcourses/components/starredcourses/starredcourses.ts +++ b/src/addons/block/starredcourses/components/starredcourses/starredcourses.ts @@ -63,15 +63,15 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im */ async ngOnInit(): Promise { // Refresh the enabled flags if enabled. - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); // Refresh the enabled flags if site is updated. this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); this.coursesObserver = CoreEvents.on( CoreCoursesProvider.EVENT_MY_COURSES_UPDATED, @@ -83,7 +83,7 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im this.refreshContent(); }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); super.ngOnInit(); @@ -107,17 +107,17 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im protected async invalidateContent(): Promise { const promises: Promise[] = []; - promises.push(CoreCourses.instance.invalidateUserCourses().finally(() => + promises.push(CoreCourses.invalidateUserCourses().finally(() => // Invalidate course completion data. - CoreUtils.instance.allPromises(this.courseIds.map((courseId) => - AddonCourseCompletion.instance.invalidateCourseCompletion(courseId))))); + CoreUtils.allPromises(this.courseIds.map((courseId) => + AddonCourseCompletion.invalidateCourseCompletion(courseId))))); - promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions()); + promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions()); if (this.courseIds.length > 0) { - promises.push(CoreCourses.instance.invalidateCoursesByField('ids', this.courseIds.join(','))); + promises.push(CoreCourses.invalidateCoursesByField('ids', this.courseIds.join(','))); } - await CoreUtils.instance.allPromises(promises).finally(() => { + await CoreUtils.allPromises(promises).finally(() => { this.prefetchIconsInitialized = false; }); } @@ -131,7 +131,7 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im const showCategories = this.block.configsRecord && this.block.configsRecord.displaycategories && this.block.configsRecord.displaycategories.value == '1'; - this.courses = await CoreCoursesHelper.instance.getUserCoursesWithOptions('timemodified', 0, 'isfavourite', showCategories); + this.courses = await CoreCoursesHelper.getUserCoursesWithOptions('timemodified', 0, 'isfavourite', showCategories); this.initPrefetchCoursesIcons(); } @@ -144,7 +144,7 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_REFRESHED); try { - await CoreCourses.instance.invalidateUserCourses(); + await CoreCourses.invalidateUserCourses(); } catch (error) { // Ignore errors. } @@ -184,7 +184,7 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im this.prefetchIconsInitialized = true; - this.prefetchCoursesData = await CoreCourseHelper.instance.initPrefetchCoursesIcons(this.courses, this.prefetchCoursesData); + this.prefetchCoursesData = await CoreCourseHelper.initPrefetchCoursesIcons(this.courses, this.prefetchCoursesData); } /** @@ -196,10 +196,10 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im const initialIcon = this.prefetchCoursesData.icon; try { - return CoreCourseHelper.instance.prefetchCourses(this.courses, this.prefetchCoursesData); + return CoreCourseHelper.prefetchCourses(this.courses, this.prefetchCoursesData); } catch (error) { if (!this.isDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); this.prefetchCoursesData.icon = initialIcon; } } diff --git a/src/addons/block/starredcourses/services/block-handler.ts b/src/addons/block/starredcourses/services/block-handler.ts index b220d9be3..4b8c678c1 100644 --- a/src/addons/block/starredcourses/services/block-handler.ts +++ b/src/addons/block/starredcourses/services/block-handler.ts @@ -43,4 +43,4 @@ export class AddonBlockStarredCoursesHandlerService extends CoreBlockBaseHandler } -export class AddonBlockStarredCoursesHandler extends makeSingleton(AddonBlockStarredCoursesHandlerService) {} +export const AddonBlockStarredCoursesHandler = makeSingleton(AddonBlockStarredCoursesHandlerService); diff --git a/src/addons/block/starredcourses/starredcourses.module.ts b/src/addons/block/starredcourses/starredcourses.module.ts index 20dfba809..e88ff3b4b 100644 --- a/src/addons/block/starredcourses/starredcourses.module.ts +++ b/src/addons/block/starredcourses/starredcourses.module.ts @@ -30,7 +30,7 @@ import { AddonBlockStarredCoursesHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockStarredCoursesHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockStarredCoursesHandler.instance); }, }, ], diff --git a/src/addons/block/tags/services/block-handler.ts b/src/addons/block/tags/services/block-handler.ts index 381151d24..e69964127 100644 --- a/src/addons/block/tags/services/block-handler.ts +++ b/src/addons/block/tags/services/block-handler.ts @@ -44,4 +44,4 @@ export class AddonBlockTagsHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockTagsHandler extends makeSingleton(AddonBlockTagsHandlerService) {} +export const AddonBlockTagsHandler = makeSingleton(AddonBlockTagsHandlerService); diff --git a/src/addons/block/tags/tags.module.ts b/src/addons/block/tags/tags.module.ts index e20b990b6..e088c245c 100644 --- a/src/addons/block/tags/tags.module.ts +++ b/src/addons/block/tags/tags.module.ts @@ -30,7 +30,7 @@ import { AddonBlockTagsComponentsModule } from './components/components.module'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockTagsHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockTagsHandler.instance); }, }, ], diff --git a/src/addons/block/timeline/components/events/events.ts b/src/addons/block/timeline/components/events/events.ts index 0f5a3f97e..c5b71e4fd 100644 --- a/src/addons/block/timeline/components/events/events.ts +++ b/src/addons/block/timeline/components/events/events.ts @@ -51,7 +51,7 @@ export class AddonBlockTimelineEventsComponent implements OnChanges { * Detect changes on input properties. */ ngOnChanges(changes: {[name: string]: SimpleChange}): void { - this.showCourse = CoreUtils.instance.isTrueOrOne(this.showCourse); + this.showCourse = CoreUtils.isTrueOrOne(this.showCourse); if (changes.events || changes.from || changes.to) { if (this.events && this.events.length > 0) { @@ -60,7 +60,7 @@ export class AddonBlockTimelineEventsComponent implements OnChanges { const eventsByDay: Record = {}; filteredEvents.forEach((event) => { - const dayTimestamp = CoreTimeUtils.instance.getMidnightForTimestamp(event.timesort); + const dayTimestamp = CoreTimeUtils.getMidnightForTimestamp(event.timesort); if (eventsByDay[dayTimestamp]) { eventsByDay[dayTimestamp].push(event); } else { @@ -68,7 +68,7 @@ export class AddonBlockTimelineEventsComponent implements OnChanges { } }); - const todaysMidnight = CoreTimeUtils.instance.getMidnightForTimestamp(); + const todaysMidnight = CoreTimeUtils.getMidnightForTimestamp(); this.filteredEvents = []; Object.keys(eventsByDay).forEach((key) => { const dayTimestamp = parseInt(key); @@ -102,7 +102,7 @@ export class AddonBlockTimelineEventsComponent implements OnChanges { return start <= event.timesort; }).map((event) => { - event.iconUrl = CoreCourse.instance.getModuleIconSrc(event.icon.component); + event.iconUrl = CoreCourse.getModuleIconSrc(event.icon.component); return event; }); @@ -127,14 +127,14 @@ export class AddonBlockTimelineEventsComponent implements OnChanges { e.stopPropagation(); // Fix URL format. - url = CoreTextUtils.instance.decodeHTMLEntities(url); + url = CoreTextUtils.decodeHTMLEntities(url); - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { - const treated = await CoreContentLinksHelper.instance.handleLink(url); + const treated = await CoreContentLinksHelper.handleLink(url); if (!treated) { - return CoreSites.instance.getCurrentSite()?.openInBrowserWithAutoLoginIfSameSite(url); + return CoreSites.getCurrentSite()?.openInBrowserWithAutoLoginIfSameSite(url); } } finally { modal.dismiss(); diff --git a/src/addons/block/timeline/components/timeline/timeline.ts b/src/addons/block/timeline/components/timeline/timeline.ts index 4f25fcfea..c2c3c9c3b 100644 --- a/src/addons/block/timeline/components/timeline/timeline.ts +++ b/src/addons/block/timeline/components/timeline/timeline.ts @@ -69,7 +69,7 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen * Component being initialized. */ async ngOnInit(): Promise { - this.currentSite = CoreSites.instance.getCurrentSite(); + this.currentSite = CoreSites.getCurrentSite(); this.filter = await this.currentSite!.getLocalSiteConfig('AddonBlockTimelineFilter', this.filter); this.switchFilter(); @@ -87,15 +87,15 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen protected invalidateContent(): Promise { const promises: Promise[] = []; - promises.push(AddonBlockTimeline.instance.invalidateActionEventsByTimesort()); - promises.push(AddonBlockTimeline.instance.invalidateActionEventsByCourses()); - promises.push(CoreCourses.instance.invalidateUserCourses()); - promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions()); + promises.push(AddonBlockTimeline.invalidateActionEventsByTimesort()); + promises.push(AddonBlockTimeline.invalidateActionEventsByCourses()); + promises.push(CoreCourses.invalidateUserCourses()); + promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions()); if (this.courseIds.length > 0) { - promises.push(CoreCourses.instance.invalidateCoursesByField('ids', this.courseIds.join(','))); + promises.push(CoreCourses.invalidateCoursesByField('ids', this.courseIds.join(','))); } - return CoreUtils.instance.allPromises(promises); + return CoreUtils.allPromises(promises); } /** @@ -124,7 +124,7 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen try { await this.fetchMyOverviewTimeline(this.timeline.canLoadMore); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, this.fetchContentDefaultError); + CoreDomUtils.showErrorModalDefault(error, this.fetchContentDefaultError); } } @@ -136,11 +136,11 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen */ async loadMoreCourse(course: AddonBlockTimelineCourse): Promise { try { - const courseEvents = await AddonBlockTimeline.instance.getActionEventsByCourse(course.id, course.canLoadMore); + const courseEvents = await AddonBlockTimeline.getActionEventsByCourse(course.id, course.canLoadMore); course.events = course.events?.concat(courseEvents.events); course.canLoadMore = courseEvents.canLoadMore; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, this.fetchContentDefaultError); + CoreDomUtils.showErrorModalDefault(error, this.fetchContentDefaultError); } } @@ -151,7 +151,7 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen * @return Promise resolved when done. */ protected async fetchMyOverviewTimeline(afterEventId?: number): Promise { - const events = await AddonBlockTimeline.instance.getActionEventsByTimesort(afterEventId); + const events = await AddonBlockTimeline.getActionEventsByTimesort(afterEventId); this.timeline.events = events.events; this.timeline.canLoadMore = events.canLoadMore; @@ -163,8 +163,8 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen * @return Promise resolved when done. */ protected async fetchMyOverviewTimelineByCourses(): Promise { - const courses = await CoreCoursesHelper.instance.getUserCoursesWithOptions(); - const today = CoreTimeUtils.instance.timestamp(); + const courses = await CoreCoursesHelper.getUserCoursesWithOptions(); + const today = CoreTimeUtils.timestamp(); this.timelineCourses.courses = courses.filter((course) => (course.startdate || 0) <= today && (!course.enddate || course.enddate >= today)); @@ -172,7 +172,7 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen if (this.timelineCourses.courses.length > 0) { this.courseIds = this.timelineCourses.courses.map((course) => course.id); - const courseEvents = await AddonBlockTimeline.instance.getActionEventsByCourses(this.courseIds); + const courseEvents = await AddonBlockTimeline.getActionEventsByCourses(this.courseIds); this.timelineCourses.courses.forEach((course) => { course.events = courseEvents[course.id].events; diff --git a/src/addons/block/timeline/services/block-handler.ts b/src/addons/block/timeline/services/block-handler.ts index 277fd6dc7..d05574786 100644 --- a/src/addons/block/timeline/services/block-handler.ts +++ b/src/addons/block/timeline/services/block-handler.ts @@ -36,11 +36,11 @@ export class AddonBlockTimelineHandlerService extends CoreBlockBaseHandler { * @return Whether or not the handler is enabled on a site level. */ async isEnabled(): Promise { - const enabled = await AddonBlockTimeline.instance.isAvailable(); - const currentSite = CoreSites.instance.getCurrentSite(); + const enabled = await AddonBlockTimeline.isAvailable(); + const currentSite = CoreSites.getCurrentSite(); return enabled && ((currentSite && currentSite.isVersionGreaterEqualThan('3.6')) || - !CoreCourses.instance.isMyCoursesDisabledInSite()); + !CoreCourses.isMyCoursesDisabledInSite()); } /** @@ -59,4 +59,4 @@ export class AddonBlockTimelineHandlerService extends CoreBlockBaseHandler { } -export class AddonBlockTimelineHandler extends makeSingleton(AddonBlockTimelineHandlerService) {} +export const AddonBlockTimelineHandler = makeSingleton(AddonBlockTimelineHandlerService); diff --git a/src/addons/block/timeline/services/timeline.ts b/src/addons/block/timeline/services/timeline.ts index 3848dbd1a..2a4f7e4d0 100644 --- a/src/addons/block/timeline/services/timeline.ts +++ b/src/addons/block/timeline/services/timeline.ts @@ -53,7 +53,7 @@ export class AddonBlockTimelineProvider { afterEventId?: number, siteId?: string, ): Promise<{ events: AddonCalendarEvent[]; canLoadMore?: number }> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const time = moment().subtract(14, 'days').unix(); // Check two weeks ago. @@ -104,7 +104,7 @@ export class AddonBlockTimelineProvider { courseIds: number[], siteId?: string, ): Promise<{[courseId: string]: { events: AddonCalendarEvent[]; canLoadMore: number } }> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const time = moment().subtract(14, 'days').unix(); // Check two weeks ago. @@ -156,7 +156,7 @@ export class AddonBlockTimelineProvider { afterEventId?: number, siteId?: string, ): Promise<{ events: AddonCalendarEvent[]; canLoadMore?: number }> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const timesortfrom = moment().subtract(14, 'days').unix(); // Check two weeks ago. const limitnum = AddonBlockTimelineProvider.EVENTS_LIMIT; @@ -226,7 +226,7 @@ export class AddonBlockTimelineProvider { * @return Promise resolved when the data is invalidated. */ async invalidateActionEventsByCourses(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getActionEventsByCoursesCacheKey()); } @@ -238,7 +238,7 @@ export class AddonBlockTimelineProvider { * @return Promise resolved when the data is invalidated. */ async invalidateActionEventsByTimesort(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getActionEventsByTimesortPrefixCacheKey()); } @@ -250,10 +250,10 @@ export class AddonBlockTimelineProvider { * @return Promise resolved with true if available, resolved with false or rejected otherwise. */ async isAvailable(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // First check if dashboard is disabled. - if (CoreCoursesDashboard.instance.isDisabledInSite(site)) { + if (CoreCoursesDashboard.isDisabledInSite(site)) { return false; } @@ -287,4 +287,4 @@ export class AddonBlockTimelineProvider { } -export class AddonBlockTimeline extends makeSingleton(AddonBlockTimelineProvider) {} +export const AddonBlockTimeline = makeSingleton(AddonBlockTimelineProvider); diff --git a/src/addons/block/timeline/timeline.module.ts b/src/addons/block/timeline/timeline.module.ts index 3c024d20c..62cd2d20e 100644 --- a/src/addons/block/timeline/timeline.module.ts +++ b/src/addons/block/timeline/timeline.module.ts @@ -30,7 +30,7 @@ import { AddonBlockTimelineHandler } from './services/block-handler'; provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreBlockDelegate.instance.registerHandler(AddonBlockTimelineHandler.instance); + CoreBlockDelegate.registerHandler(AddonBlockTimelineHandler.instance); }, }, ], diff --git a/src/addons/calendar/calendar.module.ts b/src/addons/calendar/calendar.module.ts index 1a2d8e16d..8cb2dcd45 100644 --- a/src/addons/calendar/calendar.module.ts +++ b/src/addons/calendar/calendar.module.ts @@ -55,13 +55,13 @@ const mainMenuChildrenRoutes: Routes = [ multi: true, deps: [], useFactory: () => async () => { - CoreContentLinksDelegate.instance.registerHandler(AddonCalendarViewLinkHandler.instance); - CoreMainMenuDelegate.instance.registerHandler(AddonCalendarMainMenuHandler.instance); - CoreCronDelegate.instance.register(AddonCalendarSyncCronHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonCalendarViewLinkHandler.instance); + CoreMainMenuDelegate.registerHandler(AddonCalendarMainMenuHandler.instance); + CoreCronDelegate.register(AddonCalendarSyncCronHandler.instance); - await AddonCalendar.instance.initialize(); + await AddonCalendar.initialize(); - AddonCalendar.instance.scheduleAllSitesEventsNotifications(); + AddonCalendar.scheduleAllSitesEventsNotifications(); }, }, ], diff --git a/src/addons/calendar/components/calendar/calendar.ts b/src/addons/calendar/components/calendar/calendar.ts index 624261ec3..e4c68c18d 100644 --- a/src/addons/calendar/components/calendar/calendar.ts +++ b/src/addons/calendar/components/calendar/calendar.ts @@ -89,14 +89,14 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro differs: KeyValueDiffers, ) { - this.currentSiteId = CoreSites.instance.getCurrentSiteId(); + this.currentSiteId = CoreSites.getCurrentSiteId(); - if (CoreLocalNotifications.instance.isAvailable()) { + if (CoreLocalNotifications.isAvailable()) { // Re-schedule events if default time changes. this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => { this.weeks.forEach((week) => { week.days.forEach((day) => { - AddonCalendar.instance.scheduleEventsNotifications(day.eventsFormated!); + AddonCalendar.scheduleEventsNotifications(day.eventsFormated!); }); }); }, this.currentSiteId); @@ -144,9 +144,9 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro * Detect and act upon changes that Angular can’t or won’t detect on its own (objects and arrays). */ ngDoCheck(): void { - this.canNavigate = typeof this.canNavigate == 'undefined' ? true : CoreUtils.instance.isTrueOrOne(this.canNavigate); + this.canNavigate = typeof this.canNavigate == 'undefined' ? true : CoreUtils.isTrueOrOne(this.canNavigate); this.displayNavButtons = typeof this.displayNavButtons == 'undefined' ? true : - CoreUtils.instance.isTrueOrOne(this.displayNavButtons); + CoreUtils.isTrueOrOne(this.displayNavButtons); if (this.weeks) { // Check if there's any change in the filter object. @@ -168,9 +168,9 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro promises.push(this.loadCategories()); // Get offline events. - promises.push(AddonCalendarOffline.instance.getAllEditedEvents().then((events) => { + promises.push(AddonCalendarOffline.getAllEditedEvents().then((events) => { // Classify them by month. - this.offlineEvents = AddonCalendarHelper.instance.classifyIntoMonths(events); + this.offlineEvents = AddonCalendarHelper.classifyIntoMonths(events); // Get the IDs of events edited in offline. const filtered = events.filter((event) => event.id! > 0); @@ -180,14 +180,14 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro })); // Get events deleted in offline. - promises.push(AddonCalendarOffline.instance.getAllDeletedEventsIds().then((ids) => { + promises.push(AddonCalendarOffline.getAllDeletedEventsIds().then((ids) => { this.deletedEvents = ids; return; })); // Get time format to use. - promises.push(AddonCalendar.instance.getCalendarTimeFormat().then((value) => { + promises.push(AddonCalendar.getCalendarTimeFormat().then((value) => { this.timeFormat = value; return; @@ -199,7 +199,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro await this.fetchEvents(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); } this.loaded = true; @@ -214,22 +214,22 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro // Don't pass courseId and categoryId, we'll filter them locally. let result: { daynames: Partial[]; weeks: Partial[] }; try { - result = await AddonCalendar.instance.getMonthlyEvents(this.year!, this.month!); + result = await AddonCalendar.getMonthlyEvents(this.year!, this.month!); } catch (error) { - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // Allow navigating to non-cached months in offline (behave as if using emergency cache). - result = await AddonCalendarHelper.instance.getOfflineMonthWeeks(this.year!, this.month!); + result = await AddonCalendarHelper.getOfflineMonthWeeks(this.year!, this.month!); } else { throw error; } } // Calculate the period name. We don't use the one in result because it's in server's language. - this.periodName = CoreTimeUtils.instance.userDate( + this.periodName = CoreTimeUtils.userDate( new Date(this.year!, this.month! - 1).getTime(), 'core.strftimemonthyear', ); - this.weekDays = AddonCalendar.instance.getWeekDays(result.daynames[0].dayno); + this.weekDays = AddonCalendar.getWeekDays(result.daynames[0].dayno); this.weeks = result.weeks as AddonCalendarWeek[]; this.calculateIsCurrentMonth(); @@ -239,7 +239,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro day.filteredEvents = day.filteredEvents || []; day.events.forEach((event) => { /// Format online events. - day.eventsFormated!.push(AddonCalendarHelper.instance.formatEventData(event)); + day.eventsFormated!.push(AddonCalendarHelper.formatEventData(event)); }); }); }); @@ -280,7 +280,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro } try { - const cats = await CoreCourses.instance.getCategories(0, true); + const cats = await CoreCourses.getCategories(0, true); this.categoriesRetrieved = true; this.categories = {}; @@ -299,14 +299,14 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro filterEvents(): void { this.weeks.forEach((week) => { week.days.forEach((day) => { - day.filteredEvents = AddonCalendarHelper.instance.getFilteredEvents( + day.filteredEvents = AddonCalendarHelper.getFilteredEvents( day.eventsFormated!, this.filter!, this.categories, ); // Re-calculate some properties. - AddonCalendarHelper.instance.calculateDayData(day, day.filteredEvents); + AddonCalendarHelper.calculateDayData(day, day.filteredEvents); }); }); } @@ -322,10 +322,10 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro // Don't invalidate monthly events after a change, it has already been handled. if (!afterChange) { - promises.push(AddonCalendar.instance.invalidateMonthlyEvents(this.year!, this.month!)); + promises.push(AddonCalendar.invalidateMonthlyEvents(this.year!, this.month!)); } - promises.push(CoreCourses.instance.invalidateCategories(0, true)); - promises.push(AddonCalendar.instance.invalidateTimeFormat()); + promises.push(CoreCourses.invalidateCategories(0, true)); + promises.push(AddonCalendar.invalidateTimeFormat()); this.categoriesRetrieved = false; // Get categories again. @@ -345,7 +345,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro try { await this.fetchEvents(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.decreaseMonth(); } this.loaded = true; @@ -362,7 +362,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro try { await this.fetchEvents(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.increaseMonth(); } this.loaded = true; @@ -394,7 +394,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro calculateIsCurrentMonth(): void { const now = new Date(); - this.currentTime = CoreTimeUtils.instance.timestamp(); + this.currentTime = CoreTimeUtils.timestamp(); this.isCurrentMonth = this.year == now.getFullYear() && this.month == now.getMonth() + 1; this.isPastMonth = this.year! < now.getFullYear() || (this.year == now.getFullYear() && this.month! < now.getMonth() + 1); @@ -417,7 +417,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro await this.fetchEvents(); this.isCurrentMonth = true; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.year = initialYear; this.month = initialMonth; } @@ -454,13 +454,13 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro */ protected mergeEvents(): void { const monthOfflineEvents: { [day: number]: AddonCalendarEventToDisplay[] } = - this.offlineEvents[AddonCalendarHelper.instance.getMonthId(this.year!, this.month!)]; + this.offlineEvents[AddonCalendarHelper.getMonthId(this.year!, this.month!)]; this.weeks.forEach((week) => { week.days.forEach((day) => { // Schedule notifications for the events retrieved (only future events will be scheduled). - AddonCalendar.instance.scheduleEventsNotifications(day.eventsFormated!); + AddonCalendar.scheduleEventsNotifications(day.eventsFormated!); if (monthOfflineEvents || this.deletedEvents.length) { // There is offline data, merge it. @@ -480,7 +480,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro if (monthOfflineEvents && monthOfflineEvents[day.mday]) { // Add the offline events (either new or edited). day.eventsFormated = - AddonCalendarHelper.instance.sortEvents(day.eventsFormated!.concat(monthOfflineEvents[day.mday])); + AddonCalendarHelper.sortEvents(day.eventsFormated!.concat(monthOfflineEvents[day.mday])); } } }); diff --git a/src/addons/calendar/components/filter/filter.ts b/src/addons/calendar/components/filter/filter.ts index 9b69396aa..601b53b62 100644 --- a/src/addons/calendar/components/filter/filter.ts +++ b/src/addons/calendar/components/filter/filter.ts @@ -48,7 +48,7 @@ export class AddonCalendarFilterPopoverComponent implements OnInit { types: string[] = []; constructor() { - CoreUtils.instance.enumKeys(AddonCalendarEventType).forEach((name) => { + CoreUtils.enumKeys(AddonCalendarEventType).forEach((name) => { const value = AddonCalendarEventType[name]; this.typeIcons[value] = AddonCalendarEventIcons[name]; this.types.push(value); diff --git a/src/addons/calendar/components/upcoming-events/upcoming-events.ts b/src/addons/calendar/components/upcoming-events/upcoming-events.ts index 6c12077b1..abd2c1b9c 100644 --- a/src/addons/calendar/components/upcoming-events/upcoming-events.ts +++ b/src/addons/calendar/components/upcoming-events/upcoming-events.ts @@ -64,11 +64,11 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On constructor( differs: KeyValueDiffers, ) { - this.currentSiteId = CoreSites.instance.getCurrentSiteId(); + this.currentSiteId = CoreSites.getCurrentSiteId(); - if (CoreLocalNotifications.instance.isAvailable()) { // Re-schedule events if default time changes. + if (CoreLocalNotifications.isAvailable()) { // Re-schedule events if default time changes. this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => { - AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); + AddonCalendar.scheduleEventsNotifications(this.onlineEvents); }, this.currentSiteId); } @@ -124,31 +124,31 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On promises.push(this.loadCategories()); // Get offline events. - promises.push(AddonCalendarOffline.instance.getAllEditedEvents().then((offlineEvents) => { + promises.push(AddonCalendarOffline.getAllEditedEvents().then((offlineEvents) => { // Format data. const events: AddonCalendarEventToDisplay[] = offlineEvents.map((event) => - AddonCalendarHelper.instance.formatOfflineEventData(event)); + AddonCalendarHelper.formatOfflineEventData(event)); - this.offlineEvents = AddonCalendarHelper.instance.sortEvents(events); + this.offlineEvents = AddonCalendarHelper.sortEvents(events); return; })); // Get events deleted in offline. - promises.push(AddonCalendarOffline.instance.getAllDeletedEventsIds().then((ids) => { + promises.push(AddonCalendarOffline.getAllDeletedEventsIds().then((ids) => { this.deletedEvents = ids; return; })); // Get user preferences. - promises.push(AddonCalendar.instance.getCalendarLookAhead().then((value) => { + promises.push(AddonCalendar.getCalendarLookAhead().then((value) => { this.lookAhead = value; return; })); - promises.push(AddonCalendar.instance.getCalendarTimeFormat().then((value) => { + promises.push(AddonCalendar.getCalendarTimeFormat().then((value) => { this.timeFormat = value; return; @@ -160,7 +160,7 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On this.fetchEvents(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); } this.loaded = true; @@ -173,10 +173,10 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On */ async fetchEvents(): Promise { // Don't pass courseId and categoryId, we'll filter them locally. - const result = await AddonCalendar.instance.getUpcomingEvents(); - this.onlineEvents = result.events.map((event) => AddonCalendarHelper.instance.formatEventData(event)); + const result = await AddonCalendar.getUpcomingEvents(); + this.onlineEvents = result.events.map((event) => AddonCalendarHelper.formatEventData(event)); // Schedule notifications for the events retrieved. - AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); + AddonCalendar.scheduleEventsNotifications(this.onlineEvents); // Merge the online events with offline data. this.events = this.mergeEvents(); // Filter events by course. @@ -184,7 +184,7 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On // Re-calculate the formatted time so it uses the device date. const promises = this.events.map((event) => - AddonCalendar.instance.formatEventTime(event, this.timeFormat!).then((time) => { + AddonCalendar.formatEventTime(event, this.timeFormat!).then((time) => { event.formattedtime = time; return; @@ -205,7 +205,7 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On } try { - const cats = await CoreCourses.instance.getCategories(0, true); + const cats = await CoreCourses.getCategories(0, true); this.categoriesRetrieved = true; this.categories = {}; @@ -222,7 +222,7 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On * Filter events based on the filter popover. */ protected filterEvents(): void { - this.filteredEvents = AddonCalendarHelper.instance.getFilteredEvents(this.events, this.filter!, this.categories); + this.filteredEvents = AddonCalendarHelper.getFilteredEvents(this.events, this.filter!, this.categories); } /** @@ -236,11 +236,11 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On // Don't invalidate upcoming events after a change, it has already been handled. if (!afterChange) { - promises.push(AddonCalendar.instance.invalidateAllUpcomingEvents()); + promises.push(AddonCalendar.invalidateAllUpcomingEvents()); } - promises.push(CoreCourses.instance.invalidateCategories(0, true)); - promises.push(AddonCalendar.instance.invalidateLookAhead()); - promises.push(AddonCalendar.instance.invalidateTimeFormat()); + promises.push(CoreCourses.invalidateCategories(0, true)); + promises.push(AddonCalendar.invalidateLookAhead()); + promises.push(AddonCalendar.invalidateTimeFormat()); this.categoriesRetrieved = false; // Get categories again. @@ -297,7 +297,7 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On // Merge both arrays and sort them. result = result.concat(periodOfflineEvents); - return AddonCalendarHelper.instance.sortEvents(result); + return AddonCalendarHelper.sortEvents(result); } /** diff --git a/src/addons/calendar/pages/day/day.page.ts b/src/addons/calendar/pages/day/day.page.ts index c680e52fe..2bd06f1c4 100644 --- a/src/addons/calendar/pages/day/day.page.ts +++ b/src/addons/calendar/pages/day/day.page.ts @@ -102,12 +102,12 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { }; constructor() { - this.currentSiteId = CoreSites.instance.getCurrentSiteId(); + this.currentSiteId = CoreSites.getCurrentSiteId(); - if (CoreLocalNotifications.instance.isAvailable()) { + if (CoreLocalNotifications.isAvailable()) { // Re-schedule events if default time changes. this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => { - AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); + AddonCalendar.scheduleEventsNotifications(this.onlineEvents); }, this.currentSiteId); } @@ -210,17 +210,17 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { this.filter = data; // Course viewed has changed, check if the user can create events for this course calendar. - this.canCreate = await AddonCalendarHelper.instance.canEditEvents(this.filter.courseId); + this.canCreate = await AddonCalendarHelper.canEditEvents(this.filter.courseId); this.filterEvents(); }, ); // Refresh online status when changes. - this.onlineObserver = Network.instance.onChange().subscribe(() => { + this.onlineObserver = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { - this.isOnline = CoreApp.instance.isOnline(); + NgZone.run(() => { + this.isOnline = CoreApp.isOnline(); }); }); } @@ -231,20 +231,20 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { ngOnInit(): void { const types: string[] = []; - CoreUtils.instance.enumKeys(AddonCalendarEventType).forEach((name) => { + CoreUtils.enumKeys(AddonCalendarEventType).forEach((name) => { const value = AddonCalendarEventType[name]; - this.filter[name] = CoreNavigator.instance.getRouteBooleanParam(name) ?? true; + this.filter[name] = CoreNavigator.getRouteBooleanParam(name) ?? true; types.push(value); }); - this.filter.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || -1; - this.filter.categoryId = CoreNavigator.instance.getRouteNumberParam('categoryId'); + this.filter.courseId = CoreNavigator.getRouteNumberParam('courseId') || -1; + this.filter.categoryId = CoreNavigator.getRouteNumberParam('categoryId'); this.filter.filtered = typeof this.filter.courseId != 'undefined' || types.some((name) => !this.filter[name]); const now = new Date(); - this.year = CoreNavigator.instance.getRouteNumberParam('year') || now.getFullYear(); - this.month = CoreNavigator.instance.getRouteNumberParam('month') || (now.getMonth() + 1); - this.day = CoreNavigator.instance.getRouteNumberParam('day') || now.getDate(); + this.year = CoreNavigator.getRouteNumberParam('year') || now.getFullYear(); + this.month = CoreNavigator.getRouteNumberParam('month') || (now.getMonth() + 1); + this.day = CoreNavigator.getRouteNumberParam('day') || now.getDate(); this.calculateCurrentMoment(); this.calculateIsCurrentDay(); @@ -262,7 +262,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { async fetchData(sync?: boolean): Promise { this.syncIcon = CoreConstants.ICON_LOADING; - this.isOnline = CoreApp.instance.isOnline(); + this.isOnline = CoreApp.isOnline(); if (sync) { await this.sync(); @@ -272,7 +272,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { const promises: Promise[] = []; // Load courses for the popover. - promises.push(CoreCoursesHelper.instance.getCoursesForPopover(this.filter.courseId).then((data) => { + promises.push(CoreCoursesHelper.getCoursesForPopover(this.filter.courseId).then((data) => { this.courses = data.courses; return; @@ -282,9 +282,9 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { promises.push(this.loadCategories()); // Get offline events. - promises.push(AddonCalendarOffline.instance.getAllEditedEvents().then((offlineEvents) => { + promises.push(AddonCalendarOffline.getAllEditedEvents().then((offlineEvents) => { // Classify them by month & day. - this.offlineEvents = AddonCalendarHelper.instance.classifyIntoMonths(offlineEvents); + this.offlineEvents = AddonCalendarHelper.classifyIntoMonths(offlineEvents); // Get the IDs of events edited in offline. this.offlineEditedEventsIds = offlineEvents.filter((event) => event.id! > 0).map((event) => event.id!); @@ -293,21 +293,21 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { })); // Get events deleted in offline. - promises.push(AddonCalendarOffline.instance.getAllDeletedEventsIds().then((ids) => { + promises.push(AddonCalendarOffline.getAllDeletedEventsIds().then((ids) => { this.deletedEvents = ids; return; })); // Check if user can create events. - promises.push(AddonCalendarHelper.instance.canEditEvents(this.filter.courseId).then((canEdit) => { + promises.push(AddonCalendarHelper.canEditEvents(this.filter.courseId).then((canEdit) => { this.canCreate = canEdit; return; })); // Get user preferences. - promises.push(AddonCalendar.instance.getCalendarTimeFormat().then((value) => { + promises.push(AddonCalendar.getCalendarTimeFormat().then((value) => { this.timeFormat = value; return; @@ -317,7 +317,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { await this.fetchEvents(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); } this.loaded = true; @@ -333,10 +333,10 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { let result: AddonCalendarCalendarDay; try { // Don't pass courseId and categoryId, we'll filter them locally. - result = await AddonCalendar.instance.getDayEvents(this.year, this.month, this.day); - this.onlineEvents = result.events.map((event) => AddonCalendarHelper.instance.formatEventData(event)); + result = await AddonCalendar.getDayEvents(this.year, this.month, this.day); + this.onlineEvents = result.events.map((event) => AddonCalendarHelper.formatEventData(event)); } catch (error) { - if (CoreApp.instance.isOnline()) { + if (CoreApp.isOnline()) { throw error; } // Allow navigating to non-cached days in offline (behave as if using emergency cache). @@ -344,13 +344,13 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { } // Calculate the period name. We don't use the one in result because it's in server's language. - this.periodName = CoreTimeUtils.instance.userDate( + this.periodName = CoreTimeUtils.userDate( new Date(this.year, this.month - 1, this.day).getTime(), 'core.strftimedaydate', ); // Schedule notifications for the events retrieved (only future events will be scheduled). - AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); + AddonCalendar.scheduleEventsNotifications(this.onlineEvents); // Merge the online events with offline data. this.events = this.mergeEvents(); // Filter events by course. @@ -362,7 +362,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { const promises = this.events.map((event) => { event.ispast = this.isPastDay || (this.isCurrentDay && this.isEventPast(event)); - return AddonCalendar.instance.formatEventTime(event, this.timeFormat!, true, dayTime).then((time) => { + return AddonCalendar.formatEventTime(event, this.timeFormat!, true, dayTime).then((time) => { event.formattedtime = time; return; @@ -385,7 +385,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { return this.onlineEvents; } - const monthOfflineEvents = this.offlineEvents[AddonCalendarHelper.instance.getMonthId(this.year, this.month)]; + const monthOfflineEvents = this.offlineEvents[AddonCalendarHelper.getMonthId(this.year, this.month)]; const dayOfflineEvents = monthOfflineEvents && monthOfflineEvents[this.day]; let result = this.onlineEvents; @@ -412,7 +412,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { if (dayOfflineEvents && dayOfflineEvents.length) { // Add the offline events (either new or edited). this.hasOffline = true; - result = AddonCalendarHelper.instance.sortEvents(result.concat(dayOfflineEvents)); + result = AddonCalendarHelper.sortEvents(result.concat(dayOfflineEvents)); } return result; @@ -422,7 +422,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { * Filter events based on the filter popover. */ protected filterEvents(): void { - this.filteredEvents = AddonCalendarHelper.instance.getFilteredEvents(this.events, this.filter, this.categories); + this.filteredEvents = AddonCalendarHelper.getFilteredEvents(this.events, this.filter, this.categories); } /** @@ -457,11 +457,11 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { // Don't invalidate day events after a change, it has already been handled. if (!afterChange) { - promises.push(AddonCalendar.instance.invalidateDayEvents(this.year, this.month, this.day)); + promises.push(AddonCalendar.invalidateDayEvents(this.year, this.month, this.day)); } - promises.push(AddonCalendar.instance.invalidateAllowedEventTypes()); - promises.push(CoreCourses.instance.invalidateCategories(0, true)); - promises.push(AddonCalendar.instance.invalidateTimeFormat()); + promises.push(AddonCalendar.invalidateAllowedEventTypes()); + promises.push(CoreCourses.invalidateCategories(0, true)); + promises.push(AddonCalendar.invalidateTimeFormat()); await Promise.all(promises).finally(() => this.fetchData(sync)); @@ -474,7 +474,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { */ protected async loadCategories(): Promise { try { - const cats = await CoreCourses.instance.getCategories(0, true); + const cats = await CoreCourses.getCategories(0, true); this.categories = {}; // Index categories by ID. @@ -494,10 +494,10 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { */ protected async sync(showErrors?: boolean): Promise { try { - const result = await AddonCalendarSync.instance.syncEvents(); + const result = await AddonCalendarSync.syncEvents(); if (result.warnings && result.warnings.length) { - CoreDomUtils.instance.showErrorModal(result.warnings[0]); + CoreDomUtils.showErrorModal(result.warnings[0]); } if (result.updated) { @@ -511,7 +511,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { } } catch (error) { if (showErrors) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errorsync', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errorsync', true); } } } @@ -526,7 +526,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { // It's an offline event, go to the edit page. this.openEdit(eventId); } else { - CoreNavigator.instance.navigateToSitePath('/calendar/event', { params: { id: eventId } }); + CoreNavigator.navigateToSitePath('/calendar/event', { params: { id: eventId } }); } } @@ -536,7 +536,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { * @param event Event. */ async openFilter(event: MouseEvent): Promise { - const popover = await PopoverController.instance.create({ + const popover = await PopoverController.create({ component: AddonCalendarFilterPopoverComponent, componentProps: { courses: this.courses, @@ -566,7 +566,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { params.courseId = this.filter.courseId; } - CoreNavigator.instance.navigateToSitePath('/calendar/edit', { params }); + CoreNavigator.navigateToSitePath('/calendar/edit', { params }); } /** @@ -582,7 +582,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { calculateIsCurrentDay(): void { const now = new Date(); - this.currentTime = CoreTimeUtils.instance.timestamp(); + this.currentTime = CoreTimeUtils.timestamp(); this.isCurrentDay = this.year == now.getFullYear() && this.month == now.getMonth() + 1 && this.day == now.getDate(); this.isPastDay = this.year < now.getFullYear() || (this.year == now.getFullYear() && this.month < now.getMonth()) || @@ -610,7 +610,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { this.isCurrentDay = true; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.year = initialYear; this.month = initialMonth; @@ -632,7 +632,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { try { await this.fetchEvents(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.decreaseDay(); } this.loaded = true; @@ -649,7 +649,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy { try { await this.fetchEvents(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.increaseDay(); } this.loaded = true; diff --git a/src/addons/calendar/pages/edit-event/edit-event.page.ts b/src/addons/calendar/pages/edit-event/edit-event.page.ts index e78fe1adb..2321e24eb 100644 --- a/src/addons/calendar/pages/edit-event/edit-event.page.ts +++ b/src/addons/calendar/pages/edit-event/edit-event.page.ts @@ -94,13 +94,13 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { @Optional() protected svComponent: CoreSplitViewComponent, ) { - this.currentSite = CoreSites.instance.getCurrentSite()!; + this.currentSite = CoreSites.getCurrentSite()!; this.errors = { - required: Translate.instance.instant('core.required'), + required: Translate.instant('core.required'), }; // Calculate format to use. ion-datetime doesn't support escaping characters ([]), so we remove them. - this.dateFormat = CoreTimeUtils.instance.convertPHPToMoment(Translate.instance.instant('core.strftimedatetimeshort')) + this.dateFormat = CoreTimeUtils.convertPHPToMoment(Translate.instant('core.strftimedatetimeshort')) .replace(/[[\]]/g, ''); this.form = new FormGroup({}); @@ -127,18 +127,18 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { * Component being initialized. */ ngOnInit(): void { - this.eventId = CoreNavigator.instance.getRouteNumberParam('eventId'); - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || 0; + this.eventId = CoreNavigator.getRouteNumberParam('eventId'); + this.courseId = CoreNavigator.getRouteNumberParam('courseId') || 0; this.title = this.eventId ? 'addon.calendar.editevent' : 'addon.calendar.newevent'; - const timestamp = CoreNavigator.instance.getRouteNumberParam('timestamp'); - const currentDate = CoreTimeUtils.instance.toDatetimeFormat(timestamp); + const timestamp = CoreNavigator.getRouteNumberParam('timestamp'); + const currentDate = CoreTimeUtils.toDatetimeFormat(timestamp); this.form.addControl('timestart', this.fb.control(currentDate, Validators.required)); this.form.addControl('timedurationuntil', this.fb.control(currentDate)); this.form.addControl('courseid', this.fb.control(this.courseId)); this.fetchData().finally(() => { - this.originalData = CoreUtils.instance.clone(this.form.value); + this.originalData = CoreUtils.clone(this.form.value); this.loaded = true; }); } @@ -156,29 +156,29 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { // Get access info. try { - accessInfo = await AddonCalendar.instance.getAccessInformation(this.courseId); - this.types = await AddonCalendar.instance.getAllowedEventTypes(this.courseId); + accessInfo = await AddonCalendar.getAccessInformation(this.courseId); + this.types = await AddonCalendar.getAllowedEventTypes(this.courseId); const promises: Promise[] = []; - const eventTypes = AddonCalendarHelper.instance.getEventTypeOptions(this.types); + const eventTypes = AddonCalendarHelper.getEventTypeOptions(this.types); if (!eventTypes.length) { - throw new CoreError(Translate.instance.instant('addon.calendar.nopermissiontoupdatecalendar')); + throw new CoreError(Translate.instant('addon.calendar.nopermissiontoupdatecalendar')); } if (this.eventId && !this.gotEventData) { // Editing an event, get the event data. Wait for sync first. - promises.push(AddonCalendarSync.instance.waitForSync(AddonCalendarSyncProvider.SYNC_ID).then(async () => { + promises.push(AddonCalendarSync.waitForSync(AddonCalendarSyncProvider.SYNC_ID).then(async () => { // Do not block if the scope is already destroyed. if (!this.isDestroyed && this.eventId) { - CoreSync.instance.blockOperation(AddonCalendarProvider.COMPONENT, this.eventId); + CoreSync.blockOperation(AddonCalendarProvider.COMPONENT, this.eventId); } let eventForm: AddonCalendarEvent | AddonCalendarOfflineEventDBRecord | undefined; // Get the event offline data if there's any. try { - eventForm = await AddonCalendarOffline.instance.getEvent(this.eventId!); + eventForm = await AddonCalendarOffline.getEvent(this.eventId!); this.hasOffline = true; } catch { @@ -188,7 +188,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { if (this.eventId! > 0) { // It's an online event. get its data from server. - const event = await AddonCalendar.instance.getEventById(this.eventId!); + const event = await AddonCalendar.getEventById(this.eventId!); if (!eventForm) { eventForm = event; // Use offline data first. @@ -217,7 +217,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { promises.push(this.fetchCategories()); } - this.showAll = CoreUtils.instance.isTrueOrOne(this.currentSite.getStoredConfig('calendar_adminseesall')) && + this.showAll = CoreUtils.isTrueOrOne(this.currentSite.getStoredConfig('calendar_adminseesall')) && accessInfo.canmanageentries; if (this.types.course || this.types.groups) { @@ -236,18 +236,18 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { this.eventTypes = eventTypes; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting data.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting data.'); this.error = true; } } protected async fetchCategories(): Promise { - this.categories = await CoreCourses.instance.getCategories(0, true); + this.categories = await CoreCourses.getCategories(0, true); } protected async fetchCourses(): Promise { // Get the courses. - let courses = await (this.showAll ? CoreCourses.instance.getCoursesByField() : CoreCourses.instance.getUserCourses()); + let courses = await (this.showAll ? CoreCourses.getCoursesByField() : CoreCourses.getUserCourses()); if (courses.length < 0) { this.courses = []; @@ -256,7 +256,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { } const courseFillterFullname = (course: CoreCourseSearchedData | CoreEnrolledCourseData): Promise => - CoreFilterHelper.instance.getFiltersAndFormatText(course.fullname, 'course', course.id) + CoreFilterHelper.getFiltersAndFormatText(course.fullname, 'course', course.id) .then((result) => { course.fullname = result.text; @@ -268,7 +268,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { if (this.showAll) { // Remove site home from the list of courses. - const siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); + const siteHomeId = CoreSites.getCurrentSiteHomeId(); if ('contacts' in courses[0]) { courses = (courses as CoreCourseSearchedData[]).filter((course) => course.id != siteHomeId); @@ -316,7 +316,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { const courseId = isOffline ? offlineEvent.courseid : onlineEvent.course?.id; this.form.controls.name.setValue(event.name); - this.form.controls.timestart.setValue(CoreTimeUtils.instance.toDatetimeFormat(event.timestart * 1000)); + this.form.controls.timestart.setValue(CoreTimeUtils.toDatetimeFormat(event.timestart * 1000)); this.form.controls.eventtype.setValue(event.eventtype); this.form.controls.categoryid.setValue(event.categoryid || ''); this.form.controls.courseid.setValue(courseId || ''); @@ -329,7 +329,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { // It's an offline event, use the data as it is. this.form.controls.duration.setValue(offlineEvent.duration); this.form.controls.timedurationuntil.setValue( - CoreTimeUtils.instance.toDatetimeFormat(((offlineEvent.timedurationuntil || 0) * 1000) || Date.now()), + CoreTimeUtils.toDatetimeFormat(((offlineEvent.timedurationuntil || 0) * 1000) || Date.now()), ); this.form.controls.timedurationminutes.setValue(offlineEvent.timedurationminutes || ''); this.form.controls.repeat.setValue(!!offlineEvent.repeat); @@ -340,13 +340,13 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { if (onlineEvent.timeduration > 0) { this.form.controls.duration.setValue(1); - this.form.controls.timedurationuntil.setValue(CoreTimeUtils.instance.toDatetimeFormat( + this.form.controls.timedurationuntil.setValue(CoreTimeUtils.toDatetimeFormat( (onlineEvent.timestart + onlineEvent.timeduration) * 1000, )); } else { // No duration. this.form.controls.duration.setValue(0); - this.form.controls.timedurationuntil.setValue(CoreTimeUtils.instance.toDatetimeFormat()); + this.form.controls.timedurationuntil.setValue(CoreTimeUtils.toDatetimeFormat()); } this.form.controls.timedurationminutes.setValue(''); @@ -367,19 +367,19 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { */ refreshData(refresher?: CustomEvent): void { const promises = [ - AddonCalendar.instance.invalidateAccessInformation(this.courseId), - AddonCalendar.instance.invalidateAllowedEventTypes(this.courseId), + AddonCalendar.invalidateAccessInformation(this.courseId), + AddonCalendar.invalidateAllowedEventTypes(this.courseId), ]; if (this.types) { if (this.types.category) { - promises.push(CoreCourses.instance.invalidateCategories(0, true)); + promises.push(CoreCourses.invalidateCategories(0, true)); } if (this.types.course || this.types.groups) { if (this.showAll) { - promises.push(CoreCourses.instance.invalidateCoursesByField()); + promises.push(CoreCourses.invalidateCoursesByField()); } else { - promises.push(CoreCourses.instance.invalidateUserCourses()); + promises.push(CoreCourses.invalidateUserCourses()); } } } @@ -401,14 +401,14 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { return; } - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { await this.loadGroups(courseId); this.groupControl.setValue(''); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting data.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting data.'); } modal.dismiss(); @@ -424,7 +424,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { this.loadingGroups = true; try { - this.groups = await CoreGroups.instance.getUserGroupsInCourse(courseId); + this.groups = await CoreGroups.getUserGroupsInCourse(courseId); this.courseGroupSet = true; } finally { this.loadingGroups = false; @@ -448,8 +448,8 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { async submit(): Promise { // Validate data. const formData = this.form.value; - const timeStartDate = CoreTimeUtils.instance.convertToTimestamp(formData.timestart); - const timeUntilDate = CoreTimeUtils.instance.convertToTimestamp(formData.timedurationuntil); + const timeStartDate = CoreTimeUtils.convertToTimestamp(formData.timestart); + const timeUntilDate = CoreTimeUtils.convertToTimestamp(formData.timedurationuntil); const timeDurationMinutes = parseInt(formData.timedurationminutes || '', 10); let error: string | undefined; @@ -469,7 +469,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { if (error) { // Show error and stop. - CoreDomUtils.instance.showErrorModal(Translate.instance.instant(error)); + CoreDomUtils.showErrorModal(Translate.instant(error)); return; } @@ -513,14 +513,14 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { } // Send the data. - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); let event: AddonCalendarEvent | AddonCalendarOfflineEventDBRecord; try { - const result = await AddonCalendar.instance.submitEvent(this.eventId, data); + const result = await AddonCalendar.submitEvent(this.eventId, data); event = result.event; - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, result.sent, this.currentSite.getId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, result.sent, this.currentSite.getId()); if (result.sent) { // Event created or edited, invalidate right days & months. @@ -528,7 +528,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { (data.repeateditall && this.otherEventsCount ? this.otherEventsCount + 1 : 1); try { - await AddonCalendarHelper.instance.refreshAfterChangeEvent(result.event, numberOfRepetitions); + await AddonCalendarHelper.refreshAfterChangeEvent(result.event, numberOfRepetitions); } catch { // Ignore errors. } @@ -536,7 +536,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { this.returnToList(event); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error sending data.'); + CoreDomUtils.showErrorModalDefault(error, 'Error sending data.'); } modal.dismiss(); @@ -574,10 +574,10 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { // Empty form. this.hasOffline = false; this.form.reset(this.originalData); - this.originalData = CoreUtils.instance.clone(this.form.value); + this.originalData = CoreUtils.clone(this.form.value); } else { this.originalData = undefined; // Avoid asking for confirmation. - CoreNavigator.instance.back(); + CoreNavigator.back(); } } @@ -586,16 +586,16 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { */ async discard(): Promise { try { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.areyousure')); + await CoreDomUtils.showConfirm(Translate.instant('core.areyousure')); try { - await AddonCalendarOffline.instance.deleteEvent(this.eventId!); + await AddonCalendarOffline.deleteEvent(this.eventId!); - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, this.currentSite.getId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, this.currentSite.getId()); this.returnToList(); } catch { // Shouldn't happen. - CoreDomUtils.instance.showErrorModal('Error discarding event.'); + CoreDomUtils.showErrorModal('Error discarding event.'); } } catch { // Ignore errors @@ -608,12 +608,12 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { * @return Resolved if we can leave it, rejected if not. */ async ionViewCanLeave(): Promise { - if (AddonCalendarHelper.instance.hasEventDataChanged(this.form.value, this.originalData)) { + if (AddonCalendarHelper.hasEventDataChanged(this.form.value, this.originalData)) { // Show confirmation if some data has been modified. - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.confirmcanceledit')); + await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); } - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, this.currentSite.getId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, this.currentSite.getId()); } /** @@ -621,7 +621,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy { */ protected unblockSync(): void { if (this.eventId) { - CoreSync.instance.unblockOperation(AddonCalendarProvider.COMPONENT, this.eventId); + CoreSync.unblockOperation(AddonCalendarProvider.COMPONENT, this.eventId); } } diff --git a/src/addons/calendar/pages/event/event.page.ts b/src/addons/calendar/pages/event/event.page.ts index 5a1597ca1..43dc8a502 100644 --- a/src/addons/calendar/pages/event/event.page.ts +++ b/src/addons/calendar/pages/event/event.page.ts @@ -93,14 +93,14 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { protected route: ActivatedRoute, ) { - this.notificationsEnabled = CoreLocalNotifications.instance.isAvailable(); - this.siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); - this.currentSiteId = CoreSites.instance.getCurrentSiteId(); + this.notificationsEnabled = CoreLocalNotifications.isAvailable(); + this.siteHomeId = CoreSites.getCurrentSiteHomeId(); + this.currentSiteId = CoreSites.getCurrentSiteId(); this.isSplitViewOn = this.svComponent?.outletActivated; // Check if site supports editing and deleting. No need to check allowed types, event.canedit already does it. - this.canEdit = AddonCalendar.instance.canEditEventsInSite(); - this.canDelete = AddonCalendar.instance.canDeleteEventsInSite(); + this.canEdit = AddonCalendar.canEditEventsInSite(); + this.canDelete = AddonCalendar.canDeleteEventsInSite(); this.asyncConstructor(); @@ -127,23 +127,23 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { ); // Refresh online status when changes. - this.onlineObserver = Network.instance.onChange().subscribe(() => { + this.onlineObserver = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { - this.isOnline = CoreApp.instance.isOnline(); + NgZone.run(() => { + this.isOnline = CoreApp.isOnline(); }); }); } protected async asyncConstructor(): Promise { if (this.notificationsEnabled) { - this.reminders = await AddonCalendar.instance.getEventReminders(this.eventId); - this.defaultTime = await AddonCalendar.instance.getDefaultNotificationTime() * 60; + this.reminders = await AddonCalendar.getEventReminders(this.eventId); + this.defaultTime = await AddonCalendar.getDefaultNotificationTime() * 60; // Calculate format to use. this.notificationFormat = - CoreTimeUtils.instance.fixFormatForDatetime(CoreTimeUtils.instance.convertPHPToMoment( - Translate.instance.instant('core.strftimedatetime'), + CoreTimeUtils.fixFormatForDatetime(CoreTimeUtils.convertPHPToMoment( + Translate.instant('core.strftimedatetime'), )); } } @@ -155,10 +155,10 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { this.route.queryParams.subscribe(() => { this.eventLoaded = false; - const eventId = CoreNavigator.instance.getRouteNumberParam('id'); + const eventId = CoreNavigator.getRouteNumberParam('id'); if (!eventId) { - CoreDomUtils.instance.showErrorModal('Event ID not supplied.'); - CoreNavigator.instance.back(); + CoreDomUtils.showErrorModal('Event ID not supplied.'); + CoreNavigator.back(); return; } @@ -178,18 +178,18 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ async fetchEvent(sync = false, showErrors = false): Promise { - const currentSite = CoreSites.instance.getCurrentSite(); - const canGetById = AddonCalendar.instance.isGetEventByIdAvailableInSite(); + const currentSite = CoreSites.getCurrentSite(); + const canGetById = AddonCalendar.isGetEventByIdAvailableInSite(); let deleted = false; - this.isOnline = CoreApp.instance.isOnline(); + this.isOnline = CoreApp.isOnline(); if (sync) { // Try to synchronize offline events. try { - const result = await AddonCalendarSync.instance.syncEvents(); + const result = await AddonCalendarSync.syncEvents(); if (result.warnings && result.warnings.length) { - CoreDomUtils.instance.showErrorModal(result.warnings[0]); + CoreDomUtils.showErrorModal(result.warnings[0]); } if (result.deleted && result.deleted.indexOf(this.eventId) != -1) { @@ -209,7 +209,7 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { } } catch (error) { if (showErrors) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errorsync', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errorsync', true); } } } @@ -222,15 +222,15 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { let event: AddonCalendarEvent | AddonCalendarEventBase | AddonCalendarGetEventsEvent; // Get the event data. if (canGetById) { - event = await AddonCalendar.instance.getEventById(this.eventId); + event = await AddonCalendar.getEventById(this.eventId); } else { - event = await AddonCalendar.instance.getEvent(this.eventId); + event = await AddonCalendar.getEvent(this.eventId); } - this.event = AddonCalendarHelper.instance.formatEventData(event); + this.event = AddonCalendarHelper.formatEventData(event); try { - const offlineEvent = AddonCalendarHelper.instance.formatOfflineEventData( - await AddonCalendarOffline.instance.getEvent(this.eventId), + const offlineEvent = AddonCalendarHelper.formatOfflineEventData( + await AddonCalendarOffline.getEvent(this.eventId), ); // There is offline data, apply it. @@ -242,9 +242,9 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { this.hasOffline = false; } - this.currentTime = CoreTimeUtils.instance.timestamp(); - this.notificationMin = CoreTimeUtils.instance.userDate(this.currentTime * 1000, 'YYYY-MM-DDTHH:mm', false); - this.notificationMax = CoreTimeUtils.instance.userDate( + this.currentTime = CoreTimeUtils.timestamp(); + this.notificationMin = CoreTimeUtils.userDate(this.currentTime * 1000, 'YYYY-MM-DDTHH:mm', false); + this.notificationMax = CoreTimeUtils.userDate( (this.event!.timestart + this.event!.timeduration) * 1000, 'YYYY-MM-DDTHH:mm', false, @@ -258,7 +258,7 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { if (this.event!.moduleIcon) { // It's a module event, translate the module name to the current language. - const name = CoreCourse.instance.translateModuleName(this.event!.modulename || ''); + const name = CoreCourse.translateModuleName(this.event!.modulename || ''); if (name.indexOf('core.mod_') === -1) { this.event!.modulename = name; } @@ -280,10 +280,10 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { this.courseUrl = this.event.course.viewurl; } else if (!canGetById && this.event.courseid ) { // Retrieve the course. - promises.push(CoreCourses.instance.getUserCourse(this.event.courseid, true).then((course) => { + promises.push(CoreCourses.getUserCourse(this.event.courseid, true).then((course) => { this.courseId = course.id; this.courseName = course.fullname; - this.courseUrl = currentSite ? CoreTextUtils.instance.concatenatePaths( + this.courseUrl = currentSite ? CoreTextUtils.concatenatePaths( currentSite.siteUrl, '/course/view.php?id=' + this.courseId, ) : ''; @@ -297,7 +297,7 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { // If it's a group event, get the name of the group. if (courseId && this.event.groupid) { - promises.push(CoreGroups.instance.getUserGroupsInCourse(courseId).then((groups) => { + promises.push(CoreGroups.getUserGroupsInCourse(courseId).then((groups) => { const group = groups.find((group) => group.id == this.event!.groupid); this.groupName = group ? group.name : ''; @@ -315,27 +315,27 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { if (this.event.location) { // Build a link to open the address in maps. - this.event.location = CoreTextUtils.instance.decodeHTML(this.event.location); - this.event.encodedLocation = CoreTextUtils.instance.buildAddressURL(this.event.location); + this.event.location = CoreTextUtils.decodeHTML(this.event.location); + this.event.encodedLocation = CoreTextUtils.buildAddressURL(this.event.location); } // Check if event was deleted in offine. - promises.push(AddonCalendarOffline.instance.isEventDeleted(this.eventId).then((deleted) => { + promises.push(AddonCalendarOffline.isEventDeleted(this.eventId).then((deleted) => { this.event!.deleted = deleted; return; })); // Re-calculate the formatted time so it uses the device date. - promises.push(AddonCalendar.instance.getCalendarTimeFormat().then(async (timeFormat) => { - this.event!.formattedtime = await AddonCalendar.instance.formatEventTime(this.event!, timeFormat); + promises.push(AddonCalendar.getCalendarTimeFormat().then(async (timeFormat) => { + this.event!.formattedtime = await AddonCalendar.formatEventTime(this.event!, timeFormat); return; })); await Promise.all(promises); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevent', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevent', true); } this.eventLoaded = true; @@ -347,9 +347,9 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { */ async addNotificationTime(): Promise { if (this.notificationTimeText && this.event && this.event.id) { - let notificationTime = CoreTimeUtils.instance.convertToTimestamp(this.notificationTimeText); + let notificationTime = CoreTimeUtils.convertToTimestamp(this.notificationTimeText); - const currentTime = CoreTimeUtils.instance.timestamp(); + const currentTime = CoreTimeUtils.timestamp(); const minute = Math.floor(currentTime / 60) * 60; // Check if the notification time is in the same minute as we are, so the notification is triggered. @@ -357,8 +357,8 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { notificationTime = currentTime + 1; } - await AddonCalendar.instance.addEventReminder(this.event, notificationTime); - this.reminders = await AddonCalendar.instance.getEventReminders(this.eventId); + await AddonCalendar.addEventReminder(this.event, notificationTime); + this.reminders = await AddonCalendar.getEventReminders(this.eventId); this.notificationTimeText = undefined; } } @@ -374,15 +374,15 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { e.stopPropagation(); try { - await CoreDomUtils.instance.showDeleteConfirm(); + await CoreDomUtils.showDeleteConfirm(); - const modal = await CoreDomUtils.instance.showModalLoading('core.deleting', true); + const modal = await CoreDomUtils.showModalLoading('core.deleting', true); try { - await AddonCalendar.instance.deleteEventReminder(id); - this.reminders = await AddonCalendar.instance.getEventReminders(this.eventId); + await AddonCalendar.deleteEventReminder(id); + this.reminders = await AddonCalendar.getEventReminders(this.eventId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error deleting reminder'); + CoreDomUtils.showErrorModalDefault(error, 'Error deleting reminder'); } finally { modal.dismiss(); } @@ -422,10 +422,10 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { const promises: Promise[] = []; - promises.push(AddonCalendar.instance.invalidateEvent(this.eventId)); - promises.push(AddonCalendar.instance.invalidateTimeFormat()); + promises.push(AddonCalendar.invalidateEvent(this.eventId)); + promises.push(AddonCalendar.invalidateTimeFormat()); - await CoreUtils.instance.allPromisesIgnoringErrors(promises); + await CoreUtils.allPromisesIgnoringErrors(promises); await this.fetchEvent(sync, showErrors); } @@ -436,7 +436,7 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { openEdit(): void { // Decide which navCtrl to use. If this page is inside a split view, use the split view's master nav. // @todo const navCtrl = this.svComponent ? this.svComponent.getMasterNav() : this.navCtrl; - CoreNavigator.instance.navigateToSitePath('/calendar/edit', { params: { eventId: this.eventId } }); + CoreNavigator.navigateToSitePath('/calendar/edit', { params: { eventId: this.eventId } }); } /** @@ -447,13 +447,13 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { return; } - const title = Translate.instance.instant('addon.calendar.deleteevent'); + const title = Translate.instant('addon.calendar.deleteevent'); const options: AlertOptions = {}; let message: string; if (this.event.eventcount > 1) { // It's a repeated event. - message = Translate.instance.instant( + message = Translate.instant( 'addon.calendar.confirmeventseriesdelete', { $a: { name: this.event.name, count: this.event.eventcount } }, ); @@ -464,39 +464,39 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { name: 'deleteall', checked: true, value: false, - label: Translate.instance.instant('addon.calendar.deleteoneevent'), + label: Translate.instant('addon.calendar.deleteoneevent'), }, { type: 'radio', name: 'deleteall', checked: false, value: true, - label: Translate.instance.instant('addon.calendar.deleteallevents'), + label: Translate.instant('addon.calendar.deleteallevents'), }, ]; } else { // Not repeated, display a simple confirm. - message = Translate.instance.instant('addon.calendar.confirmeventdelete', { $a: this.event.name }); + message = Translate.instant('addon.calendar.confirmeventdelete', { $a: this.event.name }); } let deleteAll = false; try { - deleteAll = await CoreDomUtils.instance.showConfirm(message, title, undefined, undefined, options); + deleteAll = await CoreDomUtils.showConfirm(message, title, undefined, undefined, options); } catch { // User canceled. return; } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - const sent = await AddonCalendar.instance.deleteEvent(this.event.id, this.event.name, deleteAll); + const sent = await AddonCalendar.deleteEvent(this.event.id, this.event.name, deleteAll); if (sent) { // Event deleted, invalidate right days & months. try { - await AddonCalendarHelper.instance.refreshAfterChangeEvent(this.event, deleteAll ? this.event.eventcount : 1); + await AddonCalendarHelper.refreshAfterChangeEvent(this.event, deleteAll ? this.event.eventcount : 1); } catch { // Ignore errors. } @@ -506,21 +506,21 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { CoreEvents.trigger(AddonCalendarProvider.DELETED_EVENT_EVENT, { eventId: this.eventId, sent: sent, - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); if (sent) { - CoreDomUtils.instance.showToast('addon.calendar.eventcalendareventdeleted', true, 3000); + CoreDomUtils.showToast('addon.calendar.eventcalendareventdeleted', true, 3000); // Event deleted, close the view. - if (CoreScreen.instance.isMobile) { - CoreNavigator.instance.back(); + if (CoreScreen.isMobile) { + CoreNavigator.back(); } } else { // Event deleted in offline, just mark it as deleted. this.event.deleted = true; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error deleting event.'); + CoreDomUtils.showErrorModalDefault(error, 'Error deleting event.'); } modal.dismiss(); @@ -534,21 +534,21 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { return; } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - await AddonCalendarOffline.instance.unmarkDeleted(this.event.id); + await AddonCalendarOffline.unmarkDeleted(this.event.id); // Trigger an event. CoreEvents.trigger(AddonCalendarProvider.UNDELETED_EVENT_EVENT, { eventId: this.eventId, - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); this.event.deleted = false; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error undeleting event.'); + CoreDomUtils.showErrorModalDefault(error, 'Error undeleting event.'); } modal.dismiss(); @@ -566,11 +566,11 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy { } if (data.deleted && data.deleted.indexOf(this.eventId) != -1) { - CoreDomUtils.instance.showToast('addon.calendar.eventcalendareventdeleted', true, 3000); + CoreDomUtils.showToast('addon.calendar.eventcalendareventdeleted', true, 3000); // Event was deleted, close the view. - if (CoreScreen.instance.isMobile) { - CoreNavigator.instance.back(); + if (CoreScreen.isMobile) { + CoreNavigator.back(); } } else if (data.events && (!isManual || data.source != 'event')) { const event = data.events.find((ev) => ev.id == this.eventId); diff --git a/src/addons/calendar/pages/index/index.page.ts b/src/addons/calendar/pages/index/index.page.ts index 600dc8369..1e90f5ccc 100644 --- a/src/addons/calendar/pages/index/index.page.ts +++ b/src/addons/calendar/pages/index/index.page.ts @@ -86,7 +86,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { constructor( protected route: ActivatedRoute, ) { - this.currentSiteId = CoreSites.instance.getCurrentSiteId(); + this.currentSiteId = CoreSites.getCurrentSiteId(); // Listen for events added. When an event is added, reload the data. this.newEventObserver = CoreEvents.on( @@ -140,7 +140,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { // Update the "hasOffline" property if an event deleted in offline is restored. this.undeleteEventObserver = CoreEvents.on(AddonCalendarProvider.UNDELETED_EVENT_EVENT, async () => { - this.hasOffline = await AddonCalendarOffline.instance.hasOfflineData(); + this.hasOffline = await AddonCalendarOffline.hasOfflineData(); }, this.currentSiteId); this.filterChangedObserver = CoreEvents.on( @@ -149,15 +149,15 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { this.filter = filterData; // Course viewed has changed, check if the user can create events for this course calendar. - this.canCreate = await AddonCalendarHelper.instance.canEditEvents(this.filter['courseId']); + this.canCreate = await AddonCalendarHelper.canEditEvents(this.filter['courseId']); }, ); // Refresh online status when changes. - this.onlineObserver = Network.instance.onChange().subscribe(() => { + this.onlineObserver = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { - this.isOnline = CoreApp.instance.isOnline(); + NgZone.run(() => { + this.isOnline = CoreApp.isOnline(); }); }); } @@ -166,14 +166,14 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { * View loaded. */ ngOnInit(): void { - this.notificationsEnabled = CoreLocalNotifications.instance.isAvailable(); + this.notificationsEnabled = CoreLocalNotifications.isAvailable(); this.route.queryParams.subscribe(() => { - this.eventId = CoreNavigator.instance.getRouteNumberParam('eventId'); - this.filter.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || -1; - this.year = CoreNavigator.instance.getRouteNumberParam('year'); - this.month = CoreNavigator.instance.getRouteNumberParam('month'); - this.loadUpcoming = !!CoreNavigator.instance.getRouteBooleanParam('upcoming'); + this.eventId = CoreNavigator.getRouteNumberParam('eventId'); + this.filter.courseId = CoreNavigator.getRouteNumberParam('courseId') || -1; + this.year = CoreNavigator.getRouteNumberParam('year'); + this.month = CoreNavigator.getRouteNumberParam('month'); + this.loadUpcoming = !!CoreNavigator.getRouteBooleanParam('upcoming'); this.showCalendar = !this.loadUpcoming; this.filter.filtered = this.filter.courseId > 0; @@ -196,14 +196,14 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { async fetchData(sync?: boolean, showErrors?: boolean): Promise { this.syncIcon = CoreConstants.ICON_LOADING; - this.isOnline = CoreApp.instance.isOnline(); + this.isOnline = CoreApp.isOnline(); if (sync) { // Try to synchronize offline events. try { - const result = await AddonCalendarSync.instance.syncEvents(); + const result = await AddonCalendarSync.syncEvents(); if (result.warnings && result.warnings.length) { - CoreDomUtils.instance.showErrorModal(result.warnings[0]); + CoreDomUtils.showErrorModal(result.warnings[0]); } if (result.updated) { @@ -218,7 +218,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { } } catch (error) { if (showErrors) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errorsync', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errorsync', true); } } } @@ -229,21 +229,21 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { this.hasOffline = false; // Load courses for the popover. - promises.push(CoreCoursesHelper.instance.getCoursesForPopover(this.filter.courseId).then((data) => { + promises.push(CoreCoursesHelper.getCoursesForPopover(this.filter.courseId).then((data) => { this.courses = data.courses; return; })); // Check if user can create events. - promises.push(AddonCalendarHelper.instance.canEditEvents(this.filter.courseId).then((canEdit) => { + promises.push(AddonCalendarHelper.canEditEvents(this.filter.courseId).then((canEdit) => { this.canCreate = canEdit; return; })); // Check if there is offline data. - promises.push(AddonCalendarOffline.instance.hasOfflineData().then((hasOffline) => { + promises.push(AddonCalendarOffline.hasOfflineData().then((hasOffline) => { this.hasOffline = hasOffline; return; @@ -251,7 +251,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { await Promise.all(promises); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); } this.loaded = true; @@ -290,7 +290,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { const promises: Promise[] = []; - promises.push(AddonCalendar.instance.invalidateAllowedEventTypes()); + promises.push(AddonCalendar.invalidateAllowedEventTypes()); // Refresh the sub-component. if (this.showCalendar && this.calendarComponent) { @@ -312,7 +312,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { // It's an offline event, go to the edit page. this.openEdit(eventId); } else { - CoreNavigator.instance.navigateToSitePath('/calendar/event', { params: { id: eventId } }); + CoreNavigator.navigateToSitePath('/calendar/event', { params: { id: eventId } }); } } @@ -332,7 +332,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { params[key] = this.filter[key]; }); - CoreNavigator.instance.navigateToSitePath('/calendar/day', { params }); + CoreNavigator.navigateToSitePath('/calendar/day', { params }); } /** @@ -341,7 +341,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { * @param event Event. */ async openFilter(event: MouseEvent): Promise { - const popover = await PopoverController.instance.create({ + const popover = await PopoverController.create({ component: AddonCalendarFilterPopoverComponent, componentProps: { courses: this.courses, @@ -367,14 +367,14 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy { params.courseId = this.filter.courseId; } - CoreNavigator.instance.navigateToSitePath('/calendar/edit', { params }); + CoreNavigator.navigateToSitePath('/calendar/edit', { params }); } /** * Open calendar events settings. */ openSettings(): void { - CoreNavigator.instance.navigateToSitePath('/calendar/settings'); + CoreNavigator.navigateToSitePath('/calendar/settings'); } /** diff --git a/src/addons/calendar/pages/list/list.module.ts b/src/addons/calendar/pages/list/list.module.ts index 291795211..cae527712 100644 --- a/src/addons/calendar/pages/list/list.module.ts +++ b/src/addons/calendar/pages/list/list.module.ts @@ -43,8 +43,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; diff --git a/src/addons/calendar/pages/list/list.page.ts b/src/addons/calendar/pages/list/list.page.ts index b45b49595..a6f6ab0f9 100644 --- a/src/addons/calendar/pages/list/list.page.ts +++ b/src/addons/calendar/pages/list/list.page.ts @@ -103,14 +103,14 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { constructor() { - this.siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); - this.notificationsEnabled = CoreLocalNotifications.instance.isAvailable(); - this.currentSiteId = CoreSites.instance.getCurrentSiteId(); + this.siteHomeId = CoreSites.getCurrentSiteHomeId(); + this.notificationsEnabled = CoreLocalNotifications.isAvailable(); + this.currentSiteId = CoreSites.getCurrentSiteId(); if (this.notificationsEnabled) { // Re-schedule events if default time changes. this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => { - AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); + AddonCalendar.scheduleEventsNotifications(this.onlineEvents); }, this.currentSiteId); } @@ -225,7 +225,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { this.filter = data; // Course viewed has changed, check if the user can create events for this course calendar. - this.canCreate = await AddonCalendarHelper.instance.canEditEvents(this.filter.courseId); + this.canCreate = await AddonCalendarHelper.canEditEvents(this.filter.courseId); this.filterEvents(); @@ -233,10 +233,10 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { }); // Refresh online status when changes. - this.onlineObserver = Network.instance.onChange().subscribe(() => { + this.onlineObserver = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { - this.isOnline = CoreApp.instance.isOnline(); + NgZone.run(() => { + this.isOnline = CoreApp.isOnline(); }); }); } @@ -245,8 +245,8 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { * View loaded. */ async ngOnInit(): Promise { - this.eventId = CoreNavigator.instance.getRouteNumberParam('eventId'); - this.filter.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || -1; + this.eventId = CoreNavigator.getRouteNumberParam('eventId'); + this.filter.courseId = CoreNavigator.getRouteNumberParam('courseId') || -1; if (this.eventId) { // There is an event to load, open the event in a new state. @@ -272,10 +272,10 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { */ protected emptySplitView(): void { // Empty details. - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/event') || - CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/edit'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/calendar/list/event') || + CoreNavigator.isCurrentPathInTablet('**/calendar/list/edit'); if (splitViewLoaded) { - CoreNavigator.instance.navigate('../'); + CoreNavigator.navigate('../'); } } @@ -288,17 +288,17 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ async fetchData(refresh = false, sync = false, showErrors = false): Promise { - this.initialTime = CoreTimeUtils.instance.timestamp(); + this.initialTime = CoreTimeUtils.timestamp(); this.daysLoaded = 0; this.emptyEventsTimes = 0; - this.isOnline = CoreApp.instance.isOnline(); + this.isOnline = CoreApp.isOnline(); if (sync) { // Try to synchronize offline events. try { - const result = await AddonCalendarSync.instance.syncEvents(); + const result = await AddonCalendarSync.syncEvents(); if (result.warnings && result.warnings.length) { - CoreDomUtils.instance.showErrorModal(result.warnings[0]); + CoreDomUtils.showErrorModal(result.warnings[0]); } if (result.updated) { @@ -313,7 +313,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { } } catch (error) { if (showErrors) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errorsync', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errorsync', true); } } } @@ -323,34 +323,34 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { this.hasOffline = false; - promises.push(AddonCalendarHelper.instance.canEditEvents(this.filter.courseId).then((canEdit) => { + promises.push(AddonCalendarHelper.canEditEvents(this.filter.courseId).then((canEdit) => { this.canCreate = canEdit; return; })); // Load courses for the popover. - promises.push(CoreCoursesHelper.instance.getCoursesForPopover(this.filter.courseId).then((result) => { + promises.push(CoreCoursesHelper.getCoursesForPopover(this.filter.courseId).then((result) => { this.courses = result.courses; return this.fetchEvents(refresh); })); // Get offline events. - promises.push(AddonCalendarOffline.instance.getAllEditedEvents().then((offlineEvents) => { + promises.push(AddonCalendarOffline.getAllEditedEvents().then((offlineEvents) => { this.hasOffline = this.hasOffline || !!offlineEvents.length; // Format data and sort by timestart. const events: AddonCalendarEventToDisplay[] = offlineEvents.map((event) => - AddonCalendarHelper.instance.formatOfflineEventData(event)); + AddonCalendarHelper.formatOfflineEventData(event)); - this.offlineEvents = AddonCalendarHelper.instance.sortEvents(events); + this.offlineEvents = AddonCalendarHelper.sortEvents(events); return; })); // Get events deleted in offline. - promises.push(AddonCalendarOffline.instance.getAllDeletedEventsIds().then((ids) => { + promises.push(AddonCalendarOffline.getAllDeletedEventsIds().then((ids) => { this.hasOffline = this.hasOffline || !!ids.length; this.deletedEvents = ids; @@ -359,7 +359,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { await Promise.all(promises); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); } this.eventsLoaded = true; @@ -377,7 +377,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { try { const onlineEventsTemp = - await AddonCalendar.instance.getEventsList(this.initialTime, this.daysLoaded, AddonCalendarProvider.DAYS_INTERVAL); + await AddonCalendar.getEventsList(this.initialTime, this.daysLoaded, AddonCalendarProvider.DAYS_INTERVAL); if (onlineEventsTemp.length === 0) { this.emptyEventsTimes++; @@ -395,7 +395,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { return this.fetchEvents(); } } else { - const onlineEvents = onlineEventsTemp.map((event) => AddonCalendarHelper.instance.formatEventData(event)); + const onlineEvents = onlineEventsTemp.map((event) => AddonCalendarHelper.formatEventData(event)); // Get the merged events of this period. const events = this.mergeEvents(onlineEvents); @@ -407,8 +407,8 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { this.events = events; } else { // Filter events with same ID. Repeated events are returned once per WS call, show them only once. - this.onlineEvents = CoreUtils.instance.mergeArraysWithoutDuplicates(this.onlineEvents, onlineEvents, 'id'); - this.events = CoreUtils.instance.mergeArraysWithoutDuplicates(this.events, events, 'id'); + this.onlineEvents = CoreUtils.mergeArraysWithoutDuplicates(this.onlineEvents, onlineEvents, 'id'); + this.events = CoreUtils.mergeArraysWithoutDuplicates(this.events, events, 'id'); } this.filterEvents(); @@ -420,7 +420,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { this.canLoadMore = true; // Schedule notifications for the events retrieved (might have new events). - AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); + AddonCalendar.scheduleEventsNotifications(this.onlineEvents); this.daysLoaded += AddonCalendarProvider.DAYS_INTERVAL; } @@ -429,7 +429,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { // @todo: Infinite loading is not working if content is not high enough. // this.content.resize(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.loadMoreError = true; // Set to prevent infinite calls with infinite-loading. } @@ -454,7 +454,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { } protected filterEvents(): void { - this.filteredEvents = AddonCalendarHelper.instance.getFilteredEvents(this.events, this.filter, this.categories); + this.filteredEvents = AddonCalendarHelper.getFilteredEvents(this.events, this.filter, this.categories); } /** @@ -482,7 +482,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { */ protected async loadCategories(): Promise { try { - const cats = await CoreCourses.instance.getCategories(0, true); + const cats = await CoreCourses.getCategories(0, true); this.categoriesRetrieved = true; this.categories = {}; // Index categories by ID. @@ -539,7 +539,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { // Merge both arrays and sort them. result = result.concat(periodOfflineEvents); - return AddonCalendarHelper.instance.sortEvents(result); + return AddonCalendarHelper.sortEvents(result); } /** @@ -573,11 +573,11 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { const promises: Promise[] = []; - promises.push(AddonCalendar.instance.invalidateEventsList()); - promises.push(AddonCalendar.instance.invalidateAllowedEventTypes()); + promises.push(AddonCalendar.invalidateEventsList()); + promises.push(AddonCalendar.invalidateAllowedEventTypes()); if (this.categoriesRetrieved) { - promises.push(CoreCourses.instance.invalidateCategories(0, true)); + promises.push(CoreCourses.invalidateCategories(0, true)); this.categoriesRetrieved = false; } @@ -624,7 +624,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { * @param event Event. */ async openFilter(event: MouseEvent): Promise { - const popover = await PopoverController.instance.create({ + const popover = await PopoverController.create({ component: AddonCalendarFilterPopoverComponent, componentProps: { courses: this.courses, @@ -652,17 +652,17 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { params.courseId = this.filter.courseId; } - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/event') || - CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/edit'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/calendar/list/event') || + CoreNavigator.isCurrentPathInTablet('**/calendar/list/edit'); const path = (splitViewLoaded ? '../' : '') + 'edit'; - CoreNavigator.instance.navigate(path, { params }); + CoreNavigator.navigate(path, { params }); } /** * Open calendar events settings. */ openSettings(): void { - CoreNavigator.instance.navigateToSitePath('/calendar/settings'); + CoreNavigator.navigateToSitePath('/calendar/settings'); } /** @@ -677,10 +677,10 @@ export class AddonCalendarListPage implements OnInit, OnDestroy { // It's an offline event, go to the edit page. this.openEdit(eventId); } else { - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/event') || - CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/edit'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/calendar/list/event') || + CoreNavigator.isCurrentPathInTablet('**/calendar/list/edit'); const path = (splitViewLoaded ? '../' : '') + 'event'; - CoreNavigator.instance.navigate(path, { params: { + CoreNavigator.navigate(path, { params: { id: eventId, } }); } diff --git a/src/addons/calendar/pages/settings/settings.ts b/src/addons/calendar/pages/settings/settings.ts index 11e6057ed..91dede6e4 100644 --- a/src/addons/calendar/pages/settings/settings.ts +++ b/src/addons/calendar/pages/settings/settings.ts @@ -32,7 +32,7 @@ export class AddonCalendarSettingsPage implements OnInit { * View loaded. */ async ngOnInit(): Promise { - this.defaultTime = await AddonCalendar.instance.getDefaultNotificationTime(); + this.defaultTime = await AddonCalendar.getDefaultNotificationTime(); } /** @@ -41,12 +41,12 @@ export class AddonCalendarSettingsPage implements OnInit { * @param newTime New time. */ updateDefaultTime(newTime: number): void { - AddonCalendar.instance.setDefaultNotificationTime(newTime); + AddonCalendar.setDefaultNotificationTime(newTime); CoreEvents.trigger( AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, { time: newTime }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } diff --git a/src/addons/calendar/services/calendar-helper.ts b/src/addons/calendar/services/calendar-helper.ts index e276b98f3..881f133e1 100644 --- a/src/addons/calendar/services/calendar-helper.ts +++ b/src/addons/calendar/services/calendar-helper.ts @@ -64,7 +64,7 @@ export class AddonCalendarHelperProvider { */ getEventIcon(eventType: AddonCalendarEventType): string { if (this.eventTypeIcons.length == 0) { - CoreUtils.instance.enumKeys(AddonCalendarEventType).forEach((name) => { + CoreUtils.enumKeys(AddonCalendarEventType).forEach((name) => { const value = AddonCalendarEventType[name]; this.eventTypeIcons[value] = AddonCalendarEventIcons[name]; }); @@ -104,12 +104,12 @@ export class AddonCalendarHelperProvider { */ async canEditEvents(courseId?: number, siteId?: string): Promise { try { - const canEdit = await AddonCalendar.instance.canEditEvents(siteId); + const canEdit = await AddonCalendar.canEditEvents(siteId); if (!canEdit) { return false; } - const types = await AddonCalendar.instance.getAllowedEventTypes(courseId, siteId); + const types = await AddonCalendar.getAllowedEventTypes(courseId, siteId); return Object.keys(types).length > 0; } catch { @@ -129,7 +129,7 @@ export class AddonCalendarHelperProvider { ): { [monthId: string]: { [day: number]: AddonCalendarEventToDisplay[] } } { // Format data. const events: AddonCalendarEventToDisplay[] = offlineEvents.map((event) => - AddonCalendarHelper.instance.formatOfflineEventData(event)); + AddonCalendarHelper.formatOfflineEventData(event)); const result = {}; @@ -180,7 +180,7 @@ export class AddonCalendarHelperProvider { userid: event.userid, timemodified: event.timemodified, eventIcon: this.getEventIcon(event.eventtype), - formattedType: AddonCalendar.instance.getEventType(event), + formattedType: AddonCalendar.getEventType(event), modulename: event.modulename, format: 1, visible: 1, @@ -188,11 +188,11 @@ export class AddonCalendarHelperProvider { }; if (event.modulename) { - eventFormatted.eventIcon = CoreCourse.instance.getModuleIconSrc(event.modulename); + eventFormatted.eventIcon = CoreCourse.getModuleIconSrc(event.modulename); eventFormatted.moduleIcon = eventFormatted.eventIcon; } - eventFormatted.formattedType = AddonCalendar.instance.getEventType(event); + eventFormatted.formattedType = AddonCalendar.getEventType(event); // Calculate context. if ('course' in event) { @@ -345,10 +345,10 @@ export class AddonCalendarHelperProvider { month: number, siteId?: string, ): Promise<{ daynames: Partial[]; weeks: Partial[] }> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Get starting week day user preference, fallback to site configuration. let startWeekDayStr = site.getStoredConfig('calendar_startwday'); - startWeekDayStr = await CoreConfig.instance.get(AddonCalendarProvider.STARTING_WEEK_DAY, startWeekDayStr); + startWeekDayStr = await CoreConfig.get(AddonCalendarProvider.STARTING_WEEK_DAY, startWeekDayStr); const startWeekDay = parseInt(startWeekDayStr, 10); const today = moment(); @@ -531,7 +531,7 @@ export class AddonCalendarHelperProvider { const eventCourse = (event.course && event.course.id) || event.courseid; // Show the event if it is from site home or if it matches the selected course. - return !!eventCourse && (eventCourse == CoreSites.instance.getCurrentSiteHomeId() || eventCourse == courseId); + return !!eventCourse && (eventCourse == CoreSites.getCurrentSiteHomeId() || eventCourse == courseId); } /** @@ -543,13 +543,13 @@ export class AddonCalendarHelperProvider { * @return Resolved when done. */ async refreshAfterChangeEvents(events: AddonCalendarSyncInvalidateEvent[], siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const fetchTimestarts: number[] = []; const invalidateTimestarts: number[] = []; const promises: Promise[] = []; // Always fetch upcoming events. - promises.push(AddonCalendar.instance.getUpcomingEvents(undefined, undefined, true, site.id)); + promises.push(AddonCalendar.getUpcomingEvents(undefined, undefined, true, site.id)); promises.concat(events.map(async (eventData) => { @@ -557,7 +557,7 @@ export class AddonCalendarHelperProvider { // Not repeated. fetchTimestarts.push(eventData.timestart); - return AddonCalendar.instance.invalidateEvent(eventData.id); + return AddonCalendar.invalidateEvent(eventData.id); } if (eventData.repeatid) { @@ -573,10 +573,10 @@ export class AddonCalendarHelperProvider { // Get the repeated events to invalidate them. const repeatedEvents = - await AddonCalendar.instance.getLocalEventsByRepeatIdFromLocalDb(eventData.repeatid, site.id); + await AddonCalendar.getLocalEventsByRepeatIdFromLocalDb(eventData.repeatid, site.id); - await CoreUtils.instance.allPromises(repeatedEvents.map((event) => - AddonCalendar.instance.invalidateEvent(event.id!))); + await CoreUtils.allPromises(repeatedEvents.map((event) => + AddonCalendar.invalidateEvent(event.id!))); return; } @@ -596,11 +596,11 @@ export class AddonCalendarHelperProvider { })); try { - await CoreUtils.instance.allPromisesIgnoringErrors(promises); + await CoreUtils.allPromisesIgnoringErrors(promises); } finally { const treatedMonths = {}; const treatedDays = {}; - const finalPromises: Promise[] =[AddonCalendar.instance.invalidateAllUpcomingEvents()]; + const finalPromises: Promise[] =[AddonCalendar.invalidateAllUpcomingEvents()]; // Fetch months and days. fetchTimestarts.map((fetchTime) => { @@ -611,7 +611,7 @@ export class AddonCalendarHelperProvider { // Month not refetch or invalidated already, do it now. treatedMonths[monthId] = true; - finalPromises.push(AddonCalendar.instance.getMonthlyEvents( + finalPromises.push(AddonCalendar.getMonthlyEvents( day.year(), day.month() + 1, undefined, @@ -626,7 +626,7 @@ export class AddonCalendarHelperProvider { // Dat not refetch or invalidated already, do it now. treatedDays[dayId] = true; - finalPromises.push(AddonCalendar.instance.getDayEvents( + finalPromises.push(AddonCalendar.getDayEvents( day.year(), day.month() + 1, day.date(), @@ -647,7 +647,7 @@ export class AddonCalendarHelperProvider { // Month not refetch or invalidated already, do it now. treatedMonths[monthId] = true; - finalPromises.push(AddonCalendar.instance.invalidateMonthlyEvents(day.year(), day.month() + 1, site.id)); + finalPromises.push(AddonCalendar.invalidateMonthlyEvents(day.year(), day.month() + 1, site.id)); } const dayId = monthId + '#' + day.date(); @@ -655,7 +655,7 @@ export class AddonCalendarHelperProvider { // Dat not refetch or invalidated already, do it now. treatedDays[dayId] = true; - finalPromises.push(AddonCalendar.instance.invalidateDayEvents( + finalPromises.push(AddonCalendar.invalidateDayEvents( day.year(), day.month() + 1, day.date(), @@ -664,7 +664,7 @@ export class AddonCalendarHelperProvider { } }); - await CoreUtils.instance.allPromisesIgnoringErrors(finalPromises); + await CoreUtils.allPromisesIgnoringErrors(finalPromises); } } @@ -714,7 +714,7 @@ export class AddonCalendarHelperProvider { } -export class AddonCalendarHelper extends makeSingleton(AddonCalendarHelperProvider) {} +export const AddonCalendarHelper = makeSingleton(AddonCalendarHelperProvider); /** * Calculated data for Calendar filtering. diff --git a/src/addons/calendar/services/calendar-offline.ts b/src/addons/calendar/services/calendar-offline.ts index eb8d04518..d34586f91 100644 --- a/src/addons/calendar/services/calendar-offline.ts +++ b/src/addons/calendar/services/calendar-offline.ts @@ -39,7 +39,7 @@ export class AddonCalendarOfflineProvider { * @return Promise resolved if deleted, rejected if failure. */ async deleteEvent(eventId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions: SQLiteDBRecordValues = { id: eventId, @@ -62,7 +62,7 @@ export class AddonCalendarOfflineProvider { const result = await Promise.all(promises); - return CoreUtils.instance.mergeArraysWithoutDuplicates(result[0], result[1]); + return CoreUtils.mergeArraysWithoutDuplicates(result[0], result[1]); } /** @@ -72,7 +72,7 @@ export class AddonCalendarOfflineProvider { * @return Promise resolved with all the events deleted in offline. */ async getAllDeletedEvents(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecords(DELETED_EVENTS_TABLE); } @@ -96,7 +96,7 @@ export class AddonCalendarOfflineProvider { * @return Promise resolved with events. */ async getAllEditedEvents(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecords(EVENTS_TABLE); } @@ -121,7 +121,7 @@ export class AddonCalendarOfflineProvider { * @return Promise resolved with the deleted event. */ async getDeletedEvent(eventId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions: SQLiteDBRecordValues = { id: eventId, }; @@ -137,7 +137,7 @@ export class AddonCalendarOfflineProvider { * @return Promise resolved with the event. */ async getEvent(eventId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions: SQLiteDBRecordValues = { id: eventId, }; @@ -201,7 +201,7 @@ export class AddonCalendarOfflineProvider { * @return Promise resolved when done. */ async markDeleted(eventId: number, name: string, deleteAll?: boolean, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const event: AddonCalendarOfflineDeletedEventDBRecord = { id: eventId, name: name || '', @@ -227,7 +227,7 @@ export class AddonCalendarOfflineProvider { timeCreated?: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); timeCreated = timeCreated || Date.now(); const event: AddonCalendarOfflineEventDBRecord = { id: eventId || -timeCreated, @@ -263,7 +263,7 @@ export class AddonCalendarOfflineProvider { * @return Promise resolved if deleted, rejected if failure. */ async unmarkDeleted(eventId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions: SQLiteDBRecordValues = { id: eventId, }; @@ -272,5 +272,4 @@ export class AddonCalendarOfflineProvider { } } -export class AddonCalendarOffline extends makeSingleton(AddonCalendarOfflineProvider) {} - +export const AddonCalendarOffline = makeSingleton(AddonCalendarOfflineProvider); diff --git a/src/addons/calendar/services/calendar-sync.ts b/src/addons/calendar/services/calendar-sync.ts index 9f9c80a36..ed43cc834 100644 --- a/src/addons/calendar/services/calendar-sync.ts +++ b/src/addons/calendar/services/calendar-sync.ts @@ -81,7 +81,7 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const needed = await this.isSyncNeeded(AddonCalendarSyncProvider.SYNC_ID, siteId); @@ -97,7 +97,7 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.isSyncing(AddonCalendarSyncProvider.SYNC_ID, siteId)) { // There's already a sync ongoing for this site, return the promise. @@ -127,32 +127,32 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider 0) { - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // Cannot sync in offline. throw new CoreNetworkError(); } const promises = eventIds.map((eventId) => this.syncOfflineEvent(eventId, result, siteId)); - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); if (result.updated) { // Data has been sent to server. Now invalidate the WS calls. const promises = [ - AddonCalendar.instance.invalidateEventsList(siteId), - AddonCalendarHelper.instance.refreshAfterChangeEvents(result.toinvalidate, siteId), + AddonCalendar.invalidateEventsList(siteId), + AddonCalendarHelper.refreshAfterChangeEvents(result.toinvalidate, siteId), ]; - await CoreUtils.instance.ignoreErrors(Promise.all(promises)); + await CoreUtils.ignoreErrors(Promise.all(promises)); } } // Sync finished, set sync time. - await CoreUtils.instance.ignoreErrors(this.setSyncTime(AddonCalendarSyncProvider.SYNC_ID, siteId)); + await CoreUtils.ignoreErrors(this.setSyncTime(AddonCalendarSyncProvider.SYNC_ID, siteId)); // All done, return the result. return result; @@ -169,21 +169,21 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider { // Verify that event isn't blocked. - if (CoreSync.instance.isBlocked(AddonCalendarProvider.COMPONENT, eventId, siteId)) { + if (CoreSync.isBlocked(AddonCalendarProvider.COMPONENT, eventId, siteId)) { this.logger.debug('Cannot sync event ' + eventId + ' because it is blocked.'); - throw new CoreSyncBlockedError(Translate.instance.instant( + throw new CoreSyncBlockedError(Translate.instant( 'core.errorsyncblocked', - { $a: Translate.instance.instant('addon.calendar.calendarevent') }, + { $a: Translate.instant('addon.calendar.calendarevent') }, )); } // First of all, check if the event has been deleted. try { - const data = await AddonCalendarOffline.instance.getDeletedEvent(eventId, siteId); + const data = await AddonCalendarOffline.getDeletedEvent(eventId, siteId); // Delete the event. try { - await AddonCalendar.instance.deleteEventOnline(data.id, !!data.repeat, siteId); + await AddonCalendar.deleteEventOnline(data.id, !!data.repeat, siteId); result.updated = true; result.deleted.push(eventId); @@ -191,13 +191,13 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider[] = []; - promises.push(AddonCalendarOffline.instance.unmarkDeleted(eventId, siteId)); - promises.push(AddonCalendarOffline.instance.deleteEvent(eventId, siteId).catch(() => { + promises.push(AddonCalendarOffline.unmarkDeleted(eventId, siteId)); + promises.push(AddonCalendarOffline.deleteEvent(eventId, siteId).catch(() => { // Ignore errors, maybe there was no edit data. })); // We need the event data to invalidate it. Get it from local DB. - promises.push(AddonCalendar.instance.getEventFromLocalDb(eventId, siteId).then((event) => { + promises.push(AddonCalendar.getEventFromLocalDb(eventId, siteId).then((event) => { result.toinvalidate.push({ id: event.id, repeatid: event.repeatid, @@ -213,7 +213,7 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider[] = []; - promises.push(AddonCalendarOffline.instance.unmarkDeleted(eventId, siteId)); - promises.push(AddonCalendarOffline.instance.deleteEvent(eventId, siteId).catch(() => { + promises.push(AddonCalendarOffline.unmarkDeleted(eventId, siteId)); + promises.push(AddonCalendarOffline.deleteEvent(eventId, siteId).catch(() => { // Ignore errors, maybe there was no edit data. })); await Promise.all(promises); // Event deleted, add a warning. - result.warnings.push(Translate.instance.instant('core.warningofflinedatadeleted', { - component: Translate.instance.instant('addon.calendar.calendarevent'), + result.warnings.push(Translate.instant('core.warningofflinedatadeleted', { + component: Translate.instant('addon.calendar.calendarevent'), name: data.name, - error: CoreTextUtils.instance.getErrorMessageFromError(error), + error: CoreTextUtils.getErrorMessageFromError(error), })); } @@ -243,11 +243,11 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider 0 ? eventId : 0, data, siteId); + const newEvent = await AddonCalendar.submitEventOnline(eventId > 0 ? eventId : 0, data, siteId); result.updated = true; result.events.push(newEvent); @@ -274,10 +274,10 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.canDeleteEventsInSite(site); } catch { @@ -129,7 +129,7 @@ export class AddonCalendarProvider { * @since 3.3 */ canDeleteEventsInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.wsAvailable('core_calendar_delete_calendar_events'); } @@ -143,7 +143,7 @@ export class AddonCalendarProvider { */ async canEditEvents(siteId?: string): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.canEditEventsInSite(site); } catch { @@ -159,7 +159,7 @@ export class AddonCalendarProvider { * @since 3.7.1 */ canEditEventsInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); // The WS to create/edit events requires a fix that was integrated in 3.7.1. return !!site?.isVersionGreaterEqualThan('3.7.1'); @@ -174,7 +174,7 @@ export class AddonCalendarProvider { */ async canViewMonth(siteId?: string): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.canViewMonthInSite(site); } catch { @@ -190,7 +190,7 @@ export class AddonCalendarProvider { * @since 3.4 */ canViewMonthInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.wsAvailable('core_calendar_get_calendar_monthly_view'); } @@ -212,7 +212,7 @@ export class AddonCalendarProvider { * @return Promise resolved when done. */ async cleanExpiredEvents(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (this.canViewMonthInSite(site)) { // Site supports monthly view, don't clean expired events because user can see past events. return; @@ -220,7 +220,7 @@ export class AddonCalendarProvider { const events = await site.getDb().getRecordsSelect( EVENTS_TABLE, 'timestart + timeduration < ?', - [CoreTimeUtils.instance.timestamp()], + [CoreTimeUtils.timestamp()], ); await Promise.all(events.map((event) => this.deleteLocalEvent(event.id!, siteId))); @@ -244,25 +244,25 @@ export class AddonCalendarProvider { siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Function to store the submission to be synchronized later. const storeOffline = (): Promise => - AddonCalendarOffline.instance.markDeleted(eventId, name, deleteAll, siteId).then(() => false); + AddonCalendarOffline.markDeleted(eventId, name, deleteAll, siteId).then(() => false); - if (forceOffline || !CoreApp.instance.isOnline()) { + if (forceOffline || !CoreApp.isOnline()) { // App is offline, store the action. return storeOffline(); } // If the event is already stored, discard it first. - await AddonCalendarOffline.instance.unmarkDeleted(eventId, siteId); + await AddonCalendarOffline.unmarkDeleted(eventId, siteId); try { await this.deleteEventOnline(eventId, deleteAll, siteId); return true; } catch (error) { - if (error && !CoreUtils.instance.isWebServiceError(error)) { + if (error && !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server, store in offline. return storeOffline(); } else { @@ -281,7 +281,7 @@ export class AddonCalendarProvider { * @return Promise resolved when done. */ async deleteEventOnline(eventId: number, deleteAll = false, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonCalendarDeleteCalendarEventsWSParams = { events: [ { @@ -305,7 +305,7 @@ export class AddonCalendarProvider { * @return Resolved when done. */ protected async deleteLocalEvent(eventId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); const promises: Promise[] = []; @@ -334,11 +334,11 @@ export class AddonCalendarProvider { */ async initialize(): Promise { - CoreLocalNotifications.instance.registerClick( + CoreLocalNotifications.registerClick( AddonCalendarProvider.COMPONENT, async (notification) => { if (notification.eventId) { - await ApplicationInit.instance.donePromise; + await ApplicationInit.donePromise; const disabled = await this.isDisabled(notification.siteId); if (disabled) { @@ -347,10 +347,10 @@ export class AddonCalendarProvider { } // Check which page we should load. - const site = await CoreSites.instance.getSite(notification.siteId); + const site = await CoreSites.getSite(notification.siteId); const pageName = this.getMainCalendarPagePath(site); - CoreNavigator.instance.navigateToSitePath( + CoreNavigator.navigateToSitePath( pageName, { params: { eventId: notification.eventId }, siteId: notification.siteId }, ); @@ -389,16 +389,16 @@ export class AddonCalendarProvider { if (moment(start).isSame(end, 'day')) { // Event starts and ends the same day. if (event.timeduration == CoreConstants.SECONDS_DAY) { - time = Translate.instance.instant('addon.calendar.allday'); + time = Translate.instant('addon.calendar.allday'); } else { - time = CoreTimeUtils.instance.userDate(start, format) + ' » ' + - CoreTimeUtils.instance.userDate(end, format); + time = CoreTimeUtils.userDate(start, format) + ' » ' + + CoreTimeUtils.userDate(end, format); } } else { // Event lasts more than one day. - const timeStart = CoreTimeUtils.instance.userDate(start, format); - const timeEnd = CoreTimeUtils.instance.userDate(end, format); + const timeStart = CoreTimeUtils.userDate(start, format); + const timeEnd = CoreTimeUtils.userDate(end, format); const promises: Promise[] = []; // Don't use common words when the event lasts more than one day. @@ -408,14 +408,14 @@ export class AddonCalendarProvider { // Add links to the days if needed. if (dayStart && (!seenDay || !moment(seenDay).isSame(start, 'day'))) { promises.push(this.getViewUrl('day', event.timestart, undefined, siteId).then((url) => { - dayStart = CoreUrlUtils.instance.buildLink(url, dayStart); + dayStart = CoreUrlUtils.buildLink(url, dayStart); return; })); } if (dayEnd && (!seenDay || !moment(seenDay).isSame(end, 'day'))) { promises.push(this.getViewUrl('day', end / 1000, undefined, siteId).then((url) => { - dayEnd = CoreUrlUtils.instance.buildLink(url, dayEnd); + dayEnd = CoreUrlUtils.buildLink(url, dayEnd); return; })); @@ -427,7 +427,7 @@ export class AddonCalendarProvider { } } else { // There is no time duration. - time = CoreTimeUtils.instance.userDate(start, format); + time = CoreTimeUtils.userDate(start, format); } if (showTime) { @@ -443,7 +443,7 @@ export class AddonCalendarProvider { // Add link to view the day. const url = await this.getViewUrl('day', event.timestart, undefined, siteId); - return CoreUrlUtils.instance.buildLink(url, this.getDayRepresentation(start, useCommonWords)) + ', ' + time; + return CoreUrlUtils.buildLink(url, this.getDayRepresentation(start, useCommonWords)) + ', ' + time; } /** @@ -455,7 +455,7 @@ export class AddonCalendarProvider { * @since 3.7 */ async getAccessInformation(courseId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonCalendarGetCalendarAccessInformationWSParams = {}; const preSets: CoreSiteWSPreSets = { cacheKey: this.getAccessInformationCacheKey(courseId), @@ -484,7 +484,7 @@ export class AddonCalendarProvider { * @return Promise resolved with all the events. */ async getAllEventsFromLocalDb(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getAllRecords(EVENTS_TABLE); } @@ -498,7 +498,7 @@ export class AddonCalendarProvider { * @since 3.7 */ async getAllowedEventTypes(courseId?: number, siteId?: string): Promise<{[name: string]: boolean}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonCalendarGetAllowedEventTypesWSParams = {}; const preSets: CoreSiteWSPreSets = { cacheKey: this.getAllowedEventTypesCacheKey(courseId), @@ -537,10 +537,10 @@ export class AddonCalendarProvider { * @return Promise resolved with the look ahead (number of days). */ async getCalendarLookAhead(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); let value: string | undefined; try { - value = await CoreUser.instance.getUserPreference('calendar_lookahead'); + value = await CoreUser.getUserPreference('calendar_lookahead'); } catch { // Ignore errors. } @@ -559,11 +559,11 @@ export class AddonCalendarProvider { * @return Promise resolved with the format. */ async getCalendarTimeFormat(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); let format: string | undefined; try { - format = await CoreUser.instance.getUserPreference('calendar_timeformat'); + format = await CoreUser.getUserPreference('calendar_timeformat'); } catch { // Ignore errors. } @@ -573,12 +573,12 @@ export class AddonCalendarProvider { } if (format === AddonCalendarProvider.CALENDAR_TF_12) { - format = Translate.instance.instant('core.strftimetime12'); + format = Translate.instant('core.strftimetime12'); } else if (format === AddonCalendarProvider.CALENDAR_TF_24) { - format = Translate.instance.instant('core.strftimetime24'); + format = Translate.instant('core.strftimetime24'); } - return format && format !== '0' ? format : Translate.instance.instant('core.strftimetime'); + return format && format !== '0' ? format : Translate.instant('core.strftimetime'); } /** @@ -592,23 +592,23 @@ export class AddonCalendarProvider { if (!useCommonWords) { // We don't want words, just a date. - return CoreTimeUtils.instance.userDate(time, 'core.strftimedayshort'); + return CoreTimeUtils.userDate(time, 'core.strftimedayshort'); } const date = moment(time); const today = moment(); if (date.isSame(today, 'day')) { - return Translate.instance.instant('addon.calendar.today'); + return Translate.instant('addon.calendar.today'); } if (date.isSame(today.clone().subtract(1, 'days'), 'day')) { - return Translate.instance.instant('addon.calendar.yesterday'); + return Translate.instant('addon.calendar.yesterday'); } if (date.isSame(today.clone().add(1, 'days'), 'day')) { - return Translate.instance.instant('addon.calendar.tomorrow'); + return Translate.instant('addon.calendar.tomorrow'); } - return CoreTimeUtils.instance.userDate(time, 'core.strftimedayshort'); + return CoreTimeUtils.userDate(time, 'core.strftimedayshort'); } /** @@ -618,11 +618,11 @@ export class AddonCalendarProvider { * @return Promise resolved with the default time. */ async getDefaultNotificationTime(siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const key = AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_SETTING + '#' + siteId; - return CoreConfig.instance.get(key, AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME); + return CoreConfig.get(key, AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME); } /** @@ -633,7 +633,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the event data is retrieved. */ async getEvent(id: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { cacheKey: this.getEventCacheKey(id), updateFrequency: CoreSite.FREQUENCY_RARELY, @@ -670,7 +670,7 @@ export class AddonCalendarProvider { * @since 3.4 */ async getEventById(id: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { cacheKey: this.getEventCacheKey(id), updateFrequency: CoreSite.FREQUENCY_RARELY, @@ -710,7 +710,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the event data is retrieved. */ async getEventFromLocalDb(id: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const record: AddonCalendarGetEventsEvent | AddonCalendarEvent | AddonCalendarEventDBRecord = await site.getDb().getRecord(EVENTS_TABLE, { id: id }); @@ -729,18 +729,18 @@ export class AddonCalendarProvider { eventConverted.iscategoryevent = originalEvent.eventtype == AddonCalendarEventType.CATEGORY; eventConverted.normalisedeventtype = this.getEventType(recordAsRecord); try { - eventConverted.category = CoreTextUtils.instance.parseJSON(recordAsRecord.category!); + eventConverted.category = CoreTextUtils.parseJSON(recordAsRecord.category!); } catch { // Ignore errors. } try { - eventConverted.course = CoreTextUtils.instance.parseJSON(recordAsRecord.course!); + eventConverted.course = CoreTextUtils.parseJSON(recordAsRecord.course!); } catch { // Ignore errors. } try { - eventConverted.subscription = CoreTextUtils.instance.parseJSON(recordAsRecord.subscription!); + eventConverted.subscription = CoreTextUtils.parseJSON(recordAsRecord.subscription!); } catch { // Ignore errors. } @@ -761,7 +761,7 @@ export class AddonCalendarProvider { time: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const reminder: AddonCalendarReminderDBRecord = { eventid: event.id, time: time, @@ -794,10 +794,10 @@ export class AddonCalendarProvider { * @return Promise resolved when the notification is updated. */ async deleteEventReminder(id: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - if (CoreLocalNotifications.instance.isAvailable()) { - CoreLocalNotifications.instance.cancel(id, AddonCalendarProvider.COMPONENT, site.getId()); + if (CoreLocalNotifications.isAvailable()) { + CoreLocalNotifications.cancel(id, AddonCalendarProvider.COMPONENT, site.getId()); } await site.getDb().deleteRecords(REMINDERS_TABLE, { id: id }); @@ -825,7 +825,7 @@ export class AddonCalendarProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonCalendarGetCalendarDayViewWSParams = { year: year, month: month, @@ -895,7 +895,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the event data is retrieved. */ async getEventReminders(id: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecords(REMINDERS_TABLE, { eventid: id }, 'time ASC'); } @@ -920,9 +920,9 @@ export class AddonCalendarProvider { siteId?: string, ): Promise { - initialTime = initialTime || CoreTimeUtils.instance.timestamp(); + initialTime = initialTime || CoreTimeUtils.timestamp(); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); const start = initialTime + (CoreConstants.SECONDS_DAY * daysToStart); @@ -943,7 +943,7 @@ export class AddonCalendarProvider { const promises: Promise[] = []; - promises.push(CoreCourses.instance.getUserCourses(false, siteId).then((courses) => { + promises.push(CoreCourses.getUserCourses(false, siteId).then((courses) => { params.events!.courseids = courses.map((course) => course.id); params.events!.courseids.push(site.getSiteHomeId()); // Add front page. @@ -951,7 +951,7 @@ export class AddonCalendarProvider { return; })); - promises.push(CoreGroups.instance.getAllUserGroups(siteId).then((groups) => { + promises.push(CoreGroups.getAllUserGroups(siteId).then((groups) => { params.events!.groupids = groups.map((group) => group.id); return; @@ -1004,7 +1004,7 @@ export class AddonCalendarProvider { * @return Promise resolved with all the events. */ async getLocalEventsByRepeatIdFromLocalDb(repeatId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecords(EVENTS_TABLE, { repeatid: repeatId }); } @@ -1029,7 +1029,7 @@ export class AddonCalendarProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonCalendarGetCalendarMonthlyViewWSParams = { year: year, month: month, @@ -1063,8 +1063,8 @@ export class AddonCalendarProvider { }); // Store starting week day preference, we need it in offline to show months that are not in cache. - if (CoreApp.instance.isOnline()) { - CoreConfig.instance.set(AddonCalendarProvider.STARTING_WEEK_DAY, response.daynames[0].dayno); + if (CoreApp.isOnline()) { + CoreConfig.set(AddonCalendarProvider.STARTING_WEEK_DAY, response.daynames[0].dayno); } return response; @@ -1120,7 +1120,7 @@ export class AddonCalendarProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonCalendarGetCalendarUpcomingViewWSParams = {}; if (courseId) { @@ -1177,8 +1177,8 @@ export class AddonCalendarProvider { * @return Promise resolved with the URL.x */ async getViewUrl(view: string, time?: number, courseId?: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); - let url = CoreTextUtils.instance.concatenatePaths(site.getURL(), 'calendar/view.php?view=' + view); + const site = await CoreSites.getSite(siteId); + let url = CoreTextUtils.concatenatePaths(site.getURL(), 'calendar/view.php?view=' + view); if (time) { url += '&time=' + time; @@ -1210,7 +1210,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAccessInformation(courseId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAccessInformationCacheKey(courseId)); } @@ -1223,7 +1223,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAllowedEventTypes(courseId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAllowedEventTypesCacheKey(courseId)); } @@ -1235,7 +1235,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAllDayEvents(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getDayEventsPrefixCacheKey()); } @@ -1249,7 +1249,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ async invalidateDayEvents(year: number, month: number, day: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getDayEventsDayPrefixCacheKey(year, month, day)); } @@ -1261,12 +1261,12 @@ export class AddonCalendarProvider { * @return Promise resolved when the list is invalidated. */ async invalidateEventsList(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); const promises: Promise[] = []; - promises.push(CoreCourses.instance.invalidateUserCourses(siteId)); - promises.push(CoreGroups.instance.invalidateAllUserGroups(siteId)); + promises.push(CoreCourses.invalidateUserCourses(siteId)); + promises.push(CoreGroups.invalidateAllUserGroups(siteId)); promises.push(site.invalidateWsCacheForKeyStartingWith(this.getEventsListPrefixCacheKey())); await Promise.all(promises); @@ -1280,7 +1280,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the list is invalidated. */ async invalidateEvent(eventId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getEventCacheKey(eventId)); } @@ -1292,7 +1292,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAllMonthlyEvents(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getMonthlyEventsPrefixCacheKey()); } @@ -1305,7 +1305,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ async invalidateMonthlyEvents(year: number, month: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getMonthlyEventsMonthPrefixCacheKey(year, month)); } @@ -1317,7 +1317,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAllUpcomingEvents(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUpcomingEventsPrefixCacheKey()); } @@ -1331,7 +1331,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUpcomingEvents(courseId?: number, categoryId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUpcomingEventsCacheKey(courseId, categoryId)); } @@ -1343,7 +1343,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ async invalidateLookAhead(siteId?: string): Promise { - await CoreUser.instance.invalidateUserPreference('calendar_lookahead', siteId); + await CoreUser.invalidateUserPreference('calendar_lookahead', siteId); } /** @@ -1353,7 +1353,7 @@ export class AddonCalendarProvider { * @return Promise resolved when the data is invalidated. */ invalidateTimeFormat(siteId?: string): Promise { - return CoreUser.instance.invalidateUserPreference('calendar_timeformat', siteId); + return CoreUser.invalidateUserPreference('calendar_timeformat', siteId); } /** @@ -1363,7 +1363,7 @@ export class AddonCalendarProvider { * @return Whether it's disabled. */ isCalendarDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('CoreMainMenuDelegate_AddonCalendar'); } @@ -1375,7 +1375,7 @@ export class AddonCalendarProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isCalendarDisabledInSite(site); } @@ -1389,7 +1389,7 @@ export class AddonCalendarProvider { */ async isGetEventByIdAvailable(siteId?: string): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isGetEventByIdAvailableInSite(site); } catch { @@ -1405,7 +1405,7 @@ export class AddonCalendarProvider { * @since 3.4 */ isGetEventByIdAvailableInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.wsAvailable('core_calendar_get_calendar_event_by_id'); } @@ -1418,11 +1418,11 @@ export class AddonCalendarProvider { * @return Promise resolved when all the notifications have been scheduled. */ async scheduleAllSitesEventsNotifications(): Promise { - await Platform.instance.ready(); + await Platform.ready(); - const notificationsEnabled = CoreLocalNotifications.instance.isAvailable(); + const notificationsEnabled = CoreLocalNotifications.isAvailable(); - const siteIds = await CoreSites.instance.getSitesIds(); + const siteIds = await CoreSites.getSitesIds(); const promises = siteIds.map((siteId: string) => this.cleanExpiredEvents(siteId).then(async() => { if (notificationsEnabled) { @@ -1458,15 +1458,15 @@ export class AddonCalendarProvider { siteId?: string, ): Promise { - if (!CoreLocalNotifications.instance.isAvailable()) { + if (!CoreLocalNotifications.isAvailable()) { return; } - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (time === 0) { // Cancel if it was scheduled. - return CoreLocalNotifications.instance.cancel(reminderId, AddonCalendarProvider.COMPONENT, siteId); + return CoreLocalNotifications.cancel(reminderId, AddonCalendarProvider.COMPONENT, siteId); } if (time == -1) { @@ -1475,7 +1475,7 @@ export class AddonCalendarProvider { if (time == 0) { // Default notification time is disabled, do not show. - return CoreLocalNotifications.instance.cancel(reminderId, AddonCalendarProvider.COMPONENT, siteId); + return CoreLocalNotifications.cancel(reminderId, AddonCalendarProvider.COMPONENT, siteId); } time = event.timestart - (time * 60); @@ -1485,7 +1485,7 @@ export class AddonCalendarProvider { if (time <= Date.now()) { // This reminder is over, don't schedule. Cancel if it was scheduled. - return CoreLocalNotifications.instance.cancel(reminderId, AddonCalendarProvider.COMPONENT, siteId); + return CoreLocalNotifications.cancel(reminderId, AddonCalendarProvider.COMPONENT, siteId); } const notificationData: AddonCalendarPushNotificationData = { @@ -1497,7 +1497,7 @@ export class AddonCalendarProvider { const notification: ILocalNotification = { id: reminderId, title: event.name, - text: CoreTimeUtils.instance.userDate(event.timestart * 1000, 'core.strftimedaydatetime', true), + text: CoreTimeUtils.userDate(event.timestart * 1000, 'core.strftimedaydatetime', true), icon: 'file://assets/img/icons/calendar.png', trigger: { at: new Date(time), @@ -1505,7 +1505,7 @@ export class AddonCalendarProvider { data: notificationData, }; - return CoreLocalNotifications.instance.schedule(notification, AddonCalendarProvider.COMPONENT, siteId); + return CoreLocalNotifications.schedule(notification, AddonCalendarProvider.COMPONENT, siteId); } /** @@ -1522,11 +1522,11 @@ export class AddonCalendarProvider { siteId?: string, ): Promise { - if (!CoreLocalNotifications.instance.isAvailable()) { + if (!CoreLocalNotifications.isAvailable()) { return; } - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const promises = events.map(async (event) => { const timeEnd = (event.timestart + event.timeduration) * 1000; @@ -1555,11 +1555,11 @@ export class AddonCalendarProvider { * @return Promise resolved when stored. */ async setDefaultNotificationTime(time: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const key = AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_SETTING + '#' + siteId; - await CoreConfig.instance.set(key, time); + await CoreConfig.set(key, time); } /** @@ -1570,7 +1570,7 @@ export class AddonCalendarProvider { * @return Promise resolved when stored. */ async storeEventInLocalDb(event: AddonCalendarGetEventsEvent | AddonCalendarCalendarEvent, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); try { await this.getEventFromLocalDb(event.id, site.id); @@ -1646,7 +1646,7 @@ export class AddonCalendarProvider { events: (AddonCalendarGetEventsEvent | AddonCalendarCalendarEvent)[], siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); await Promise.all(events.map((event: AddonCalendarGetEventsEvent| AddonCalendarCalendarEvent) => @@ -1672,28 +1672,28 @@ export class AddonCalendarProvider { siteId?: string, ): Promise<{sent: boolean; event: AddonCalendarOfflineEventDBRecord | AddonCalendarEvent}> { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Function to store the event to be synchronized later. const storeOffline = (): Promise<{ sent: boolean; event: AddonCalendarOfflineEventDBRecord }> => - AddonCalendarOffline.instance.saveEvent(eventId, formData, timeCreated, siteId).then((event) => + AddonCalendarOffline.saveEvent(eventId, formData, timeCreated, siteId).then((event) => ({ sent: false, event })); - if (forceOffline || !CoreApp.instance.isOnline()) { + if (forceOffline || !CoreApp.isOnline()) { // App is offline, store the event. return storeOffline(); } if (eventId) { // If the event is already stored, discard it first. - await AddonCalendarOffline.instance.deleteEvent(eventId, siteId); + await AddonCalendarOffline.deleteEvent(eventId, siteId); } try { const event = await this.submitEventOnline(eventId, formData, siteId); return ({ sent: true, event }); } catch (error) { - if (error && !CoreUtils.instance.isWebServiceError(error)) { + if (error && !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server, store in offline. return storeOffline(); } else { @@ -1716,7 +1716,7 @@ export class AddonCalendarProvider { formData: AddonCalendarSubmitCreateUpdateFormDataWSParams, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Add data that is "hidden" in web. formData.id = eventId; formData.userid = site.getUserId(); @@ -1728,14 +1728,14 @@ export class AddonCalendarProvider { formData['_qf__core_calendar_local_event_forms_create'] = 1; } const params: AddonCalendarSubmitCreateUpdateFormWSParams = { - formdata: CoreUtils.instance.objectToGetParams(formData), + formdata: CoreUtils.objectToGetParams(formData), }; const result = await site.write('core_calendar_submit_create_update_form', params); if (result.validationerror) { // Simulate a WS error. throw new CoreWSError({ - message: Translate.instance.instant('core.invalidformdata'), + message: Translate.instant('core.invalidformdata'), errorcode: 'validationerror', }); } @@ -1745,7 +1745,7 @@ export class AddonCalendarProvider { } -export class AddonCalendar extends makeSingleton(AddonCalendarProvider) {} +export const AddonCalendar = makeSingleton(AddonCalendarProvider); /** * Data returned by calendar's events_exporter. diff --git a/src/addons/calendar/services/handlers/mainmenu.ts b/src/addons/calendar/services/handlers/mainmenu.ts index ebda4f8f0..2f2e2395e 100644 --- a/src/addons/calendar/services/handlers/mainmenu.ts +++ b/src/addons/calendar/services/handlers/mainmenu.ts @@ -35,7 +35,7 @@ export class AddonCalendarMainMenuHandlerService implements CoreMainMenuHandler * @return Whether or not the handler is enabled on a site level. */ async isEnabled(): Promise { - return !AddonCalendar.instance.isCalendarDisabledInSite(); + return !AddonCalendar.isCalendarDisabledInSite(); } /** @@ -47,11 +47,11 @@ export class AddonCalendarMainMenuHandlerService implements CoreMainMenuHandler return { icon: 'far-calendar', title: 'addon.calendar.calendar', - page: AddonCalendar.instance.getMainCalendarPagePath(), + page: AddonCalendar.getMainCalendarPagePath(), class: 'addon-calendar-handler', }; } } -export class AddonCalendarMainMenuHandler extends makeSingleton(AddonCalendarMainMenuHandlerService) {} +export const AddonCalendarMainMenuHandler = makeSingleton(AddonCalendarMainMenuHandlerService); diff --git a/src/addons/calendar/services/handlers/sync-cron.ts b/src/addons/calendar/services/handlers/sync-cron.ts index a30754ec0..59443a05d 100644 --- a/src/addons/calendar/services/handlers/sync-cron.ts +++ b/src/addons/calendar/services/handlers/sync-cron.ts @@ -34,7 +34,7 @@ export class AddonCalendarSyncCronHandlerService implements CoreCronHandler { * @return Promise resolved when done, rejected if failure. */ async execute(siteId?: string, force?: boolean): Promise { - await AddonCalendarSync.instance.syncAllEvents(siteId, force); + await AddonCalendarSync.syncAllEvents(siteId, force); } /** @@ -43,9 +43,9 @@ export class AddonCalendarSyncCronHandlerService implements CoreCronHandler { * @return Time between consecutive executions (in ms). */ getInterval(): number { - return AddonCalendarSync.instance.syncInterval; + return AddonCalendarSync.syncInterval; } } -export class AddonCalendarSyncCronHandler extends makeSingleton(AddonCalendarSyncCronHandlerService) {} +export const AddonCalendarSyncCronHandler = makeSingleton(AddonCalendarSyncCronHandlerService); diff --git a/src/addons/calendar/services/handlers/view-link.ts b/src/addons/calendar/services/handlers/view-link.ts index 1bd87d619..2faf2b177 100644 --- a/src/addons/calendar/services/handlers/view-link.ts +++ b/src/addons/calendar/services/handlers/view-link.ts @@ -59,7 +59,7 @@ export class AddonCalendarViewLinkHandlerService extends CoreContentLinksHandler stateParams.month = date.getMonth() + 1; // @todo: Add checkMenu param. - CoreNavigator.instance.navigateToSitePath('/calendar/index', { params: stateParams, siteId }); + CoreNavigator.navigateToSitePath('/calendar/index', { params: stateParams, siteId }); } else if (params.view == 'day') { // Daily view, open the page. @@ -73,7 +73,7 @@ export class AddonCalendarViewLinkHandlerService extends CoreContentLinksHandler stateParams.month = date.getMonth() + 1; stateParams.day = date.getDate(); - CoreNavigator.instance.navigateToSitePath('/calendar/day', { params: stateParams, siteId }); + CoreNavigator.navigateToSitePath('/calendar/day', { params: stateParams, siteId }); } else if (params.view == 'upcoming' || params.view == 'upcoming_mini') { // Upcoming view, open the calendar tab. @@ -83,7 +83,7 @@ export class AddonCalendarViewLinkHandlerService extends CoreContentLinksHandler }; // @todo: Add checkMenu param. - CoreNavigator.instance.navigateToSitePath('/calendar/index', { params: stateParams, siteId }); + CoreNavigator.navigateToSitePath('/calendar/index', { params: stateParams, siteId }); } }, @@ -105,15 +105,15 @@ export class AddonCalendarViewLinkHandlerService extends CoreContentLinksHandler return false; } - return AddonCalendar.instance.isDisabled(siteId).then((disabled) => { + return AddonCalendar.isDisabled(siteId).then((disabled) => { if (disabled) { return false; } - return AddonCalendar.instance.canViewMonth(siteId); + return AddonCalendar.canViewMonth(siteId); }); } } -export class AddonCalendarViewLinkHandler extends makeSingleton(AddonCalendarViewLinkHandlerService) {} +export const AddonCalendarViewLinkHandler = makeSingleton(AddonCalendarViewLinkHandlerService); diff --git a/src/addons/coursecompletion/services/coursecompletion.ts b/src/addons/coursecompletion/services/coursecompletion.ts index dd6f7205e..cee944029 100644 --- a/src/addons/coursecompletion/services/coursecompletion.ts +++ b/src/addons/coursecompletion/services/coursecompletion.ts @@ -45,7 +45,7 @@ export class AddonCourseCompletionProvider { * @return True if user can mark course as self completed, false otherwise. */ canMarkSelfCompleted(userId: number, completion: AddonCourseCompletionCourseCompletionStatus): boolean { - if (CoreSites.instance.getCurrentSiteUserId() != userId) { + if (CoreSites.getCurrentSiteUserId() != userId) { return false; } @@ -100,7 +100,7 @@ export class AddonCourseCompletionProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); this.logger.debug('Get completion for course ' + courseId + ' and user ' + userId); @@ -142,7 +142,7 @@ export class AddonCourseCompletionProvider { * @return Promise resolved when the list is invalidated. */ async invalidateCourseCompletion(courseId: number, userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.invalidateWsCacheForKey(this.getCompletionCacheKey(courseId, userId)); @@ -154,7 +154,7 @@ export class AddonCourseCompletionProvider { * @return True if plugin enabled, false otherwise. */ isPluginViewEnabled(): boolean { - return CoreSites.instance.isLoggedIn(); + return CoreSites.isLoggedIn(); } /** @@ -169,7 +169,7 @@ export class AddonCourseCompletionProvider { throw new CoreError('No courseId provided'); } - const course = await CoreCourses.instance.getUserCourse(courseId, preferCache); + const course = await CoreCourses.getUserCourse(courseId, preferCache); if (course) { if (typeof course.enablecompletion != 'undefined' && !course.enablecompletion) { @@ -195,14 +195,14 @@ export class AddonCourseCompletionProvider { * @return Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise. */ async isPluginViewEnabledForUser(courseId: number, userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const currentUserId = site.getUserId(); // Check if user wants to view his own completion. try { if (!userId || userId == currentUserId) { // Viewing own completion. Get the course to check if it has completion criteria. - const course = await CoreCourses.instance.getUserCourse(courseId, true); + const course = await CoreCourses.getUserCourse(courseId, true); // If the site is returning the completionhascriteria then the user can view his own completion. // We already checked the value in isPluginViewEnabledForCourse. @@ -226,7 +226,7 @@ export class AddonCourseCompletionProvider { return true; } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // The WS returned an error, plugin is not enabled. return false; } @@ -252,7 +252,7 @@ export class AddonCourseCompletionProvider { * @return Promise resolved on success. */ async markCourseAsSelfCompleted(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonCourseCompletionMarkCourseSelfCompletedWSParams = { courseid: courseId, @@ -267,7 +267,7 @@ export class AddonCourseCompletionProvider { } -export class AddonCourseCompletion extends makeSingleton(AddonCourseCompletionProvider) {} +export const AddonCourseCompletion = makeSingleton(AddonCourseCompletionProvider); /** * Completion status returned by core_completion_get_course_completion_status. diff --git a/src/addons/filter/activitynames/activitynames.module.ts b/src/addons/filter/activitynames/activitynames.module.ts index aad852015..1aa7ac805 100644 --- a/src/addons/filter/activitynames/activitynames.module.ts +++ b/src/addons/filter/activitynames/activitynames.module.ts @@ -27,7 +27,7 @@ import { AddonFilterActivityNamesHandler } from './services/handlers/activitynam provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterActivityNamesHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterActivityNamesHandler.instance), }, ], }) diff --git a/src/addons/filter/activitynames/services/handlers/activitynames.ts b/src/addons/filter/activitynames/services/handlers/activitynames.ts index b6f27260b..83a57daf8 100644 --- a/src/addons/filter/activitynames/services/handlers/activitynames.ts +++ b/src/addons/filter/activitynames/services/handlers/activitynames.ts @@ -43,4 +43,4 @@ export class AddonFilterActivityNamesHandlerService extends CoreFilterDefaultHan } -export class AddonFilterActivityNamesHandler extends makeSingleton(AddonFilterActivityNamesHandlerService) {} +export const AddonFilterActivityNamesHandler = makeSingleton(AddonFilterActivityNamesHandlerService); diff --git a/src/addons/filter/algebra/algebra.module.ts b/src/addons/filter/algebra/algebra.module.ts index 1e6b6287c..8fe37b21d 100644 --- a/src/addons/filter/algebra/algebra.module.ts +++ b/src/addons/filter/algebra/algebra.module.ts @@ -27,7 +27,7 @@ import { AddonFilterAlgebraHandler } from './services/handlers/algebra'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterAlgebraHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterAlgebraHandler.instance), }, ], }) diff --git a/src/addons/filter/algebra/services/handlers/algebra.ts b/src/addons/filter/algebra/services/handlers/algebra.ts index 378e2833e..fdb1552db 100644 --- a/src/addons/filter/algebra/services/handlers/algebra.ts +++ b/src/addons/filter/algebra/services/handlers/algebra.ts @@ -43,4 +43,4 @@ export class AddonFilterAlgebraHandlerService extends CoreFilterDefaultHandler { } -export class AddonFilterAlgebraHandler extends makeSingleton(AddonFilterAlgebraHandlerService) {} +export const AddonFilterAlgebraHandler = makeSingleton(AddonFilterAlgebraHandlerService); diff --git a/src/addons/filter/censor/censor.module.ts b/src/addons/filter/censor/censor.module.ts index 28b749619..bdb741ab7 100644 --- a/src/addons/filter/censor/censor.module.ts +++ b/src/addons/filter/censor/censor.module.ts @@ -27,7 +27,7 @@ import { AddonFilterCensorHandler } from './services/handlers/censor'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterCensorHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterCensorHandler.instance), }, ], }) diff --git a/src/addons/filter/censor/services/handlers/censor.ts b/src/addons/filter/censor/services/handlers/censor.ts index 074c76dd9..93e490d07 100644 --- a/src/addons/filter/censor/services/handlers/censor.ts +++ b/src/addons/filter/censor/services/handlers/censor.ts @@ -43,4 +43,4 @@ export class AddonFilterCensorHandlerService extends CoreFilterDefaultHandler { } -export class AddonFilterCensorHandler extends makeSingleton(AddonFilterCensorHandlerService) {} +export const AddonFilterCensorHandler = makeSingleton(AddonFilterCensorHandlerService); diff --git a/src/addons/filter/data/data.module.ts b/src/addons/filter/data/data.module.ts index 1e2488629..fe88960d0 100644 --- a/src/addons/filter/data/data.module.ts +++ b/src/addons/filter/data/data.module.ts @@ -27,7 +27,7 @@ import { AddonFilterDataHandler } from './services/handlers/data'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterDataHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterDataHandler.instance), }, ], }) diff --git a/src/addons/filter/data/services/handlers/data.ts b/src/addons/filter/data/services/handlers/data.ts index 92006a5b2..83693cc26 100644 --- a/src/addons/filter/data/services/handlers/data.ts +++ b/src/addons/filter/data/services/handlers/data.ts @@ -43,4 +43,4 @@ export class AddonFilterDataHandlerService extends CoreFilterDefaultHandler { } -export class AddonFilterDataHandler extends makeSingleton(AddonFilterDataHandlerService) {} +export const AddonFilterDataHandler = makeSingleton(AddonFilterDataHandlerService); diff --git a/src/addons/filter/displayh5p/displayh5p.module.ts b/src/addons/filter/displayh5p/displayh5p.module.ts index 9aaa97ea2..d40923144 100644 --- a/src/addons/filter/displayh5p/displayh5p.module.ts +++ b/src/addons/filter/displayh5p/displayh5p.module.ts @@ -27,7 +27,7 @@ import { AddonFilterDisplayH5PHandler } from './services/handlers/displayh5p'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterDisplayH5PHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterDisplayH5PHandler.instance), }, ], }) diff --git a/src/addons/filter/displayh5p/services/handlers/displayh5p.ts b/src/addons/filter/displayh5p/services/handlers/displayh5p.ts index e4ac253c8..8134fac47 100644 --- a/src/addons/filter/displayh5p/services/handlers/displayh5p.ts +++ b/src/addons/filter/displayh5p/services/handlers/displayh5p.ts @@ -109,4 +109,4 @@ export class AddonFilterDisplayH5PHandlerService extends CoreFilterDefaultHandle } -export class AddonFilterDisplayH5PHandler extends makeSingleton(AddonFilterDisplayH5PHandlerService) {} +export const AddonFilterDisplayH5PHandler = makeSingleton(AddonFilterDisplayH5PHandlerService); diff --git a/src/addons/filter/emailprotect/emailprotect.module.ts b/src/addons/filter/emailprotect/emailprotect.module.ts index f035274e6..3793c4219 100644 --- a/src/addons/filter/emailprotect/emailprotect.module.ts +++ b/src/addons/filter/emailprotect/emailprotect.module.ts @@ -27,7 +27,7 @@ import { AddonFilterEmailProtectHandler } from './services/handlers/emailprotect provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterEmailProtectHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterEmailProtectHandler.instance), }, ], }) diff --git a/src/addons/filter/emailprotect/services/handlers/emailprotect.ts b/src/addons/filter/emailprotect/services/handlers/emailprotect.ts index 972356e66..f56bdcaeb 100644 --- a/src/addons/filter/emailprotect/services/handlers/emailprotect.ts +++ b/src/addons/filter/emailprotect/services/handlers/emailprotect.ts @@ -43,4 +43,4 @@ export class AddonFilterEmailProtectHandlerService extends CoreFilterDefaultHand } -export class AddonFilterEmailProtectHandler extends makeSingleton(AddonFilterEmailProtectHandlerService) {} +export const AddonFilterEmailProtectHandler = makeSingleton(AddonFilterEmailProtectHandlerService); diff --git a/src/addons/filter/emoticon/emoticon.module.ts b/src/addons/filter/emoticon/emoticon.module.ts index ada8d0aac..1e925074e 100644 --- a/src/addons/filter/emoticon/emoticon.module.ts +++ b/src/addons/filter/emoticon/emoticon.module.ts @@ -27,7 +27,7 @@ import { AddonFilterEmoticonHandler } from './services/handlers/emoticon'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterEmoticonHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterEmoticonHandler.instance), }, ], }) diff --git a/src/addons/filter/emoticon/services/handlers/emoticon.ts b/src/addons/filter/emoticon/services/handlers/emoticon.ts index 0033e21fa..9b0c7652c 100644 --- a/src/addons/filter/emoticon/services/handlers/emoticon.ts +++ b/src/addons/filter/emoticon/services/handlers/emoticon.ts @@ -43,4 +43,4 @@ export class AddonFilterEmoticonHandlerService extends CoreFilterDefaultHandler } -export class AddonFilterEmoticonHandler extends makeSingleton(AddonFilterEmoticonHandlerService) {} +export const AddonFilterEmoticonHandler = makeSingleton(AddonFilterEmoticonHandlerService); diff --git a/src/addons/filter/glossary/glossary.module.ts b/src/addons/filter/glossary/glossary.module.ts index d38234843..6464e2c84 100644 --- a/src/addons/filter/glossary/glossary.module.ts +++ b/src/addons/filter/glossary/glossary.module.ts @@ -27,7 +27,7 @@ import { AddonFilterGlossaryHandler } from './services/handlers/glossary'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterGlossaryHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterGlossaryHandler.instance), }, ], }) diff --git a/src/addons/filter/glossary/services/handlers/glossary.ts b/src/addons/filter/glossary/services/handlers/glossary.ts index 412434058..96e2799ea 100644 --- a/src/addons/filter/glossary/services/handlers/glossary.ts +++ b/src/addons/filter/glossary/services/handlers/glossary.ts @@ -43,4 +43,4 @@ export class AddonFilterGlossaryHandlerService extends CoreFilterDefaultHandler } -export class AddonFilterGlossaryHandler extends makeSingleton(AddonFilterGlossaryHandlerService) {} +export const AddonFilterGlossaryHandler = makeSingleton(AddonFilterGlossaryHandlerService); diff --git a/src/addons/filter/mathjaxloader/mathjaxloader.module.ts b/src/addons/filter/mathjaxloader/mathjaxloader.module.ts index 3caa6efb9..0f3aa5b60 100644 --- a/src/addons/filter/mathjaxloader/mathjaxloader.module.ts +++ b/src/addons/filter/mathjaxloader/mathjaxloader.module.ts @@ -28,9 +28,9 @@ import { AddonFilterMathJaxLoaderHandler } from './services/handlers/mathjaxload multi: true, deps: [], useFactory: () => async () => { - CoreFilterDelegate.instance.registerHandler(AddonFilterMathJaxLoaderHandler.instance); + CoreFilterDelegate.registerHandler(AddonFilterMathJaxLoaderHandler.instance); - await AddonFilterMathJaxLoaderHandler.instance.initialize(); + await AddonFilterMathJaxLoaderHandler.initialize(); }, }, ], diff --git a/src/addons/filter/mathjaxloader/services/handlers/mathjaxloader.ts b/src/addons/filter/mathjaxloader/services/handlers/mathjaxloader.ts index c8dc95b46..ca9963c39 100644 --- a/src/addons/filter/mathjaxloader/services/handlers/mathjaxloader.ts +++ b/src/addons/filter/mathjaxloader/services/handlers/mathjaxloader.ts @@ -96,7 +96,7 @@ export class AddonFilterMathJaxLoaderHandlerService extends CoreFilterDefaultHan }); // Get the current language. - const lang = await CoreLang.instance.getCurrentLanguage(); + const lang = await CoreLang.getCurrentLanguage(); // Now call the configure function. this.window.M!.filter_mathjaxloader!.configure({ @@ -121,7 +121,7 @@ export class AddonFilterMathJaxLoaderHandlerService extends CoreFilterDefaultHan siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Don't apply this filter if Moodle is 3.7 or higher and the WS already filtered the content. if (!options.wsNotFiltered && site.isVersionGreaterEqualThan('3.7')) { @@ -188,7 +188,7 @@ export class AddonFilterMathJaxLoaderHandlerService extends CoreFilterDefaultHan * @return The whole text with the span inserted around the defined substring. */ protected insertSpan(text: string, start: number, end: number): string { - return CoreTextUtils.instance.substrReplace( + return CoreTextUtils.substrReplace( text, '' + text.substr(start, end - start + 1) + '', start, @@ -280,7 +280,7 @@ export class AddonFilterMathJaxLoaderHandlerService extends CoreFilterDefaultHan } // No more guessing, use default language. - return CoreLang.instance.getDefaultLanguage(); + return CoreLang.getDefaultLanguage(); } /** @@ -292,7 +292,7 @@ export class AddonFilterMathJaxLoaderHandlerService extends CoreFilterDefaultHan */ shouldBeApplied(options: CoreFilterFormatTextOptions, site?: CoreSite): boolean { // Only apply the filter if logged in and we're filtering current site. - return !!(site && site.getId() == CoreSites.instance.getCurrentSiteId()); + return !!(site && site.getId() == CoreSites.getCurrentSiteId()); } /** @@ -307,7 +307,7 @@ export class AddonFilterMathJaxLoaderHandlerService extends CoreFilterDefaultHan return; } - const deferred = CoreUtils.instance.promiseDefer(); + const deferred = CoreUtils.promiseDefer(); setTimeout(async () => { try { @@ -396,7 +396,7 @@ export class AddonFilterMathJaxLoaderHandlerService extends CoreFilterDefaultHan } -export class AddonFilterMathJaxLoaderHandler extends makeSingleton(AddonFilterMathJaxLoaderHandlerService) {} +export const AddonFilterMathJaxLoaderHandler = makeSingleton(AddonFilterMathJaxLoaderHandlerService); type MathJaxWindow = Window & { MathJax?: any; // eslint-disable-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any diff --git a/src/addons/filter/mediaplugin/mediaplugin.module.ts b/src/addons/filter/mediaplugin/mediaplugin.module.ts index f1099474f..a72670098 100644 --- a/src/addons/filter/mediaplugin/mediaplugin.module.ts +++ b/src/addons/filter/mediaplugin/mediaplugin.module.ts @@ -27,7 +27,7 @@ import { AddonFilterMediaPluginHandler } from './services/handlers/mediaplugin'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterMediaPluginHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterMediaPluginHandler.instance), }, ], }) diff --git a/src/addons/filter/mediaplugin/services/handlers/mediaplugin.ts b/src/addons/filter/mediaplugin/services/handlers/mediaplugin.ts index 9d3712100..ad08e3186 100644 --- a/src/addons/filter/mediaplugin/services/handlers/mediaplugin.ts +++ b/src/addons/filter/mediaplugin/services/handlers/mediaplugin.ts @@ -69,8 +69,8 @@ export class AddonFilterMediaPluginHandlerService extends CoreFilterDefaultHandl } const dataSetupString = video.getAttribute('data-setup') || video.getAttribute('data-setup-lazy') || '{}'; - const data = CoreTextUtils.instance.parseJSON(dataSetupString, {}); - const youtubeUrl = data.techOrder?.[0] == 'youtube' && CoreUrlUtils.instance.getYoutubeEmbedUrl(data.sources?.[0]?.src); + const data = CoreTextUtils.parseJSON(dataSetupString, {}); + const youtubeUrl = data.techOrder?.[0] == 'youtube' && CoreUrlUtils.getYoutubeEmbedUrl(data.sources?.[0]?.src); if (!youtubeUrl) { return; @@ -90,7 +90,7 @@ export class AddonFilterMediaPluginHandlerService extends CoreFilterDefaultHandl } -export class AddonFilterMediaPluginHandler extends makeSingleton(AddonFilterMediaPluginHandlerService) {} +export const AddonFilterMediaPluginHandler = makeSingleton(AddonFilterMediaPluginHandlerService); type VideoDataSetup = { techOrder?: string[]; diff --git a/src/addons/filter/multilang/multilang.module.ts b/src/addons/filter/multilang/multilang.module.ts index 58fb590e3..7ffab28b7 100644 --- a/src/addons/filter/multilang/multilang.module.ts +++ b/src/addons/filter/multilang/multilang.module.ts @@ -27,7 +27,7 @@ import { AddonFilterMultilangHandler } from './services/handlers/multilang'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterMultilangHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterMultilangHandler.instance), }, ], }) diff --git a/src/addons/filter/multilang/services/handlers/multilang.ts b/src/addons/filter/multilang/services/handlers/multilang.ts index a0b4b3eca..6824e5d4a 100644 --- a/src/addons/filter/multilang/services/handlers/multilang.ts +++ b/src/addons/filter/multilang/services/handlers/multilang.ts @@ -44,7 +44,7 @@ export class AddonFilterMultilangHandlerService extends CoreFilterDefaultHandler options: CoreFilterFormatTextOptions, // eslint-disable-line @typescript-eslint/no-unused-vars siteId?: string, // eslint-disable-line @typescript-eslint/no-unused-vars ): Promise { - let language = await CoreLang.instance.getCurrentLanguage(); + let language = await CoreLang.getCurrentLanguage(); // Match the current language. const anyLangRegEx = /<(?:lang|span)[^>]+lang="[a-zA-Z0-9_-]+"[^>]*>(.*?)<\/(?:lang|span)>/g; @@ -84,4 +84,4 @@ export class AddonFilterMultilangHandlerService extends CoreFilterDefaultHandler } -export class AddonFilterMultilangHandler extends makeSingleton(AddonFilterMultilangHandlerService) {} +export const AddonFilterMultilangHandler = makeSingleton(AddonFilterMultilangHandlerService); diff --git a/src/addons/filter/tex/services/handlers/tex.ts b/src/addons/filter/tex/services/handlers/tex.ts index c1412fbe3..ddeaabe2c 100644 --- a/src/addons/filter/tex/services/handlers/tex.ts +++ b/src/addons/filter/tex/services/handlers/tex.ts @@ -43,4 +43,4 @@ export class AddonFilterTexHandlerService extends CoreFilterDefaultHandler { } -export class AddonFilterTexHandler extends makeSingleton(AddonFilterTexHandlerService) {} +export const AddonFilterTexHandler = makeSingleton(AddonFilterTexHandlerService); diff --git a/src/addons/filter/tex/tex.module.ts b/src/addons/filter/tex/tex.module.ts index 124f0b793..414d3fdc5 100644 --- a/src/addons/filter/tex/tex.module.ts +++ b/src/addons/filter/tex/tex.module.ts @@ -27,7 +27,7 @@ import { AddonFilterTexHandler } from './services/handlers/tex'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterTexHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterTexHandler.instance), }, ], }) diff --git a/src/addons/filter/tidy/services/handlers/tidy.ts b/src/addons/filter/tidy/services/handlers/tidy.ts index 62ab7ede8..60bb56914 100644 --- a/src/addons/filter/tidy/services/handlers/tidy.ts +++ b/src/addons/filter/tidy/services/handlers/tidy.ts @@ -43,4 +43,4 @@ export class AddonFilterTidyHandlerService extends CoreFilterDefaultHandler { } -export class AddonFilterTidyHandler extends makeSingleton(AddonFilterTidyHandlerService) {} +export const AddonFilterTidyHandler = makeSingleton(AddonFilterTidyHandlerService); diff --git a/src/addons/filter/tidy/tidy.module.ts b/src/addons/filter/tidy/tidy.module.ts index fc8f3989c..cf1045f1e 100644 --- a/src/addons/filter/tidy/tidy.module.ts +++ b/src/addons/filter/tidy/tidy.module.ts @@ -27,7 +27,7 @@ import { AddonFilterTidyHandler } from './services/handlers/tidy'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterTidyHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterTidyHandler.instance), }, ], }) diff --git a/src/addons/filter/urltolink/services/handlers/urltolink.ts b/src/addons/filter/urltolink/services/handlers/urltolink.ts index cff0dd5d8..816efdb86 100644 --- a/src/addons/filter/urltolink/services/handlers/urltolink.ts +++ b/src/addons/filter/urltolink/services/handlers/urltolink.ts @@ -43,4 +43,4 @@ export class AddonFilterUrlToLinkHandlerService extends CoreFilterDefaultHandler } -export class AddonFilterUrlToLinkHandler extends makeSingleton(AddonFilterUrlToLinkHandlerService) {} +export const AddonFilterUrlToLinkHandler = makeSingleton(AddonFilterUrlToLinkHandlerService); diff --git a/src/addons/filter/urltolink/urltolink.module.ts b/src/addons/filter/urltolink/urltolink.module.ts index 8e4ee1591..48230c7dd 100644 --- a/src/addons/filter/urltolink/urltolink.module.ts +++ b/src/addons/filter/urltolink/urltolink.module.ts @@ -27,7 +27,7 @@ import { AddonFilterUrlToLinkHandler } from './services/handlers/urltolink'; provide: APP_INITIALIZER, multi: true, deps: [], - useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterUrlToLinkHandler.instance), + useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterUrlToLinkHandler.instance), }, ], }) diff --git a/src/addons/messageoutput/airnotifier/airnotifier.module.ts b/src/addons/messageoutput/airnotifier/airnotifier.module.ts index 2d8b19f1b..99c4b1849 100644 --- a/src/addons/messageoutput/airnotifier/airnotifier.module.ts +++ b/src/addons/messageoutput/airnotifier/airnotifier.module.ts @@ -41,7 +41,7 @@ const routes: Routes = [ multi: true, deps: [], useFactory: () => () => { - AddonMessageOutputDelegate.instance.registerHandler(AddonMessageOutputAirnotifierHandler.instance); + AddonMessageOutputDelegate.registerHandler(AddonMessageOutputAirnotifierHandler.instance); }, }, ], diff --git a/src/addons/messageoutput/airnotifier/pages/devices/devices.ts b/src/addons/messageoutput/airnotifier/pages/devices/devices.ts index ebd03ea82..6f64746a4 100644 --- a/src/addons/messageoutput/airnotifier/pages/devices/devices.ts +++ b/src/addons/messageoutput/airnotifier/pages/devices/devices.ts @@ -48,11 +48,11 @@ export class AddonMessageOutputAirnotifierDevicesPage implements OnInit, OnDestr */ protected async fetchDevices(): Promise { try { - const devices = await AddonMessageOutputAirnotifier.instance.getUserDevices(); + const devices = await AddonMessageOutputAirnotifier.getUserDevices(); this.devices = this.formatDevices(devices); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { this.devicesLoaded = true; } @@ -66,7 +66,7 @@ export class AddonMessageOutputAirnotifierDevicesPage implements OnInit, OnDestr */ protected formatDevices(devices: AddonMessageOutputAirnotifierDevice[]): AddonMessageOutputAirnotifierDeviceFormatted[] { const formattedDevices: AddonMessageOutputAirnotifierDeviceFormatted[] = devices; - const pushId = CorePushNotifications.instance.getPushId(); + const pushId = CorePushNotifications.getPushId(); // Convert enabled to boolean and search current device. formattedDevices.forEach((device) => { @@ -96,9 +96,9 @@ export class AddonMessageOutputAirnotifierDevicesPage implements OnInit, OnDestr * Fetch devices. The purpose is to store the updated data, it won't be reflected in the view. */ protected async updateDevices(): Promise { - await CoreUtils.instance.ignoreErrors(AddonMessageOutputAirnotifier.instance.invalidateUserDevices()); + await CoreUtils.ignoreErrors(AddonMessageOutputAirnotifier.invalidateUserDevices()); - await AddonMessageOutputAirnotifier.instance.getUserDevices(); + await AddonMessageOutputAirnotifier.getUserDevices(); } /** @@ -108,7 +108,7 @@ export class AddonMessageOutputAirnotifierDevicesPage implements OnInit, OnDestr */ async refreshDevices(refresher: CustomEvent): Promise { try { - await CoreUtils.instance.ignoreErrors(AddonMessageOutputAirnotifier.instance.invalidateUserDevices()); + await CoreUtils.ignoreErrors(AddonMessageOutputAirnotifier.invalidateUserDevices()); await this.fetchDevices(); } finally { @@ -126,13 +126,13 @@ export class AddonMessageOutputAirnotifierDevicesPage implements OnInit, OnDestr device.updating = true; try { - await AddonMessageOutputAirnotifier.instance.enableDevice(device.id, enable); + await AddonMessageOutputAirnotifier.enableDevice(device.id, enable); // Update the list of devices since it was modified. this.updateDevicesAfterDelay(); } catch (error) { // Show error and revert change. - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); device.enable = !device.enable; } finally { device.updating = false; diff --git a/src/addons/messageoutput/airnotifier/services/airnotifier.ts b/src/addons/messageoutput/airnotifier/services/airnotifier.ts index 954e29bcf..d52f8edf2 100644 --- a/src/addons/messageoutput/airnotifier/services/airnotifier.ts +++ b/src/addons/messageoutput/airnotifier/services/airnotifier.ts @@ -47,7 +47,7 @@ export class AddonMessageOutputAirnotifierProvider { * @return Promise resolved if success. */ async enableDevice(deviceId: number, enable: boolean, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data: AddonMessageOutputAirnotifierEnableDeviceWSParams = { deviceid: deviceId, @@ -89,7 +89,7 @@ export class AddonMessageOutputAirnotifierProvider { */ async getUserDevices(ignoreCache?: boolean, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data: AddonMessageOutputAirnotifierGetUserDevicesWSParams = { appid: CoreConstants.CONFIG.app_id, @@ -120,7 +120,7 @@ export class AddonMessageOutputAirnotifierProvider { * @return Promise resolved when data is invalidated. */ async invalidateUserDevices(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.invalidateWsCacheForKey(this.getUserDevicesCacheKey()); } @@ -132,13 +132,13 @@ export class AddonMessageOutputAirnotifierProvider { * @since 3.2 */ isEnabled(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('message_airnotifier_enable_device') && - CoreSites.instance.wsAvailableInCurrentSite('message_airnotifier_get_user_devices'); + return CoreSites.wsAvailableInCurrentSite('message_airnotifier_enable_device') && + CoreSites.wsAvailableInCurrentSite('message_airnotifier_get_user_devices'); } } -export class AddonMessageOutputAirnotifier extends makeSingleton(AddonMessageOutputAirnotifierProvider) {} +export const AddonMessageOutputAirnotifier = makeSingleton(AddonMessageOutputAirnotifierProvider); /** * Device data returned by WS message_airnotifier_get_user_devices. diff --git a/src/addons/messageoutput/airnotifier/services/handlers/messageoutput.ts b/src/addons/messageoutput/airnotifier/services/handlers/messageoutput.ts index c2668eb39..792a4322c 100644 --- a/src/addons/messageoutput/airnotifier/services/handlers/messageoutput.ts +++ b/src/addons/messageoutput/airnotifier/services/handlers/messageoutput.ts @@ -58,4 +58,4 @@ export class AddonMessageOutputAirnotifierHandlerService implements AddonMessage } -export class AddonMessageOutputAirnotifierHandler extends makeSingleton(AddonMessageOutputAirnotifierHandlerService) {} +export const AddonMessageOutputAirnotifierHandler = makeSingleton(AddonMessageOutputAirnotifierHandlerService); diff --git a/src/addons/messageoutput/services/messageoutput-delegate.ts b/src/addons/messageoutput/services/messageoutput-delegate.ts index 6a82ce5a6..d2f78188a 100644 --- a/src/addons/messageoutput/services/messageoutput-delegate.ts +++ b/src/addons/messageoutput/services/messageoutput-delegate.ts @@ -90,4 +90,4 @@ export class AddonMessageOutputDelegateService extends CoreDelegate { - this.conversationId = CoreNavigator.instance.getRouteNumberParam('conversationId') || 0; + this.conversationId = CoreNavigator.getRouteNumberParam('conversationId') || 0; this.loaded = false; this.fetchData().finally(() => { @@ -68,13 +68,13 @@ export class AddonMessagesConversationInfoComponent implements OnInit { protected async fetchData(): Promise { // Get the conversation data first. try { - const conversation = await AddonMessages.instance.getConversation(this.conversationId, false, true, 0, 0); + const conversation = await AddonMessages.getConversation(this.conversationId, false, true, 0, 0); this.conversation = conversation; // Now get the members. await this.fetchMembers(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting members.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting members.'); } } @@ -89,7 +89,7 @@ export class AddonMessagesConversationInfoComponent implements OnInit { const limitFrom = loadingMore ? this.members.length : 0; - const data = await AddonMessages.instance.getConversationMembers(this.conversationId, limitFrom); + const data = await AddonMessages.getConversationMembers(this.conversationId, limitFrom); if (loadingMore) { this.members = this.members.concat(data.members); } else { @@ -109,7 +109,7 @@ export class AddonMessagesConversationInfoComponent implements OnInit { try { await this.fetchMembers(true); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting members.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting members.'); this.loadMoreError = true; } finally { infiniteComplete && infiniteComplete(); @@ -125,8 +125,8 @@ export class AddonMessagesConversationInfoComponent implements OnInit { async refreshData(refresher?: CustomEvent): Promise { const promises: Promise[] = []; - promises.push(AddonMessages.instance.invalidateConversation(this.conversationId)); - promises.push(AddonMessages.instance.invalidateConversationMembers(this.conversationId)); + promises.push(AddonMessages.invalidateConversation(this.conversationId)); + promises.push(AddonMessages.invalidateConversationMembers(this.conversationId)); await Promise.all(promises); @@ -141,7 +141,7 @@ export class AddonMessagesConversationInfoComponent implements OnInit { * @param userId User conversation to load. */ closeModal(userId?: number): void { - ModalController.instance.dismiss(userId); + ModalController.dismiss(userId); } } diff --git a/src/addons/messages/messages.module.ts b/src/addons/messages/messages.module.ts index c3759dca7..33b1124a0 100644 --- a/src/addons/messages/messages.module.ts +++ b/src/addons/messages/messages.module.ts @@ -60,21 +60,21 @@ const mainMenuChildrenRoutes: Routes = [ deps: [], useFactory: () => () => { // Register handlers. - CoreMainMenuDelegate.instance.registerHandler(AddonMessagesMainMenuHandler.instance); - CoreCronDelegate.instance.register(AddonMessagesMainMenuHandler.instance); - CoreCronDelegate.instance.register(AddonMessagesSyncCronHandler.instance); - CoreSettingsDelegate.instance.registerHandler(AddonMessagesSettingsHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonMessagesIndexLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonMessagesDiscussionLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonMessagesContactRequestLinkHandler.instance); - CorePushNotificationsDelegate.instance.registerClickHandler(AddonMessagesPushClickHandler.instance); - CoreUserDelegate.instance.registerHandler(AddonMessagesSendMessageUserHandler.instance); + CoreMainMenuDelegate.registerHandler(AddonMessagesMainMenuHandler.instance); + CoreCronDelegate.register(AddonMessagesMainMenuHandler.instance); + CoreCronDelegate.register(AddonMessagesSyncCronHandler.instance); + CoreSettingsDelegate.registerHandler(AddonMessagesSettingsHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonMessagesIndexLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonMessagesDiscussionLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonMessagesContactRequestLinkHandler.instance); + CorePushNotificationsDelegate.registerClickHandler(AddonMessagesPushClickHandler.instance); + CoreUserDelegate.registerHandler(AddonMessagesSendMessageUserHandler.instance); // Sync some discussions when device goes online. - Network.instance.onConnect().subscribe(() => { + Network.onConnect().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { - AddonMessagesSync.instance.syncAllDiscussions(undefined, true); + NgZone.run(() => { + AddonMessagesSync.syncAllDiscussions(undefined, true); }); }); }, diff --git a/src/addons/messages/pages/contacts-35/contacts.module.ts b/src/addons/messages/pages/contacts-35/contacts.module.ts index e93802059..3d9a91693 100644 --- a/src/addons/messages/pages/contacts-35/contacts.module.ts +++ b/src/addons/messages/pages/contacts-35/contacts.module.ts @@ -42,8 +42,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; @NgModule({ diff --git a/src/addons/messages/pages/contacts-35/contacts.page.ts b/src/addons/messages/pages/contacts-35/contacts.page.ts index cb291043d..d3ebda14b 100644 --- a/src/addons/messages/pages/contacts-35/contacts.page.ts +++ b/src/addons/messages/pages/contacts-35/contacts.page.ts @@ -66,9 +66,9 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { constructor( protected route: ActivatedRoute, ) { - this.siteId = CoreSites.instance.getCurrentSiteId(); - this.searchingMessages = Translate.instance.instant('core.searching'); - this.loadingMessages = Translate.instance.instant('core.loading'); + this.siteId = CoreSites.getCurrentSiteId(); + this.searchingMessages = Translate.instant('core.searching'); + this.loadingMessages = Translate.instant('core.loading'); this.loadingMessage = this.loadingMessages; // Refresh the list when a contact request is confirmed. @@ -79,7 +79,7 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { this.refreshData(); } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } @@ -88,8 +88,8 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { */ ngOnInit(): void { this.route.queryParams.subscribe(async () => { - const discussionUserId = CoreNavigator.instance.getRouteNumberParam('discussionUserId') || - CoreNavigator.instance.getRouteNumberParam('userId') || undefined; + const discussionUserId = CoreNavigator.getRouteNumberParam('discussionUserId') || + CoreNavigator.getRouteNumberParam('userId') || undefined; if (this.loaded && this.discussionUserId == discussionUserId) { return; @@ -104,7 +104,7 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { try { await this.fetchData(); - if (!this.discussionUserId && this.hasContacts && CoreScreen.instance.isTablet) { + if (!this.discussionUserId && this.hasContacts && CoreScreen.isTablet) { let contact: AddonMessagesGetContactsContact | undefined; for (const x in this.contacts) { if (this.contacts[x].length > 0) { @@ -137,7 +137,7 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { await this.performSearch(this.searchString); } else { // Update contacts. - await AddonMessages.instance.invalidateAllContactsCache(); + await AddonMessages.invalidateAllContactsCache(); await this.fetchData(); } } finally { @@ -154,7 +154,7 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { this.loadingMessage = this.loadingMessages; try { - const contacts = await AddonMessages.instance.getAllContacts(); + const contacts = await AddonMessages.getAllContacts(); for (const x in contacts) { if (contacts[x].length > 0) { this.contacts[x] = this.sortUsers(contacts[x]); @@ -165,7 +165,7 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { this.clearSearch(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingcontacts', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingcontacts', true); } } @@ -208,7 +208,7 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { * @return Resolved when done. */ search(query: string): Promise { - CoreApp.instance.closeKeyboard(); + CoreApp.closeKeyboard(); this.loaded = false; this.loadingMessage = this.searchingMessages; @@ -226,14 +226,14 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { */ protected async performSearch(query: string): Promise { try { - const result = await AddonMessages.instance.searchContacts(query); + const result = await AddonMessages.searchContacts(query); this.hasContacts = result.length > 0; this.searchString = query; this.contactTypes = ['search']; this.contacts.search = this.sortUsers(result); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingcontacts', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingcontacts', true); } } @@ -249,11 +249,11 @@ export class AddonMessagesContacts35Page implements OnInit, OnDestroy { userId: discussionUserId, }; - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/messages/contacts-35/discussion'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/messages/contacts-35/discussion'); const path = (splitViewLoaded ? '../' : '') + 'discussion'; // @todo Check why this is failing on ngInit. - CoreNavigator.instance.navigate(path, { params }); + CoreNavigator.navigate(path, { params }); } /** diff --git a/src/addons/messages/pages/contacts/contacts.module.ts b/src/addons/messages/pages/contacts/contacts.module.ts index d20c0ae79..8fd496161 100644 --- a/src/addons/messages/pages/contacts/contacts.module.ts +++ b/src/addons/messages/pages/contacts/contacts.module.ts @@ -41,8 +41,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; diff --git a/src/addons/messages/pages/contacts/contacts.page.ts b/src/addons/messages/pages/contacts/contacts.page.ts index 583156ba1..c69f7a00b 100644 --- a/src/addons/messages/pages/contacts/contacts.page.ts +++ b/src/addons/messages/pages/contacts/contacts.page.ts @@ -61,7 +61,7 @@ export class AddonMessagesContactsPage implements OnInit, OnDestroy { constructor() { - this.siteId = CoreSites.instance.getCurrentSiteId(); + this.siteId = CoreSites.getCurrentSiteId(); // Update the contact requests badge. this.contactRequestsCountObserver = CoreEvents.on( @@ -97,7 +97,7 @@ export class AddonMessagesContactsPage implements OnInit, OnDestroy { } } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } @@ -106,13 +106,13 @@ export class AddonMessagesContactsPage implements OnInit, OnDestroy { * Page being initialized. */ async ngOnInit(): Promise { - AddonMessages.instance.getContactRequestsCount(this.siteId); // Badge already updated by the observer. + AddonMessages.getContactRequestsCount(this.siteId); // Badge already updated by the observer. if (this.selected == 'confirmed') { try { await this.confirmedFetchData(); - if (this.confirmedContacts.length && CoreScreen.instance.isTablet) { + if (this.confirmedContacts.length && CoreScreen.isTablet) { this.selectUser(this.confirmedContacts[0].id, true); } } finally { @@ -121,7 +121,7 @@ export class AddonMessagesContactsPage implements OnInit, OnDestroy { } else { try { await this.requestsFetchData(); - if (this.requests.length && CoreScreen.instance.isTablet) { + if (this.requests.length && CoreScreen.isTablet) { this.selectUser(this.requests[0].id, true); } } finally { @@ -143,16 +143,16 @@ export class AddonMessagesContactsPage implements OnInit, OnDestroy { if (limitFrom === 0) { // Always try to get latest data from server. - await AddonMessages.instance.invalidateUserContacts(); + await AddonMessages.invalidateUserContacts(); } try { - const result = await AddonMessages.instance.getUserContacts(limitFrom); + const result = await AddonMessages.getUserContacts(limitFrom); this.confirmedContacts = refresh ? result.contacts : this.confirmedContacts.concat(result.contacts); this.confirmedCanLoadMore = result.canLoadMore; } catch (error) { this.confirmedLoadMoreError = true; - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingcontacts', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingcontacts', true); } } @@ -169,16 +169,16 @@ export class AddonMessagesContactsPage implements OnInit, OnDestroy { if (limitFrom === 0) { // Always try to get latest data from server. - await AddonMessages.instance.invalidateContactRequestsCache(); + await AddonMessages.invalidateContactRequestsCache(); } try { - const result = await AddonMessages.instance.getContactRequests(limitFrom); + const result = await AddonMessages.getContactRequests(limitFrom); this.requests = refresh ? result.requests : this.requests.concat(result.requests); this.requestsCanLoadMore = result.canLoadMore; } catch (error) { this.requestsLoadMoreError = true; - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingcontacts', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingcontacts', true); } } @@ -195,7 +195,7 @@ export class AddonMessagesContactsPage implements OnInit, OnDestroy { await this.confirmedFetchData(true); } else { // Refresh the number of contacts requests to update badges. - AddonMessages.instance.refreshContactRequestsCount(); + AddonMessages.refreshContactRequestsCount(); // No need to invalidate contact requests, we always try to get the latest. await this.requestsFetchData(true); @@ -228,7 +228,7 @@ export class AddonMessagesContactsPage implements OnInit, OnDestroy { * Navigate to the search page. */ gotoSearch(): void { - CoreNavigator.instance.navigateToSitePath('search'); + CoreNavigator.navigateToSitePath('search'); } selectTab(selected: string): void { @@ -246,22 +246,22 @@ export class AddonMessagesContactsPage implements OnInit, OnDestroy { * @param onInit Whether the contact was selected on initial load. */ selectUser(userId: number, onInit = false): void { - if (userId == this.selectedUserId && CoreScreen.instance.isTablet) { + if (userId == this.selectedUserId && CoreScreen.isTablet) { // No user conversation to open or it is already opened. return; } - if (onInit && CoreScreen.instance.isMobile) { + if (onInit && CoreScreen.isMobile) { // Do not open a conversation by default when split view is not visible. return; } this.selectedUserId = userId; - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/messages/contacts/discussion'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/messages/contacts/discussion'); const path = (splitViewLoaded ? '../' : '') + 'discussion'; - CoreNavigator.instance.navigate(path, { params : { userId } }); + CoreNavigator.navigate(path, { params : { userId } }); } /** diff --git a/src/addons/messages/pages/discussion/discussion.page.ts b/src/addons/messages/pages/discussion/discussion.page.ts index 99c3de9fd..aa5f0487d 100644 --- a/src/addons/messages/pages/discussion/discussion.page.ts +++ b/src/addons/messages/pages/discussion/discussion.page.ts @@ -118,10 +118,10 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView constructor( protected route: ActivatedRoute, ) { - this.siteId = CoreSites.instance.getCurrentSiteId(); - this.currentUserId = CoreSites.instance.getCurrentSiteUserId(); - this.groupMessagingEnabled = AddonMessages.instance.isGroupMessagingEnabled(); - this.muteEnabled = AddonMessages.instance.isMuteConversationEnabled(); + this.siteId = CoreSites.getCurrentSiteId(); + this.currentUserId = CoreSites.getCurrentSiteUserId(); + this.groupMessagingEnabled = AddonMessages.isGroupMessagingEnabled(); + this.muteEnabled = AddonMessages.isMuteConversationEnabled(); this.logger = CoreLogger.getInstance('AddonMessagesDiscussionPage'); @@ -134,7 +134,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView // Show first warning if any. if (data.warnings && data.warnings[0]) { - CoreDomUtils.instance.showErrorModal(data.warnings[0]); + CoreDomUtils.showErrorModal(data.warnings[0]); } } }, this.siteId); @@ -164,14 +164,14 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView */ async ngOnInit(): Promise { // Disable the profile button if we're already coming from a profile. - const backViewPage = CoreNavigator.instance.getPreviousPath(); - this.showInfo = !backViewPage || !CoreTextUtils.instance.matchesGlob(backViewPage, '**/user/profile'); + const backViewPage = CoreNavigator.getPreviousPath(); + this.showInfo = !backViewPage || !CoreTextUtils.matchesGlob(backViewPage, '**/user/profile'); this.route.queryParams.subscribe(async (params) => { this.loaded = false; - this.conversationId = CoreNavigator.instance.getRouteNumberParam('conversationId', params) || undefined; - this.userId = CoreNavigator.instance.getRouteNumberParam('userId', params) || undefined; - this.showKeyboard = CoreNavigator.instance.getRouteBooleanParam('showKeyboard', params) || false; + this.conversationId = CoreNavigator.getRouteNumberParam('conversationId', params) || undefined; + this.userId = CoreNavigator.getRouteNumberParam('userId', params) || undefined; + this.showKeyboard = CoreNavigator.getRouteBooleanParam('showKeyboard', params) || false; await this.fetchData(); @@ -245,12 +245,12 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView protected async fetchData(): Promise { let loader: CoreIonLoadingElement | undefined; if (this.showLoadingModal) { - loader = await CoreDomUtils.instance.showModalLoading(); + loader = await CoreDomUtils.showModalLoading(); } if (!this.groupMessagingEnabled && this.userId) { // Get the user profile to retrieve the user fullname and image. - CoreUser.instance.getProfile(this.userId, undefined, true).then((user) => { + CoreUser.getProfile(this.userId, undefined, true).then((user) => { if (!this.title) { this.title = user.fullname; } @@ -264,9 +264,9 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView // Synchronize messages if needed. try { - const syncResult = await AddonMessagesSync.instance.syncDiscussion(this.conversationId, this.userId); + const syncResult = await AddonMessagesSync.syncDiscussion(this.conversationId, this.userId); if (syncResult.warnings && syncResult.warnings[0]) { - CoreDomUtils.instance.showErrorModal(syncResult.warnings[0]); + CoreDomUtils.showErrorModal(syncResult.warnings[0]); } } catch { // Ignore errors; @@ -285,8 +285,8 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView if (this.userId) { // Get the member info. Invalidate first to make sure we get the latest status. - promises.push(AddonMessages.instance.invalidateMemberInfo(this.userId).then(async () => { - this.otherMember = await AddonMessages.instance.getMemberInfo(this.userId!); + promises.push(AddonMessages.invalidateMemberInfo(this.userId).then(async () => { + this.otherMember = await AddonMessages.getMemberInfo(this.userId!); if (!exists && this.otherMember) { this.conversationImage = this.otherMember.profileimageurl; @@ -303,7 +303,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView } else { if (this.userId) { // Fake the user member info. - promises.push(CoreUser.instance.getProfile(this.userId!).then(async (user) => { + promises.push(CoreUser.getProfile(this.userId!).then(async (user) => { this.otherMember = { id: user.id, fullname: user.fullname, @@ -319,8 +319,8 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView canmessage: true, requirescontact: false, }; - this.otherMember.isblocked = await AddonMessages.instance.isBlocked(this.userId!); - this.otherMember.iscontact = await AddonMessages.instance.isContact(this.userId!); + this.otherMember.isblocked = await AddonMessages.isBlocked(this.userId!); + this.otherMember.iscontact = await AddonMessages.isContact(this.userId!); this.blockIcon = this.otherMember.isblocked ? 'fas-user-lock' : 'fas-user-check'; return; @@ -350,7 +350,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView await Promise.all(promises); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingmessages', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingmessages', true); } finally { this.checkCanDelete(); this.resizeContent(); @@ -411,15 +411,15 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView try { // Wait for synchronization process to finish. - await AddonMessagesSync.instance.waitForSyncConversation(this.conversationId, this.userId); + await AddonMessagesSync.waitForSyncConversation(this.conversationId, this.userId); let messages: AddonMessagesConversationMessageFormatted[] = []; // Fetch messages. Invalidate the cache before fetching. if (this.groupMessagingEnabled) { - await AddonMessages.instance.invalidateConversationMessages(this.conversationId!); + await AddonMessages.invalidateConversationMessages(this.conversationId!); messages = await this.getConversationMessages(this.pagesLoaded); } else { - await AddonMessages.instance.invalidateDiscussionCache(this.userId!); + await AddonMessages.invalidateDiscussionCache(this.userId!); messages = await this.getDiscussionMessages(this.pagesLoaded); } @@ -472,7 +472,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView } // Sort the messages. - AddonMessages.instance.sortMessages(this.messages); + AddonMessages.sortMessages(this.messages); // Calculate which messages need to display the date or user data. this.messages.forEach((message, index) => { @@ -567,17 +567,17 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView // Try to get the conversationId if we don't have it. if (!conversationId && userId) { try { - if (userId == this.currentUserId && AddonMessages.instance.isSelfConversationEnabled()) { - fallbackConversation = await AddonMessages.instance.getSelfConversation(); + if (userId == this.currentUserId && AddonMessages.isSelfConversationEnabled()) { + fallbackConversation = await AddonMessages.getSelfConversation(); } else { - fallbackConversation = await AddonMessages.instance.getConversationBetweenUsers(userId, undefined, true); + fallbackConversation = await AddonMessages.getConversationBetweenUsers(userId, undefined, true); } conversationId = fallbackConversation.id; } catch (error) { // Probably conversation does not exist or user is offline. Try to load offline messages. this.isSelf = userId == this.currentUserId; - const messages = await AddonMessagesOffline.instance.getMessages(userId); + const messages = await AddonMessagesOffline.getMessages(userId); if (messages && messages.length) { // We have offline messages, this probably means that the conversation didn't exist. Don't display error. @@ -598,10 +598,10 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView // Retrieve the conversation. Invalidate data first to get the right unreadcount. - await AddonMessages.instance.invalidateConversation(conversationId!); + await AddonMessages.invalidateConversation(conversationId!); try { - this.conversation = await AddonMessages.instance.getConversation(conversationId!, undefined, true); + this.conversation = await AddonMessages.getConversation(conversationId!, undefined, true); } catch (error) { // Get conversation failed, use the fallback one if we have it. if (fallbackConversation) { @@ -649,7 +649,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView const excludePending = offset > 0; - const result = await AddonMessages.instance.getConversationMessages(this.conversationId, { + const result = await AddonMessages.getConversationMessages(this.conversationId, { excludePending: excludePending, limitFrom: offset, }); @@ -703,7 +703,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView const excludePending = lfReceivedUnread > 0 || lfReceivedRead > 0 || lfSentUnread > 0 || lfSentRead > 0; // Get next messages. - const result = await AddonMessages.instance.getDiscussion( + const result = await AddonMessages.getDiscussion( this.userId!, excludePending, lfReceivedUnread, @@ -752,7 +752,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView protected async markMessagesAsRead(forceMark: boolean): Promise { let readChanged = false; - if (AddonMessages.instance.isMarkAllMessagesReadEnabled()) { + if (AddonMessages.isMarkAllMessagesReadEnabled()) { let messageUnreadFound = false; // Mark all messages at a time if there is any unread message. @@ -771,9 +771,9 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView this.setUnreadLabelPosition(); if (this.groupMessagingEnabled) { - await AddonMessages.instance.markAllConversationMessagesRead(this.conversationId!); + await AddonMessages.markAllConversationMessagesRead(this.conversationId!); } else { - await AddonMessages.instance.markAllMessagesRead(this.userId); + await AddonMessages.markAllMessagesRead(this.userId); // Mark all messages as read. this.messages.forEach((message) => { @@ -791,9 +791,9 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView // Mark each message as read one by one. this.messages.forEach((message) => { - // If the message is unread, call AddonMessages.instance.markMessageRead. + // If the message is unread, call AddonMessages.markMessageRead. if (message.useridfrom != this.currentUserId && 'read' in message && !message.read) { - promises.push(AddonMessages.instance.markMessageRead(message.id).then(() => { + promises.push(AddonMessages.markMessageRead(message.id).then(() => { readChanged = true; message.read = true; @@ -927,7 +927,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView return Promise.resolve(); } - const deferred = CoreUtils.instance.promiseDefer(); + const deferred = CoreUtils.promiseDefer(); setTimeout(() => this.waitForFetch().finally(() => { deferred.resolve(); @@ -973,7 +973,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView */ copyMessage(message: AddonMessagesConversationMessageFormatted): void { const text = 'smallmessage' in message ? message.smallmessage || message.text || '' : message.text || ''; - CoreUtils.instance.copyToClipboard(CoreTextUtils.instance.decodeHTMLEntities(text)); + CoreUtils.copyToClipboard(CoreTextUtils.decodeHTMLEntities(text)); } /** @@ -999,23 +999,23 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView name: 'deleteforall', checked: false, value: true, - label: Translate.instance.instant('addon.messages.deleteforeveryone'), + label: Translate.instant('addon.messages.deleteforeveryone'), }]; } try { - const data: boolean[] = await CoreDomUtils.instance.showConfirm( - Translate.instance.instant(langKey), + const data: boolean[] = await CoreDomUtils.showConfirm( + Translate.instant(langKey), undefined, undefined, undefined, options, ); - const modal = await CoreDomUtils.instance.showModalLoading('core.deleting', true); + const modal = await CoreDomUtils.showModalLoading('core.deleting', true); try { - await AddonMessages.instance.deleteMessage(message, data && data[0]); + await AddonMessages.deleteMessage(message, data && data[0]); // Remove message from the list without having to wait for re-fetch. this.messages.splice(index, 1); this.removeMessage(message.hash!); @@ -1026,7 +1026,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView modal.dismiss(); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errordeletemessage', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errordeletemessage', true); } } @@ -1065,7 +1065,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView } catch (error) { this.loadMoreError = true; // Set to prevent infinite calls with infinite-loading. this.pagesLoaded--; - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingmessages', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingmessages', true); } finally { infiniteComplete && infiniteComplete(); } @@ -1147,7 +1147,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView if (this.newMessages > 0) { const messages = Array.from(document.querySelectorAll('.addon-message-not-mine')); - CoreDomUtils.instance.scrollToElement(this.content!, messages[messages.length - this.newMessages]); + CoreDomUtils.scrollToElement(this.content!, messages[messages.length - this.newMessages]); } } @@ -1186,9 +1186,9 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView try { let data: AddonMessagesSendMessageResults; if (this.conversationId) { - data = await AddonMessages.instance.sendMessageToConversation(this.conversation!, text); + data = await AddonMessages.sendMessageToConversation(this.conversation!, text); } else { - data = await AddonMessages.instance.sendMessage(this.userId!, text); + data = await AddonMessages.sendMessage(this.userId!, text); } @@ -1235,9 +1235,9 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView // Only close the keyboard if an error happens. // We want the user to be able to send multiple messages without the keyboard being closed. - CoreApp.instance.closeKeyboard(); + CoreApp.closeKeyboard(); - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.messagenotsent', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.messagenotsent', true); this.removeMessage(message.hash!); } } @@ -1310,7 +1310,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView async viewInfo(): Promise { if (this.isGroup) { // Display the group information. - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: AddonMessagesConversationInfoComponent, componentProps: { conversationId: this.conversationId, @@ -1322,7 +1322,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView const result = await modal.onDidDismiss(); if (typeof result.data != 'undefined') { - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/messages/**/discussion'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/messages/**/discussion'); // Open user conversation. if (splitViewLoaded) { @@ -1334,12 +1334,12 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView ); } else { // Open the discussion in a new view. - CoreNavigator.instance.navigateToSitePath('/messages/discussion', { params: { userId: result.data.userId } }); + CoreNavigator.navigateToSitePath('/messages/discussion', { params: { userId: result.data.userId } }); } } } else { // Open the user profile. - CoreNavigator.instance.navigateToSitePath('/user/profile', { params: { userId: this.userId } }); + CoreNavigator.navigateToSitePath('/user/profile', { params: { userId: this.userId } }); } } @@ -1356,12 +1356,12 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView this.favouriteIcon = CoreConstants.ICON_LOADING; try { - await AddonMessages.instance.setFavouriteConversation(this.conversation.id, !this.conversation.isfavourite); + await AddonMessages.setFavouriteConversation(this.conversation.id, !this.conversation.isfavourite); this.conversation.isfavourite = !this.conversation.isfavourite; // Get the conversation data so it's cached. Don't block the user for this. - AddonMessages.instance.getConversation(this.conversation.id, undefined, true); + AddonMessages.getConversation(this.conversation.id, undefined, true); CoreEvents.trigger(AddonMessagesProvider.UPDATE_CONVERSATION_LIST_EVENT, { conversationId: this.conversation.id, @@ -1369,7 +1369,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView value: this.conversation.isfavourite, }, this.siteId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error changing favourite state.'); + CoreDomUtils.showErrorModalDefault(error, 'Error changing favourite state.'); } finally { this.favouriteIcon = 'fas-star'; this.favouriteIconSlash = this.conversation.isfavourite; @@ -1390,11 +1390,11 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView this.muteIcon = CoreConstants.ICON_LOADING; try { - await AddonMessages.instance.muteConversation(this.conversation.id, !this.conversation.ismuted); + await AddonMessages.muteConversation(this.conversation.id, !this.conversation.ismuted); this.conversation.ismuted = !this.conversation.ismuted; // Get the conversation data so it's cached. Don't block the user for this. - AddonMessages.instance.getConversation(this.conversation.id, undefined, true); + AddonMessages.getConversation(this.conversation.id, undefined, true); CoreEvents.trigger(AddonMessagesProvider.UPDATE_CONVERSATION_LIST_EVENT, { conversationId: this.conversation.id, @@ -1403,7 +1403,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView }, this.siteId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error changing muted state.'); + CoreDomUtils.showErrorModalDefault(error, 'Error changing muted state.'); } finally { this.muteIcon = this.conversation.ismuted ? 'fas-bell' : 'fas-bell-slash'; done && done(); @@ -1457,25 +1457,25 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView throw new CoreError('No member selected to be blocked.'); } - const template = Translate.instance.instant('addon.messages.blockuserconfirm', { $a: this.otherMember.fullname }); - const okText = Translate.instance.instant('addon.messages.blockuser'); + const template = Translate.instant('addon.messages.blockuserconfirm', { $a: this.otherMember.fullname }); + const okText = Translate.instant('addon.messages.blockuser'); try { - await CoreDomUtils.instance.showConfirm(template, undefined, okText); + await CoreDomUtils.showConfirm(template, undefined, okText); this.blockIcon = CoreConstants.ICON_LOADING; - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); this.showLoadingModal = true; try { try { - await AddonMessages.instance.blockContact(this.otherMember.id); + await AddonMessages.blockContact(this.otherMember.id); } finally { modal.dismiss(); this.showLoadingModal = false; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); } finally { this.blockIcon = this.otherMember.isblocked ? 'fas-user-lock' : 'fas-user-check'; } @@ -1497,12 +1497,12 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView const confirmMessage = 'addon.messages.' + (this.isSelf ? 'deleteallselfconfirm' : 'deleteallconfirm'); try { - await CoreDomUtils.instance.showDeleteConfirm(confirmMessage); + await CoreDomUtils.showDeleteConfirm(confirmMessage); this.deleteIcon = CoreConstants.ICON_LOADING; try { try { - await AddonMessages.instance.deleteConversation(this.conversation.id); + await AddonMessages.deleteConversation(this.conversation.id); CoreEvents.trigger( AddonMessagesProvider.UPDATE_CONVERSATION_LIST_EVENT, @@ -1518,7 +1518,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView done && done(); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error deleting conversation.'); + CoreDomUtils.showErrorModalDefault(error, 'Error deleting conversation.'); } finally { this.deleteIcon = 'fas-trash'; } @@ -1538,26 +1538,26 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView throw new CoreError('No member selected to be unblocked.'); } - const template = Translate.instance.instant('addon.messages.unblockuserconfirm', { $a: this.otherMember.fullname }); - const okText = Translate.instance.instant('addon.messages.unblockuser'); + const template = Translate.instant('addon.messages.unblockuserconfirm', { $a: this.otherMember.fullname }); + const okText = Translate.instant('addon.messages.unblockuser'); try { - await CoreDomUtils.instance.showConfirm(template, undefined, okText); + await CoreDomUtils.showConfirm(template, undefined, okText); this.blockIcon = CoreConstants.ICON_LOADING; - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); this.showLoadingModal = true; try { try { - await AddonMessages.instance.unblockContact(this.otherMember.id); + await AddonMessages.unblockContact(this.otherMember.id); } finally { modal.dismiss(); this.showLoadingModal = false; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); } finally { this.blockIcon = this.otherMember.isblocked ? 'fas-user-lock' : 'fas-user-check'; } @@ -1577,26 +1577,26 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView throw new CoreError('No member selected to be requested.'); } - const template = Translate.instance.instant('addon.messages.addcontactconfirm', { $a: this.otherMember.fullname }); - const okText = Translate.instance.instant('core.add'); + const template = Translate.instant('addon.messages.addcontactconfirm', { $a: this.otherMember.fullname }); + const okText = Translate.instant('core.add'); try { - await CoreDomUtils.instance.showConfirm(template, undefined, okText); + await CoreDomUtils.showConfirm(template, undefined, okText); this.addRemoveIcon = CoreConstants.ICON_LOADING; - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); this.showLoadingModal = true; try { try { - await AddonMessages.instance.createContactRequest(this.otherMember.id); + await AddonMessages.createContactRequest(this.otherMember.id); } finally { modal.dismiss(); this.showLoadingModal = false; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); } finally { this.addRemoveIcon = 'fas-user-plus'; } @@ -1616,18 +1616,18 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView throw new CoreError('No member selected to be confirmed.'); } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); this.showLoadingModal = true; try { try { - await AddonMessages.instance.confirmContactRequest(this.otherMember.id); + await AddonMessages.confirmContactRequest(this.otherMember.id); } finally { modal.dismiss(); this.showLoadingModal = false; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); } } @@ -1642,18 +1642,18 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView throw new CoreError('No member selected to be declined.'); } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); this.showLoadingModal = true; try { try { - await AddonMessages.instance.declineContactRequest(this.otherMember.id); + await AddonMessages.declineContactRequest(this.otherMember.id); } finally { modal.dismiss(); this.showLoadingModal = false; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); } } @@ -1668,26 +1668,26 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView throw new CoreError('No member selected to be removed.'); } - const template = Translate.instance.instant('addon.messages.removecontactconfirm', { $a: this.otherMember.fullname }); - const okText = Translate.instance.instant('core.remove'); + const template = Translate.instant('addon.messages.removecontactconfirm', { $a: this.otherMember.fullname }); + const okText = Translate.instant('core.remove'); try { - await CoreDomUtils.instance.showConfirm(template, undefined, okText); + await CoreDomUtils.showConfirm(template, undefined, okText); this.addRemoveIcon = CoreConstants.ICON_LOADING; - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); this.showLoadingModal = true; try { try { - await AddonMessages.instance.removeContact(this.otherMember.id); + await AddonMessages.removeContact(this.otherMember.id); } finally { modal.dismiss(); this.showLoadingModal = false; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); } finally { this.addRemoveIcon = 'fas-user-plus'; } diff --git a/src/addons/messages/pages/discussions-35/discussions.module.ts b/src/addons/messages/pages/discussions-35/discussions.module.ts index 425fd5620..2406cee87 100644 --- a/src/addons/messages/pages/discussions-35/discussions.module.ts +++ b/src/addons/messages/pages/discussions-35/discussions.module.ts @@ -42,8 +42,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; @NgModule({ diff --git a/src/addons/messages/pages/discussions-35/discussions.page.ts b/src/addons/messages/pages/discussions-35/discussions.page.ts index b9cfa73a5..b3e0f7310 100644 --- a/src/addons/messages/pages/discussions-35/discussions.page.ts +++ b/src/addons/messages/pages/discussions-35/discussions.page.ts @@ -69,9 +69,9 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { protected route: ActivatedRoute, ) { - this.search.loading = Translate.instance.instant('core.searching'); - this.loadingMessages = Translate.instance.instant('core.loading'); - this.siteId = CoreSites.instance.getCurrentSiteId(); + this.search.loading = Translate.instant('core.searching'); + this.loadingMessages = Translate.instant('core.loading'); + this.siteId = CoreSites.getCurrentSiteId(); // Update discussions when new message is received. this.newMessagesObserver = CoreEvents.on( @@ -107,8 +107,8 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { discussion.unread = false; // Conversations changed, invalidate them and refresh unread counts. - AddonMessages.instance.invalidateConversations(this.siteId); - AddonMessages.instance.refreshUnreadConversationCounts(this.siteId); + AddonMessages.invalidateConversations(this.siteId); + AddonMessages.refreshUnreadConversationCounts(this.siteId); } } }, @@ -116,7 +116,7 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { ); // Refresh the view when the app is resumed. - this.appResumeSubscription = Platform.instance.resume.subscribe(() => { + this.appResumeSubscription = Platform.resume.subscribe(() => { if (!this.loaded) { return; } @@ -126,10 +126,10 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { // If a message push notification is received, refresh the view. - this.pushObserver = CorePushNotificationsDelegate.instance.on('receive') + this.pushObserver = CorePushNotificationsDelegate.on('receive') .subscribe((notification) => { // New message received. If it's from current site, refresh the data. - if (CoreUtils.instance.isFalseOrZero(notification.notif) && notification.site == this.siteId) { + if (CoreUtils.isFalseOrZero(notification.notif) && notification.site == this.siteId) { // Don't refresh unread counts, it's refreshed from the main menu handler in this case. this.refreshData(undefined, false); } @@ -141,8 +141,8 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { */ ngOnInit(): void { this.route.queryParams.subscribe(async (params) => { - const discussionUserId = CoreNavigator.instance.getRouteNumberParam('discussionUserId', params) || - CoreNavigator.instance.getRouteNumberParam('userId', params) || undefined; + const discussionUserId = CoreNavigator.getRouteNumberParam('discussionUserId', params) || + CoreNavigator.getRouteNumberParam('userId', params) || undefined; if (this.loaded && this.discussionUserId == discussionUserId) { return; @@ -157,7 +157,7 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { await this.fetchData(); - if (!this.discussionUserId && this.discussions.length > 0 && CoreScreen.instance.isTablet) { + if (!this.discussionUserId && this.discussions.length > 0 && CoreScreen.isTablet) { // Take first and load it. this.gotoDiscussion(this.discussions[0].message!.user); } @@ -173,13 +173,13 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { */ async refreshData(refresher?: CustomEvent, refreshUnreadCounts: boolean = true): Promise { const promises: Promise[] = []; - promises.push(AddonMessages.instance.invalidateDiscussionsCache(this.siteId)); + promises.push(AddonMessages.invalidateDiscussionsCache(this.siteId)); if (refreshUnreadCounts) { - promises.push(AddonMessages.instance.invalidateUnreadConversationCounts(this.siteId)); + promises.push(AddonMessages.invalidateUnreadConversationCounts(this.siteId)); } - await CoreUtils.instance.allPromises(promises).finally(() => this.fetchData().finally(() => { + await CoreUtils.allPromises(promises).finally(() => this.fetchData().finally(() => { if (refresher) { refresher?.detail.complete(); } @@ -193,11 +193,11 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { */ protected async fetchData(): Promise { this.loadingMessage = this.loadingMessages; - this.search.enabled = AddonMessages.instance.isSearchMessagesEnabled(); + this.search.enabled = AddonMessages.isSearchMessagesEnabled(); const promises: Promise[] = []; - promises.push(AddonMessages.instance.getDiscussions(this.siteId).then((discussions) => { + promises.push(AddonMessages.getDiscussions(this.siteId).then((discussions) => { // Convert to an array for sorting. const discussionsSorted: AddonMessagesDiscussion[] = []; for (const userId in discussions) { @@ -211,12 +211,12 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { return; })); - promises.push(AddonMessages.instance.getUnreadConversationCounts(this.siteId)); + promises.push(AddonMessages.getUnreadConversationCounts(this.siteId)); try { await Promise.all(promises); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true); } this.loaded = true; @@ -241,16 +241,16 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { * @return Resolved when done. */ async searchMessage(query: string): Promise { - CoreApp.instance.closeKeyboard(); + CoreApp.closeKeyboard(); this.loaded = false; this.loadingMessage = this.search.loading; try { - const searchResults = await AddonMessages.instance.searchMessages(query, undefined, undefined, undefined, this.siteId); + const searchResults = await AddonMessages.searchMessages(query, undefined, undefined, undefined, this.siteId); this.search.showResults = true; this.search.results = searchResults.messages; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingmessages', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingmessages', true); } this.loaded = true; @@ -274,10 +274,10 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { params.message = messageId; } - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/messages/index/discussion'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/messages/index/discussion'); const path = (splitViewLoaded ? '../' : '') + 'discussion'; - CoreNavigator.instance.navigate(path, { params }); + CoreNavigator.navigate(path, { params }); } /** @@ -286,11 +286,11 @@ export class AddonMessagesDiscussions35Page implements OnInit, OnDestroy { gotoContacts(): void { const params: Params = {}; - if (CoreScreen.instance.isTablet && this.discussionUserId) { + if (CoreScreen.isTablet && this.discussionUserId) { params.discussionUserId = this.discussionUserId; } - CoreNavigator.instance.navigateToSitePath('contacts-35', { params }); + CoreNavigator.navigateToSitePath('contacts-35', { params }); } /** diff --git a/src/addons/messages/pages/group-conversations/group-conversations.module.ts b/src/addons/messages/pages/group-conversations/group-conversations.module.ts index 5ce6c6439..33f437be7 100644 --- a/src/addons/messages/pages/group-conversations/group-conversations.module.ts +++ b/src/addons/messages/pages/group-conversations/group-conversations.module.ts @@ -41,8 +41,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; @NgModule({ diff --git a/src/addons/messages/pages/group-conversations/group-conversations.page.ts b/src/addons/messages/pages/group-conversations/group-conversations.page.ts index 7e965b31b..a198e06c6 100644 --- a/src/addons/messages/pages/group-conversations/group-conversations.page.ts +++ b/src/addons/messages/pages/group-conversations/group-conversations.page.ts @@ -108,9 +108,9 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { constructor( protected route: ActivatedRoute, ) { - this.loadingMessage = Translate.instance.instant('core.loading'); - this.siteId = CoreSites.instance.getCurrentSiteId(); - this.currentUserId = CoreSites.instance.getCurrentSiteUserId(); + this.loadingMessage = Translate.instant('core.loading'); + this.siteId = CoreSites.getCurrentSiteId(); + this.currentUserId = CoreSites.getCurrentSiteUserId(); // Update conversations when new message is received. this.newMessagesObserver = CoreEvents.on( @@ -145,7 +145,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { // Sort the affected list. const option = this.getConversationOption(conversation); - option.conversations = AddonMessages.instance.sortConversations(option.conversations || []); + option.conversations = AddonMessages.sortConversations(option.conversations || []); if (isNewer) { // The last message is newer than the previous one, scroll to top to keep viewing the conversation. @@ -168,8 +168,8 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { conversation.unreadcount = 0; // Conversations changed, invalidate them and refresh unread counts. - AddonMessages.instance.invalidateConversations(this.siteId); - AddonMessages.instance.refreshUnreadConversationCounts(this.siteId); + AddonMessages.invalidateConversations(this.siteId); + AddonMessages.refreshUnreadConversationCounts(this.siteId); } } }, this.siteId); @@ -186,7 +186,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { ); // Refresh the view when the app is resumed. - this.appResumeSubscription = Platform.instance.resume.subscribe(() => { + this.appResumeSubscription = Platform.resume.subscribe(() => { if (!this.loaded) { return; } @@ -221,10 +221,10 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { ); // If a message push notification is received, refresh the view. - this.pushObserver = CorePushNotificationsDelegate.instance.on('receive') + this.pushObserver = CorePushNotificationsDelegate.on('receive') .subscribe((notification) => { // New message received. If it's from current site, refresh the data. - if (CoreUtils.instance.isFalseOrZero(notification.notif) && notification.site == this.siteId) { + if (CoreUtils.isFalseOrZero(notification.notif) && notification.site == this.siteId) { // Don't refresh unread counts, it's refreshed from the main menu handler in this case. this.refreshData(undefined, false); } @@ -281,9 +281,9 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { ngOnInit(): void { this.route.queryParams.subscribe(async (params) => { // Conversation to load. - this.conversationId = CoreNavigator.instance.getRouteNumberParam('conversationId', params) || undefined; + this.conversationId = CoreNavigator.getRouteNumberParam('conversationId', params) || undefined; if (!this.conversationId) { - this.discussionUserId = CoreNavigator.instance.getRouteNumberParam('discussionUserId', params) || undefined; + this.discussionUserId = CoreNavigator.getRouteNumberParam('discussionUserId', params) || undefined; } if (this.conversationId || this.discussionUserId) { @@ -292,7 +292,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { } await this.fetchData(); - if (!this.conversationId && !this.discussionUserId && CoreScreen.instance.isTablet) { + if (!this.conversationId && !this.discussionUserId && CoreScreen.isTablet) { // Load the first conversation. let conversation: AddonMessagesConversationForList; const expandedOption = this.getExpandedOption(); @@ -321,9 +321,9 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { promises.push(this.fetchConversationCounts()); // View updated by the events observers. - promises.push(AddonMessages.instance.getContactRequestsCount(this.siteId)); + promises.push(AddonMessages.getContactRequestsCount(this.siteId)); if (refreshUnreadCounts) { - promises.push(AddonMessages.instance.refreshUnreadConversationCounts(this.siteId)); + promises.push(AddonMessages.refreshUnreadConversationCounts(this.siteId)); } try { @@ -356,7 +356,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { // Load the data for the expanded option. await this.fetchDataForExpandedOption(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true); } this.loaded = true; } @@ -409,14 +409,14 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { AddonMessagesOfflineAnyMessagesFormatted[] = []; // Get the conversations and, if needed, the offline messages. Always try to get the latest data. - promises.push(AddonMessages.instance.invalidateConversations(this.siteId).then(async () => { - data = await AddonMessages.instance.getConversations(option.type, option.favourites, limitFrom, this.siteId); + promises.push(AddonMessages.invalidateConversations(this.siteId).then(async () => { + data = await AddonMessages.getConversations(option.type, option.favourites, limitFrom, this.siteId); return; })); if (!loadingMore) { - promises.push(AddonMessagesOffline.instance.getAllMessages().then((messages) => { + promises.push(AddonMessagesOffline.getAllMessages().then((messages) => { offlineMessages = messages; return; @@ -425,7 +425,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { if (getCounts) { promises.push(this.fetchConversationCounts()); - promises.push(AddonMessages.instance.refreshUnreadConversationCounts(this.siteId)); + promises.push(AddonMessages.refreshUnreadConversationCounts(this.siteId)); } await Promise.all(promises); @@ -441,7 +441,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { await this.loadOfflineMessages(option, offlineMessages); // Sort the conversations, the offline messages could affect the order. - option.conversations = AddonMessages.instance.sortConversations(option.conversations); + option.conversations = AddonMessages.sortConversations(option.conversations); } } } @@ -453,9 +453,9 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { */ protected async fetchConversationCounts(): Promise { // Always try to get the latest data. - await AddonMessages.instance.invalidateConversationCounts(this.siteId); + await AddonMessages.invalidateConversationCounts(this.siteId); - const counts = await AddonMessages.instance.getConversationCounts(this.siteId); + const counts = await AddonMessages.getConversationCounts(this.siteId); this.favourites.count = counts.favourites; this.individual.count = counts.individual + counts.self; // Self is only returned if it's not favourite. this.group.count = counts.group; @@ -509,7 +509,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { * Navigate to contacts view. */ gotoContacts(): void { - CoreNavigator.instance.navigateToSitePath('contacts'); + CoreNavigator.navigateToSitePath('contacts'); } /** @@ -534,16 +534,16 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { params.message = messageId; } - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/messages/group-conversations/discussion'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/messages/group-conversations/discussion'); const path = (splitViewLoaded ? '../' : '') + 'discussion'; - CoreNavigator.instance.navigate(path, { params }); + CoreNavigator.navigate(path, { params }); } /** * Navigate to message settings. */ gotoSettings(): void { - CoreNavigator.instance.navigateToSitePath(AddonMessagesSettingsHandlerService.PAGE_NAME); + CoreNavigator.navigateToSitePath(AddonMessagesSettingsHandlerService.PAGE_NAME); } /** @@ -557,7 +557,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { try { await this.fetchDataForOption(option, true); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true); option.loadMoreError = true; } @@ -625,7 +625,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { } } else { // Get the user data and create a new conversation if it belongs to the current option. - promises.push(CoreUser.instance.getProfile(message.touserid, undefined, true).catch(() => { + promises.push(CoreUser.getProfile(message.touserid, undefined, true).catch(() => { // User not found. }).then((user) => { const conversation: AddonMessagesConversationForList = { @@ -711,7 +711,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { async refreshData(refresher?: CustomEvent, refreshUnreadCounts: boolean = true): Promise { // Don't invalidate conversations and so, they always try to get latest data. try { - await AddonMessages.instance.invalidateContactRequestsCountCache(this.siteId); + await AddonMessages.invalidateContactRequestsCountCache(this.siteId); } finally { try { await this.fetchData(refreshUnreadCounts); @@ -736,7 +736,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { } else { // Pass getCounts=true to update the counts everytime the user expands an option. this.expandOption(option, true).catch((error) => { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingdiscussions', true); }); } } @@ -790,7 +790,7 @@ export class AddonMessagesGroupConversationsPage implements OnInit, OnDestroy { * Navigate to the search page. */ gotoSearch(): void { - CoreNavigator.instance.navigateToSitePath('search'); + CoreNavigator.navigateToSitePath('search'); } /** diff --git a/src/addons/messages/pages/search/search.module.ts b/src/addons/messages/pages/search/search.module.ts index 050f2c995..eb3083df2 100644 --- a/src/addons/messages/pages/search/search.module.ts +++ b/src/addons/messages/pages/search/search.module.ts @@ -42,8 +42,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; @NgModule({ diff --git a/src/addons/messages/pages/search/search.page.ts b/src/addons/messages/pages/search/search.page.ts index 7ecef5284..7d98abb95 100644 --- a/src/addons/messages/pages/search/search.page.ts +++ b/src/addons/messages/pages/search/search.page.ts @@ -96,7 +96,7 @@ export class AddonMessagesSearchPage implements OnDestroy { } }); }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } @@ -108,9 +108,9 @@ export class AddonMessagesSearchPage implements OnDestroy { this.displayResults = false; // Empty details. - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/messages/search/discussion'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/messages/search/discussion'); if (splitViewLoaded) { - CoreNavigator.instance.navigate('../'); + CoreNavigator.navigate('../'); } } @@ -123,7 +123,7 @@ export class AddonMessagesSearchPage implements OnDestroy { * @return Resolved when done. */ async search(query: string, loadMore?: 'contacts' | 'noncontacts' | 'messages', infiniteComplete?: () => void): Promise { - CoreApp.instance.closeKeyboard(); + CoreApp.closeKeyboard(); this.query = query; this.disableSearch = true; @@ -149,7 +149,7 @@ export class AddonMessagesSearchPage implements OnDestroy { } promises.push( - AddonMessages.instance.searchUsers(query, limitFrom, limitNum).then((result) => { + AddonMessages.searchUsers(query, limitFrom, limitNum).then((result) => { if (!loadMore || loadMore == 'contacts') { newContacts = result.contacts; canLoadMoreContacts = result.canLoadMoreContacts; @@ -172,7 +172,7 @@ export class AddonMessagesSearchPage implements OnDestroy { } promises.push( - AddonMessages.instance.searchMessages(query, undefined, limitFrom).then((result) => { + AddonMessages.searchMessages(query, undefined, limitFrom).then((result) => { newMessages = result.messages; canLoadMoreMessages = result.canLoadMore; @@ -220,7 +220,7 @@ export class AddonMessagesSearchPage implements OnDestroy { } } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingusers', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingusers', true); if (loadMore == 'messages') { this.messages.loadMoreError = true; @@ -248,7 +248,7 @@ export class AddonMessagesSearchPage implements OnDestroy { * @param onInit Whether the tser was selected on initial load. */ openConversation(result: AddonMessagesConversationMember | AddonMessagesMessageAreaContact, onInit: boolean = false): void { - if (!onInit || CoreScreen.instance.isTablet) { + if (!onInit || CoreScreen.isTablet) { this.selectedResult = result; const params: Params = {}; @@ -258,9 +258,9 @@ export class AddonMessagesSearchPage implements OnDestroy { params.userId = result.id; } - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/messages/search/discussion'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/messages/search/discussion'); const path = (splitViewLoaded ? '../' : '') + 'discussion'; - CoreNavigator.instance.navigate(path, { params }); + CoreNavigator.navigate(path, { params }); } } diff --git a/src/addons/messages/pages/settings/settings.page.ts b/src/addons/messages/pages/settings/settings.page.ts index 0fe82855e..4a0cf0f89 100644 --- a/src/addons/messages/pages/settings/settings.page.ts +++ b/src/addons/messages/pages/settings/settings.page.ts @@ -54,16 +54,16 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { constructor() { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); this.advancedContactable = !!currentSite?.isVersionGreaterEqualThan('3.6'); this.allowSiteMessaging = !!currentSite?.canUseAdvancedFeature('messagingallusers'); - this.groupMessagingEnabled = AddonMessages.instance.isGroupMessagingEnabled(); + this.groupMessagingEnabled = AddonMessages.isGroupMessagingEnabled(); this.asyncInit(); } protected async asyncInit(): Promise { - this.sendOnEnter = !!(await CoreConfig.instance.get(CoreConstants.SETTINGS_SEND_ON_ENTER, !CoreApp.instance.isMobile())); + this.sendOnEnter = !!(await CoreConfig.get(CoreConstants.SETTINGS_SEND_ON_ENTER, !CoreApp.isMobile())); } /** @@ -82,7 +82,7 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { */ protected async fetchPreferences(): Promise { try { - const preferences = await AddonMessages.instance.getMessagePreferences(); + const preferences = await AddonMessages.getMessagePreferences(); if (this.groupMessagingEnabled) { // Simplify the preferences. for (const component of preferences.components) { @@ -104,7 +104,7 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { this.contactablePrivacy = preferences.blocknoncontacts; this.previousContactableValue = this.contactablePrivacy; } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { this.preferencesLoaded = true; } @@ -114,7 +114,7 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { * Update preferences. The purpose is to store the updated data, it won't be reflected in the view. */ protected updatePreferences(): void { - AddonMessages.instance.invalidateMessagePreferences().finally(() => { + AddonMessages.invalidateMessagePreferences().finally(() => { this.fetchPreferences(); }); } @@ -143,7 +143,7 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { return; } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); if (!this.advancedContactable) { // Convert from boolean to number. @@ -151,13 +151,13 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { } try { - await CoreUser.instance.updateUserPreference('message_blocknoncontacts', String(value)); + await CoreUser.updateUserPreference('message_blocknoncontacts', String(value)); // Update the preferences since they were modified. this.updatePreferencesAfterDelay(); this.previousContactableValue = this.contactablePrivacy; } catch (message) { // Show error and revert change. - CoreDomUtils.instance.showErrorModal(message); + CoreDomUtils.showErrorModal(message); this.contactablePrivacy = this.previousContactableValue; } finally { modal.dismiss(); @@ -196,8 +196,8 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { notification.updating = true; - promises.push(CoreUser.instance.updateUserPreference(notification.preferencekey + '_loggedin', value)); - promises.push(CoreUser.instance.updateUserPreference(notification.preferencekey + '_loggedoff', value)); + promises.push(CoreUser.updateUserPreference(notification.preferencekey + '_loggedin', value)); + promises.push(CoreUser.updateUserPreference(notification.preferencekey + '_loggedoff', value)); try { await Promise.all(promises); @@ -205,7 +205,7 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { this.updatePreferencesAfterDelay(); } catch (error) { // Show error and revert change. - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); processor.checked = !processor.checked; } finally { notification.updating = false; @@ -234,12 +234,12 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { notification.updating[state] = true; try { - await CoreUser.instance.updateUserPreference(preferenceName, value); + await CoreUser.updateUserPreference(preferenceName, value); // Update the preferences since they were modified. this.updatePreferencesAfterDelay(); } catch (error) { // Show error and revert change. - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); processorState.checked = !processorState.checked; } finally { notification.updating[state] = false; @@ -252,7 +252,7 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { * @param refresher Refresher. */ refreshPreferences(refresher?: CustomEvent): void { - AddonMessages.instance.invalidateMessagePreferences().finally(() => { + AddonMessages.invalidateMessagePreferences().finally(() => { this.fetchPreferences().finally(() => { refresher?.detail.complete(); }); @@ -261,13 +261,13 @@ export class AddonMessagesSettingsPage implements OnInit, OnDestroy { sendOnEnterChanged(): void { // Save the value. - CoreConfig.instance.set(CoreConstants.SETTINGS_SEND_ON_ENTER, this.sendOnEnter ? 1 : 0); + CoreConfig.set(CoreConstants.SETTINGS_SEND_ON_ENTER, this.sendOnEnter ? 1 : 0); // Notify the app. CoreEvents.trigger( CoreEvents.SEND_ON_ENTER_CHANGED, { sendOnEnter: !!this.sendOnEnter }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } diff --git a/src/addons/messages/services/handlers/contact-request-link.ts b/src/addons/messages/services/handlers/contact-request-link.ts index 7c3622647..a06eb6e11 100644 --- a/src/addons/messages/services/handlers/contact-request-link.ts +++ b/src/addons/messages/services/handlers/contact-request-link.ts @@ -36,7 +36,7 @@ export class AddonMessagesContactRequestLinkHandlerService extends CoreContentLi getActions(): CoreContentLinksAction[] | Promise { return [{ action: (siteId): void => { - CoreNavigator.instance.navigateToSitePath('/messages/contacts', { siteId }); + CoreNavigator.navigateToSitePath('/messages/contacts', { siteId }); }, }]; } @@ -49,14 +49,14 @@ export class AddonMessagesContactRequestLinkHandlerService extends CoreContentLi * @return Whether the handler is enabled for the URL and site. */ async isEnabled(siteId: string): Promise { - const enabled = await AddonMessages.instance.isPluginEnabled(siteId); + const enabled = await AddonMessages.isPluginEnabled(siteId); if (!enabled) { return false; } - return AddonMessages.instance.isGroupMessagingEnabledInSite(siteId); + return AddonMessages.isGroupMessagingEnabledInSite(siteId); } } -export class AddonMessagesContactRequestLinkHandler extends makeSingleton(AddonMessagesContactRequestLinkHandlerService) {} +export const AddonMessagesContactRequestLinkHandler = makeSingleton(AddonMessagesContactRequestLinkHandlerService); diff --git a/src/addons/messages/services/handlers/discussion-link.ts b/src/addons/messages/services/handlers/discussion-link.ts index 25f488ec3..b0fae3fce 100644 --- a/src/addons/messages/services/handlers/discussion-link.ts +++ b/src/addons/messages/services/handlers/discussion-link.ts @@ -49,7 +49,7 @@ export class AddonMessagesDiscussionLinkHandlerService extends CoreContentLinksH const stateParams = { userId: parseInt(params.id || params.user2, 10), }; - CoreNavigator.instance.navigateToSitePath('/messages/discussion', { params: stateParams, siteId }); + CoreNavigator.navigateToSitePath('/messages/discussion', { params: stateParams, siteId }); }, }]; } @@ -64,7 +64,7 @@ export class AddonMessagesDiscussionLinkHandlerService extends CoreContentLinksH * @return Whether the handler is enabled for the URL and site. */ async isEnabled(siteId: string, url: string, params: Record): Promise { - const enabled = await AddonMessages.instance.isPluginEnabled(siteId); + const enabled = await AddonMessages.isPluginEnabled(siteId); if (!enabled) { return false; } @@ -76,7 +76,7 @@ export class AddonMessagesDiscussionLinkHandlerService extends CoreContentLinksH if (typeof params.user1 != 'undefined') { // Check if user1 is the current user, since the app only supports current user. - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return parseInt(params.user1, 10) == site.getUserId(); } @@ -86,4 +86,4 @@ export class AddonMessagesDiscussionLinkHandlerService extends CoreContentLinksH } -export class AddonMessagesDiscussionLinkHandler extends makeSingleton(AddonMessagesDiscussionLinkHandlerService) {} +export const AddonMessagesDiscussionLinkHandler = makeSingleton(AddonMessagesDiscussionLinkHandlerService); diff --git a/src/addons/messages/services/handlers/index-link.ts b/src/addons/messages/services/handlers/index-link.ts index 33be2367b..7f0c6f352 100644 --- a/src/addons/messages/services/handlers/index-link.ts +++ b/src/addons/messages/services/handlers/index-link.ts @@ -38,9 +38,9 @@ export class AddonMessagesIndexLinkHandlerService extends CoreContentLinksHandle getActions(): CoreContentLinksAction[] | Promise { return [{ action: async (siteId): Promise => { - const pageName = await AddonMessages.instance.getMainMessagesPagePathInSite(siteId); + const pageName = await AddonMessages.getMainMessagesPagePathInSite(siteId); - CoreNavigator.instance.navigateToSitePath(pageName, { siteId }); + CoreNavigator.navigateToSitePath(pageName, { siteId }); }, }]; } @@ -53,9 +53,9 @@ export class AddonMessagesIndexLinkHandlerService extends CoreContentLinksHandle * @return Whether the handler is enabled for the URL and site. */ isEnabled(siteId: string): Promise { - return AddonMessages.instance.isPluginEnabled(siteId); + return AddonMessages.isPluginEnabled(siteId); } } -export class AddonMessagesIndexLinkHandler extends makeSingleton(AddonMessagesIndexLinkHandlerService) {} +export const AddonMessagesIndexLinkHandler = makeSingleton(AddonMessagesIndexLinkHandlerService); diff --git a/src/addons/messages/services/handlers/mainmenu.ts b/src/addons/messages/services/handlers/mainmenu.ts index 0998b4290..c8ef29716 100644 --- a/src/addons/messages/services/handlers/mainmenu.ts +++ b/src/addons/messages/services/handlers/mainmenu.ts @@ -45,7 +45,7 @@ export class AddonMessagesMainMenuHandlerService implements CoreMainMenuHandler, protected handler: CoreMainMenuHandlerToDisplay = { icon: 'fas-comments', title: 'addon.messages.messages', - page: AddonMessages.instance.getMainMessagesPagePath(), + page: AddonMessages.getMainMessagesPagePath(), class: 'addon-messages-handler', showBadge: true, // Do not check isMessageCountEnabled because we'll use fallback it not enabled. badge: '', @@ -82,19 +82,19 @@ export class AddonMessagesMainMenuHandlerService implements CoreMainMenuHandler, }); // If a message push notification is received, refresh the count. - CorePushNotificationsDelegate.instance.on('receive').subscribe( + CorePushNotificationsDelegate.on('receive').subscribe( (notification) => { // New message received. If it's from current site, refresh the data. - const isMessage = CoreUtils.instance.isFalseOrZero(notification.notif) || + const isMessage = CoreUtils.isFalseOrZero(notification.notif) || notification.name == 'messagecontactrequests'; - if (isMessage && CoreSites.instance.isCurrentSite(notification.site)) { + if (isMessage && CoreSites.isCurrentSite(notification.site)) { this.refreshBadge(notification.site); } }, ); // Register Badge counter. - CorePushNotificationsDelegate.instance.registerCounterHandler('AddonMessages'); + CorePushNotificationsDelegate.registerCounterHandler('AddonMessages'); } /** @@ -103,7 +103,7 @@ export class AddonMessagesMainMenuHandlerService implements CoreMainMenuHandler, * @return Whether or not the handler is enabled on a site level. */ isEnabled(): Promise { - return AddonMessages.instance.isPluginEnabled(); + return AddonMessages.isPluginEnabled(); } /** @@ -112,7 +112,7 @@ export class AddonMessagesMainMenuHandlerService implements CoreMainMenuHandler, * @return Data needed to render the handler. */ getDisplayData(): CoreMainMenuHandlerToDisplay { - this.handler.page = AddonMessages.instance.getMainMessagesPagePath(); + this.handler.page = AddonMessages.getMainMessagesPagePath(); if (this.handler.loading) { this.refreshBadge(); @@ -129,21 +129,21 @@ export class AddonMessagesMainMenuHandlerService implements CoreMainMenuHandler, * @return Resolve when done. */ async refreshBadge(siteId?: string, unreadOnly?: boolean): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!siteId) { return; } const promises: Promise[] = []; - promises.push(AddonMessages.instance.refreshUnreadConversationCounts(siteId).catch(() => { + promises.push(AddonMessages.refreshUnreadConversationCounts(siteId).catch(() => { this.unreadCount = 0; this.orMore = false; })); // Refresh the number of contact requests in 3.6+ sites. - if (!unreadOnly && AddonMessages.instance.isGroupMessagingEnabled()) { - promises.push(AddonMessages.instance.refreshContactRequestsCount(siteId).catch(() => { + if (!unreadOnly && AddonMessages.isGroupMessagingEnabled()) { + promises.push(AddonMessages.refreshContactRequestsCount(siteId).catch(() => { this.contactRequestsCount = 0; })); } @@ -168,7 +168,7 @@ export class AddonMessagesMainMenuHandlerService implements CoreMainMenuHandler, } // Update push notifications badge. - CorePushNotifications.instance.updateAddonCounter('AddonMessages', totalCount, siteId); + CorePushNotifications.updateAddonCounter('AddonMessages', totalCount, siteId); } /** @@ -179,7 +179,7 @@ export class AddonMessagesMainMenuHandlerService implements CoreMainMenuHandler, * @return Promise resolved when done, rejected if failure. */ async execute(siteId?: string): Promise { - if (!CoreSites.instance.isCurrentSite(siteId)) { + if (!CoreSites.isCurrentSite(siteId)) { return; } @@ -206,7 +206,7 @@ export class AddonMessagesMainMenuHandlerService implements CoreMainMenuHandler, */ isSync(): boolean { // This is done to use only wifi if using the fallback function. - return !AddonMessages.instance.isMessageCountEnabled() && !AddonMessages.instance.isGroupMessagingEnabled(); + return !AddonMessages.isMessageCountEnabled() && !AddonMessages.isGroupMessagingEnabled(); } /** @@ -220,4 +220,4 @@ export class AddonMessagesMainMenuHandlerService implements CoreMainMenuHandler, } -export class AddonMessagesMainMenuHandler extends makeSingleton(AddonMessagesMainMenuHandlerService) {} +export const AddonMessagesMainMenuHandler = makeSingleton(AddonMessagesMainMenuHandlerService); diff --git a/src/addons/messages/services/handlers/push-click.ts b/src/addons/messages/services/handlers/push-click.ts index 05b215885..a9d0f7682 100644 --- a/src/addons/messages/services/handlers/push-click.ts +++ b/src/addons/messages/services/handlers/push-click.ts @@ -38,12 +38,12 @@ export class AddonMessagesPushClickHandlerService implements CorePushNotificatio * @return Whether the notification click is handled by this handler */ async handles(notification: AddonMessagesPushNotificationData): Promise { - if (CoreUtils.instance.isTrueOrOne(notification.notif) && notification.name != 'messagecontactrequests') { + if (CoreUtils.isTrueOrOne(notification.notif) && notification.name != 'messagecontactrequests') { return false; } // Check that messaging is enabled. - return AddonMessages.instance.isPluginEnabled(notification.site); + return AddonMessages.isPluginEnabled(notification.site); } /** @@ -54,14 +54,14 @@ export class AddonMessagesPushClickHandlerService implements CorePushNotificatio */ async handleClick(notification: AddonMessagesPushNotificationData): Promise { try { - await AddonMessages.instance.invalidateDiscussionsCache(notification.site); + await AddonMessages.invalidateDiscussionsCache(notification.site); } catch { // Ignore errors. } // Check if group messaging is enabled, to determine which page should be loaded. - const enabled = await AddonMessages.instance.isGroupMessagingEnabledInSite(notification.site); - const pageName = await AddonMessages.instance.getMainMessagesPagePathInSite(notification.site); + const enabled = await AddonMessages.isGroupMessagingEnabledInSite(notification.site); + const pageName = await AddonMessages.getMainMessagesPagePathInSite(notification.site); const pageParams: Params = {}; @@ -72,12 +72,12 @@ export class AddonMessagesPushClickHandlerService implements CorePushNotificatio pageParams.discussionUserId = Number(notification.userfromid); } - await CoreNavigator.instance.navigateToSitePath(pageName, { params: pageParams, siteId: notification.site }); + await CoreNavigator.navigateToSitePath(pageName, { params: pageParams, siteId: notification.site }); } } -export class AddonMessagesPushClickHandler extends makeSingleton(AddonMessagesPushClickHandlerService) {} +export const AddonMessagesPushClickHandler = makeSingleton(AddonMessagesPushClickHandlerService); type AddonMessagesPushNotificationData = CorePushNotificationsNotificationBasicData & { convid?: number; // Conversation Id. diff --git a/src/addons/messages/services/handlers/settings.ts b/src/addons/messages/services/handlers/settings.ts index 35cfd9435..d6e625767 100644 --- a/src/addons/messages/services/handlers/settings.ts +++ b/src/addons/messages/services/handlers/settings.ts @@ -35,9 +35,9 @@ export class AddonMessagesSettingsHandlerService implements CoreSettingsHandler * @return Whether or not the handler is enabled on a site level. */ async isEnabled(): Promise { - const messagingEnabled = await AddonMessages.instance.isPluginEnabled(); + const messagingEnabled = await AddonMessages.isPluginEnabled(); - return messagingEnabled && AddonMessages.instance.isMessagePreferencesEnabled(); + return messagingEnabled && AddonMessages.isMessagePreferencesEnabled(); } /** @@ -56,5 +56,4 @@ export class AddonMessagesSettingsHandlerService implements CoreSettingsHandler } -export class AddonMessagesSettingsHandler extends makeSingleton(AddonMessagesSettingsHandlerService) {} - +export const AddonMessagesSettingsHandler = makeSingleton(AddonMessagesSettingsHandlerService); diff --git a/src/addons/messages/services/handlers/sync-cron.ts b/src/addons/messages/services/handlers/sync-cron.ts index cd64120ae..30536a0ed 100644 --- a/src/addons/messages/services/handlers/sync-cron.ts +++ b/src/addons/messages/services/handlers/sync-cron.ts @@ -33,7 +33,7 @@ export class AddonMessagesSyncCronHandlerService implements CoreCronHandler { * @return Promise resolved when done, rejected if failure. */ execute(siteId?: string): Promise { - return AddonMessagesSync.instance.syncAllDiscussions(siteId); + return AddonMessagesSync.syncAllDiscussions(siteId); } /** @@ -47,4 +47,4 @@ export class AddonMessagesSyncCronHandlerService implements CoreCronHandler { } -export class AddonMessagesSyncCronHandler extends makeSingleton(AddonMessagesSyncCronHandlerService) {} +export const AddonMessagesSyncCronHandler = makeSingleton(AddonMessagesSyncCronHandlerService); diff --git a/src/addons/messages/services/handlers/user-send-message.ts b/src/addons/messages/services/handlers/user-send-message.ts index b3c99a5c6..d0566d7cd 100644 --- a/src/addons/messages/services/handlers/user-send-message.ts +++ b/src/addons/messages/services/handlers/user-send-message.ts @@ -37,7 +37,7 @@ export class AddonMessagesSendMessageUserHandlerService implements CoreUserProfi * @return Promise resolved with true if enabled, rejected or resolved with false otherwise. */ isEnabled(): Promise { - return AddonMessages.instance.isPluginEnabled(); + return AddonMessages.isPluginEnabled(); } /** @@ -47,7 +47,7 @@ export class AddonMessagesSendMessageUserHandlerService implements CoreUserProfi * @return Promise resolved with true if enabled, resolved with false otherwise. */ async isEnabledForUser(user: CoreUserProfile): Promise { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); if (!currentSite) { return false; @@ -75,11 +75,11 @@ export class AddonMessagesSendMessageUserHandlerService implements CoreUserProfi showKeyboard: true, userId: user.id, }; - CoreNavigator.instance.navigateToSitePath('/messages/discussion', { params: pageParams }); + CoreNavigator.navigateToSitePath('/messages/discussion', { params: pageParams }); }, }; } } -export class AddonMessagesSendMessageUserHandler extends makeSingleton(AddonMessagesSendMessageUserHandlerService) {} +export const AddonMessagesSendMessageUserHandler = makeSingleton(AddonMessagesSendMessageUserHandlerService); diff --git a/src/addons/messages/services/messages-offline.ts b/src/addons/messages/services/messages-offline.ts index 73cb35d69..271c46c5f 100644 --- a/src/addons/messages/services/messages-offline.ts +++ b/src/addons/messages/services/messages-offline.ts @@ -41,7 +41,7 @@ export class AddonMessagesOfflineProvider { * @return Promise resolved if stored, rejected if failure. */ async deleteConversationMessage(conversationId: number, message: string, timeCreated: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(CONVERSATION_MESSAGES_TABLE, { conversationid: conversationId, @@ -58,7 +58,7 @@ export class AddonMessagesOfflineProvider { * @return Promise resolved if stored, rejected if failure. */ async deleteConversationMessages(conversationId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(CONVERSATION_MESSAGES_TABLE, { conversationid: conversationId, @@ -75,7 +75,7 @@ export class AddonMessagesOfflineProvider { * @return Promise resolved if stored, rejected if failure. */ async deleteMessage(toUserId: number, message: string, timeCreated: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(MESSAGES_TABLE, { touserid: toUserId, @@ -93,7 +93,7 @@ export class AddonMessagesOfflineProvider { async getAllDeviceOfflineMessages( siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const [ messages, @@ -124,7 +124,7 @@ export class AddonMessagesOfflineProvider { async getAllMessages( siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const [ messages, @@ -155,7 +155,7 @@ export class AddonMessagesOfflineProvider { userIdFrom?: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const messages: AddonMessagesOfflineConversationMessagesDBRecord[] = await site.getDb().getRecords( CONVERSATION_MESSAGES_TABLE, @@ -173,7 +173,7 @@ export class AddonMessagesOfflineProvider { * @return Promise resolved with messages. */ async getMessages(toUserId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const messages: AddonMessagesOfflineMessagesDBRecord[] = await site.getDb().getRecords(MESSAGES_TABLE, { touserid: toUserId }); @@ -228,7 +228,7 @@ export class AddonMessagesOfflineProvider { text: message.text, timecreated: message.timecreated, deviceoffline: message.deviceoffline, - conversation: message.conversation ? CoreTextUtils.instance.parseJSON(message.conversation, undefined) : undefined, + conversation: message.conversation ? CoreTextUtils.parseJSON(message.conversation, undefined) : undefined, pending: true, useridfrom: userIdFrom, }; @@ -278,13 +278,13 @@ export class AddonMessagesOfflineProvider { message: string, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entry: AddonMessagesOfflineConversationMessagesDBRecord = { conversationid: conversation.id, text: message, timecreated: Date.now(), - deviceoffline: CoreApp.instance.isOnline() ? 0 : 1, + deviceoffline: CoreApp.isOnline() ? 0 : 1, conversation: JSON.stringify({ name: conversation.name || '', subname: conversation.subname || '', @@ -308,14 +308,14 @@ export class AddonMessagesOfflineProvider { * @return Promise resolved if stored, rejected if failure. */ async saveMessage(toUserId: number, message: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entry: AddonMessagesOfflineMessagesDBRecord = { touserid: toUserId, useridfrom: site.getUserId(), smallmessage: message, timecreated: new Date().getTime(), - deviceoffline: CoreApp.instance.isOnline() ? 0 : 1, + deviceoffline: CoreApp.isOnline() ? 0 : 1, }; await site.getDb().insertRecord(MESSAGES_TABLE, entry); @@ -336,7 +336,7 @@ export class AddonMessagesOfflineProvider { value: boolean, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const db = site.getDb(); @@ -364,7 +364,7 @@ export class AddonMessagesOfflineProvider { } -export class AddonMessagesOffline extends makeSingleton(AddonMessagesOfflineProvider) {} +export const AddonMessagesOffline = makeSingleton(AddonMessagesOfflineProvider); export type AddonMessagesOfflineMessagesDBRecordFormatted = AddonMessagesOfflineMessagesDBRecord & { pending?: boolean; // Will be likely true. diff --git a/src/addons/messages/services/messages-sync.ts b/src/addons/messages/services/messages-sync.ts index 0e8893068..94b5d2d9c 100644 --- a/src/addons/messages/services/messages-sync.ts +++ b/src/addons/messages/services/messages-sync.ts @@ -90,8 +90,8 @@ export class AddonMessagesSyncProvider extends CoreSyncBaseProvider[] = []; const messages = onlyDeviceOffline - ? await AddonMessagesOffline.instance.getAllDeviceOfflineMessages(siteId) - : await AddonMessagesOffline.instance.getAllMessages(siteId); + ? await AddonMessagesOffline.getAllDeviceOfflineMessages(siteId) + : await AddonMessagesOffline.getAllMessages(siteId); // Get all the conversations to be synced. messages.forEach((message) => { @@ -143,7 +143,7 @@ export class AddonMessagesSyncProvider extends CoreSyncBaseProvider { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const syncId = this.getSyncId(conversationId, userId); @@ -174,16 +174,16 @@ export class AddonMessagesSyncProvider extends CoreSyncBaseProvider { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const siteCurrentUserId = site.getUserId(); if (conversationId) { try { - const result = await AddonMessages.instance.getConversationMessages(conversationId, { + const result = await AddonMessages.getConversationMessages(conversationId, { excludePending: true, ignoreCache: true, timeFrom: time, @@ -306,12 +306,12 @@ export class AddonMessagesSyncProvider extends CoreSyncBaseProvider message.timecreated >= time); @@ -345,16 +345,16 @@ export class AddonMessagesSyncProvider extends CoreSyncBaseProvider { - warnings.push(Translate.instance.instant('addon.messages.warningconversationmessagenotsent', { + warnings.push(Translate.instant('addon.messages.warningconversationmessagenotsent', { conversation: conversationIdentifier, - error: CoreTextUtils.instance.getErrorMessageFromError(error), + error: CoreTextUtils.getErrorMessageFromError(error), })); }); } else if (userId) { @@ -362,16 +362,16 @@ export class AddonMessagesSyncProvider extends CoreSyncBaseProvider { - warnings.push(Translate.instance.instant('addon.messages.warningmessagenotsent', { + warnings.push(Translate.instant('addon.messages.warningmessagenotsent', { user: userIdentifier, - error: CoreTextUtils.instance.getErrorMessageFromError(error), + error: CoreTextUtils.getErrorMessageFromError(error), })); }); } @@ -398,7 +398,7 @@ export class AddonMessagesSyncProvider extends CoreSyncBaseProvider { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params = { userids: [userId], @@ -97,7 +97,7 @@ export class AddonMessagesProvider { * @return Promise resolved when done. */ async blockContact(userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); try { if (site.wsAvailable('core_message_block_user')) { @@ -131,7 +131,7 @@ export class AddonMessagesProvider { * @since 3.6 */ async confirmContactRequest(userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesConfirmContactRequestWSParams = { userid: userId, @@ -140,7 +140,7 @@ export class AddonMessagesProvider { await site.write('core_message_confirm_contact_request', params); - await CoreUtils.instance.allPromises([ + await CoreUtils.allPromises([ this.invalidateAllMemberInfo(userId, site), this.invalidateContactsCache(site.id), this.invalidateUserContacts(site.id), @@ -160,7 +160,7 @@ export class AddonMessagesProvider { * @since 3.6 */ async createContactRequest(userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Use legacy function if not available. if (!site.wsAvailable('core_message_create_contact_request')) { @@ -189,7 +189,7 @@ export class AddonMessagesProvider { * @since 3.6 */ async declineContactRequest(userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesDeclineContactRequestWSParams = { userid: userId, @@ -198,7 +198,7 @@ export class AddonMessagesProvider { await site.write('core_message_decline_contact_request', params); - await CoreUtils.instance.allPromises([ + await CoreUtils.allPromises([ this.invalidateAllMemberInfo(userId, site), this.refreshContactRequestsCount(site.id), ]).finally(() => { @@ -228,7 +228,7 @@ export class AddonMessagesProvider { * @return Promise resolved when the conversations have been deleted. */ async deleteConversations(conversationIds: number[], siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -241,7 +241,7 @@ export class AddonMessagesProvider { await Promise.all(conversationIds.map(async (conversationId) => { try { - return AddonMessagesOffline.instance.deleteConversationMessages(conversationId, site.getId()); + return AddonMessagesOffline.deleteConversationMessages(conversationId, site.getId()); } catch { // Ignore errors. } @@ -267,10 +267,10 @@ export class AddonMessagesProvider { // It's an offline message. if (!('conversationid' in message)) { - return AddonMessagesOffline.instance.deleteMessage(message.touserid, message.smallmessage, message.timecreated); + return AddonMessagesOffline.deleteMessage(message.touserid, message.smallmessage, message.timecreated); } - return AddonMessagesOffline.instance.deleteConversationMessage(message.conversationid, message.text, message.timecreated); + return AddonMessagesOffline.deleteConversationMessage(message.conversationid, message.text, message.timecreated); } /** @@ -282,7 +282,7 @@ export class AddonMessagesProvider { * @return Promise resolved when the message has been deleted. */ async deleteMessageOnline(id: number, read: boolean, userId?: number): Promise { - userId = userId || CoreSites.instance.getCurrentSiteUserId(); + userId = userId || CoreSites.getCurrentSiteUserId(); const params: AddonMessagesDeleteMessageWSParams = { messageid: id, @@ -293,7 +293,7 @@ export class AddonMessagesProvider { params.read = read; } - await CoreSites.instance.getCurrentSite()?.write('core_message_delete_message', params); + await CoreSites.getCurrentSite()?.write('core_message_delete_message', params); await this.invalidateDiscussionCache(userId); } @@ -306,14 +306,14 @@ export class AddonMessagesProvider { * @return Promise resolved when the message has been deleted. */ async deleteMessageForAllOnline(id: number, userId?: number): Promise { - userId = userId || CoreSites.instance.getCurrentSiteUserId(); + userId = userId || CoreSites.getCurrentSiteUserId(); const params: AddonMessagesDeleteMessageForAllUsersWSParams = { messageid: id, userid: userId, }; - await CoreSites.instance.getCurrentSite()?.write('core_message_delete_message_for_all_users', params); + await CoreSites.getCurrentSite()?.write('core_message_delete_message_for_all_users', params); await this.invalidateDiscussionCache(userId); } @@ -556,7 +556,7 @@ export class AddonMessagesProvider { * @deprecatedonmoodle since Moodle 3.6 */ async getAllContacts(siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const contacts = await this.getContacts(siteId); @@ -582,7 +582,7 @@ export class AddonMessagesProvider { * @return Promise resolved with the WS data. */ async getBlockedContacts(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const userId = site.getUserId(); @@ -608,7 +608,7 @@ export class AddonMessagesProvider { * @deprecatedonmoodle since Moodle 3.6 */ async getContacts(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { cacheKey: this.getCacheKeyForContacts(), @@ -653,7 +653,7 @@ export class AddonMessagesProvider { limitNum: number = AddonMessagesProvider.LIMIT_CONTACTS, siteId?: string, ): Promise<{contacts: AddonMessagesConversationMember[]; canLoadMore: boolean}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesGetUserContactsWSParams = { userid: site.getUserId(), @@ -672,7 +672,7 @@ export class AddonMessagesProvider { return { contacts: [], canLoadMore: false }; } - CoreUser.instance.storeUsers(contacts, site.id); + CoreUser.storeUsers(contacts, site.id); if (limitNum <= 0) { return { contacts, canLoadMore: false }; } @@ -697,7 +697,7 @@ export class AddonMessagesProvider { limitNum: number = AddonMessagesProvider.LIMIT_CONTACTS, siteId?: string, ): Promise<{requests: AddonMessagesConversationMember[]; canLoadMore: boolean}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesGetContactRequestsWSParams = { userid: site.getUserId(), @@ -720,7 +720,7 @@ export class AddonMessagesProvider { return { requests: [], canLoadMore: false }; } - CoreUser.instance.storeUsers(requests, site.id); + CoreUser.storeUsers(requests, site.id); if (limitNum <= 0) { return { requests, canLoadMore: false }; } @@ -739,7 +739,7 @@ export class AddonMessagesProvider { * @since 3.6 */ async getContactRequestsCount(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesGetReceivedContactRequestsCountWSParams = { userid: site.getUserId(), @@ -791,7 +791,7 @@ export class AddonMessagesProvider { siteId?: string, userId?: number, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const preSets: CoreSiteWSPreSets = { @@ -851,7 +851,7 @@ export class AddonMessagesProvider { userId?: number, preferCache?: boolean, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const preSets: CoreSiteWSPreSets = { @@ -895,7 +895,7 @@ export class AddonMessagesProvider { siteId?: string, userId?: number, ): Promise<{members: AddonMessagesConversationMember[]; canLoadMore: boolean}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); limitTo = limitTo ?? AddonMessagesProvider.LIMIT_MESSAGES; @@ -941,7 +941,7 @@ export class AddonMessagesProvider { options: AddonMessagesGetConversationMessagesOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); options.userId = options.userId || site.getUserId(); options.limitFrom = options.limitFrom || 0; @@ -996,7 +996,7 @@ export class AddonMessagesProvider { // Get offline messages. const offlineMessages = - await AddonMessagesOffline.instance.getConversationMessages(conversationId, options.userId, site.getId()); + await AddonMessagesOffline.getConversationMessages(conversationId, options.userId, site.getId()); result.messages = result.messages.concat(offlineMessages); @@ -1028,7 +1028,7 @@ export class AddonMessagesProvider { ignoreCache?: boolean, ): Promise<{conversations: AddonMessagesConversationFormatted[]; canLoadMore: boolean}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const preSets: CoreSiteWSPreSets = { @@ -1092,7 +1092,7 @@ export class AddonMessagesProvider { * @since 3.6 */ async getConversationCounts(siteId?: string): Promise<{favourites: number; individual: number; group: number; self: number}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { cacheKey: this.getCacheKeyForConversationCounts(), @@ -1138,7 +1138,7 @@ export class AddonMessagesProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const result: AddonMessagesGetDiscussionMessages = { messages: [], @@ -1189,7 +1189,7 @@ export class AddonMessagesProvider { } // Get offline messages. - const offlineMessages = await AddonMessagesOffline.instance.getMessages(userId, site.getId()); + const offlineMessages = await AddonMessagesOffline.getMessages(userId, site.getId()); result.messages = result.messages.concat(offlineMessages); @@ -1245,7 +1245,7 @@ export class AddonMessagesProvider { } }; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const currentUserId = site.getUserId(); const params: AddonMessagesGetMessagesWSParams = { @@ -1274,7 +1274,7 @@ export class AddonMessagesProvider { treatRecentMessage(message, message.useridto, message.usertofullname); }); - const offlineMessages = await AddonMessagesOffline.instance.getAllMessages(site.getId()); + const offlineMessages = await AddonMessagesOffline.getAllMessages(site.getId()); offlineMessages.forEach((message) => { treatRecentMessage(message, 'touserid' in message ? message.touserid : 0, ''); @@ -1302,7 +1302,7 @@ export class AddonMessagesProvider { for (const userId in discussions) { if (!discussions[userId].profileimageurl && discussions[userId].message) { // We don't have the user image. Try to retrieve it. - promises.push(CoreUser.instance.getProfile(discussions[userId].message!.user, 0, true, siteId).then((user) => { + promises.push(CoreUser.getProfile(discussions[userId].message!.user, 0, true, siteId).then((user) => { discussions[userId].profileimageurl = user.profileimageurl; return; @@ -1327,7 +1327,7 @@ export class AddonMessagesProvider { * @since 3.6 */ async getMemberInfo(otherUserId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -1368,7 +1368,7 @@ export class AddonMessagesProvider { async getMessagePreferences(siteId?: string): Promise { this.logger.debug('Get message preferences'); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { cacheKey: this.getMessagePreferencesCacheKey(), @@ -1431,7 +1431,7 @@ export class AddonMessagesProvider { params.type = 'conversations'; params.newestfirst = true; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const response: AddonMessagesGetMessagesResult = await site.read('core_message_get_messages', params, preSets); response.messages.forEach((message) => { @@ -1516,7 +1516,7 @@ export class AddonMessagesProvider { siteId?: string, userId?: number, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const preSets: CoreSiteWSPreSets = { @@ -1543,7 +1543,7 @@ export class AddonMessagesProvider { async getUnreadConversationCounts( siteId?: string, ): Promise<{favourites: number; individual: number; group: number; self: number; orMore?: boolean}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); let counts: AddonMessagesUnreadConversationCountsEventData; @@ -1625,7 +1625,7 @@ export class AddonMessagesProvider { ignoreCache: boolean = false, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesGetMessagesWSParams = { read: false, @@ -1653,7 +1653,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateAllContactsCache(siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); await this.invalidateContactsCache(siteId); @@ -1667,7 +1667,7 @@ export class AddonMessagesProvider { * @param siteId Site ID. If not defined, current site. */ async invalidateBlockedContactsCache(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const userId = site.getUserId(); @@ -1681,7 +1681,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateContactsCache(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCacheKeyForContacts()); } @@ -1693,7 +1693,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateUserContacts(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCacheKeyForUserContacts()); } @@ -1705,7 +1705,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateContactRequestsCache(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.invalidateWsCacheForKey(this.getCacheKeyForContactRequests()); } @@ -1717,7 +1717,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateContactRequestsCountCache(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCacheKeyForContactRequestsCount()); } @@ -1731,7 +1731,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateConversation(conversationId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.invalidateWsCacheForKey(this.getCacheKeyForConversation(userId, conversationId)); @@ -1746,7 +1746,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateConversationBetweenUsers(otherUserId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -1762,7 +1762,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateConversationMembers(conversationId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -1778,7 +1778,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateConversationMessages(conversationId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -1793,7 +1793,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateConversations(siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -1807,7 +1807,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateConversationCounts(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCacheKeyForConversationCounts()); } @@ -1820,7 +1820,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateDiscussionCache(userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCacheKeyForDiscussion(userId)); } @@ -1834,7 +1834,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateDiscussionsCache(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const promises: Promise[] = []; promises.push(site.invalidateWsCacheForKey(this.getCacheKeyForDiscussions())); @@ -1852,7 +1852,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateMemberInfo(otherUserId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -1866,7 +1866,7 @@ export class AddonMessagesProvider { * @return Promise resolved when data is invalidated. */ async invalidateMessagePreferences(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getMessagePreferencesCacheKey()); } @@ -1879,7 +1879,7 @@ export class AddonMessagesProvider { * @return Promise resolved when done. */ protected async invalidateAllMemberInfo(userId: number, site: CoreSite): Promise { - await CoreUtils.instance.allPromises([ + await CoreUtils.allPromises([ this.invalidateMemberInfo(userId, site.id), this.invalidateUserContacts(site.id), this.invalidateBlockedContactsCache(site.id), @@ -1897,7 +1897,7 @@ export class AddonMessagesProvider { site.id, undefined, true, - ).then((conversation) => CoreUtils.instance.allPromises([ + ).then((conversation) => CoreUtils.allPromises([ this.invalidateConversation(conversation.id), this.invalidateConversationMembers(conversation.id, site.id), ])).catch(() => { @@ -1914,7 +1914,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateSelfConversation(siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -1928,7 +1928,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async invalidateUnreadConversationCounts(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (this.isGroupMessagingEnabled()) { // @since 3.6 return site.invalidateWsCacheForKey(this.getCacheKeyForUnreadConversationCounts()); @@ -1993,7 +1993,7 @@ export class AddonMessagesProvider { * @since 3.6 */ isGroupMessagingEnabled(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('core_message_get_conversations'); + return CoreSites.wsAvailableInCurrentSite('core_message_get_conversations'); } /** @@ -2005,7 +2005,7 @@ export class AddonMessagesProvider { */ async isGroupMessagingEnabledInSite(siteId?: string): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.wsAvailable('core_message_get_conversations'); } catch { @@ -2020,8 +2020,8 @@ export class AddonMessagesProvider { * @since 3.2 */ isMarkAllMessagesReadEnabled(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('core_message_mark_all_conversation_messages_as_read') || - CoreSites.instance.wsAvailableInCurrentSite('core_message_mark_all_messages_as_read'); + return CoreSites.wsAvailableInCurrentSite('core_message_mark_all_conversation_messages_as_read') || + CoreSites.wsAvailableInCurrentSite('core_message_mark_all_messages_as_read'); } /** @@ -2031,7 +2031,7 @@ export class AddonMessagesProvider { * @since 3.2 */ isMessageCountEnabled(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('core_message_get_unread_conversations_count'); + return CoreSites.wsAvailableInCurrentSite('core_message_get_unread_conversations_count'); } /** @@ -2041,7 +2041,7 @@ export class AddonMessagesProvider { * @since 3.2 */ isMessagePreferencesEnabled(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('core_message_get_user_message_preferences'); + return CoreSites.wsAvailableInCurrentSite('core_message_get_user_message_preferences'); } /** @@ -2068,7 +2068,7 @@ export class AddonMessagesProvider { * @since 3.7 */ isMuteConversationEnabled(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.wsAvailable('core_message_mute_conversations'); } @@ -2082,7 +2082,7 @@ export class AddonMessagesProvider { */ async isMuteConversationEnabledInSite(siteId?: string): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isMuteConversationEnabled(site); } catch { @@ -2097,7 +2097,7 @@ export class AddonMessagesProvider { * @return Promise resolved with true if enabled, rejected or resolved with false otherwise. */ async isPluginEnabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.canUseAdvancedFeature('messaging'); } @@ -2108,7 +2108,7 @@ export class AddonMessagesProvider { * @since 3.2 */ isSearchMessagesEnabled(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('core_message_data_for_messagearea_search_messages'); + return CoreSites.wsAvailableInCurrentSite('core_message_data_for_messagearea_search_messages'); } /** @@ -2119,7 +2119,7 @@ export class AddonMessagesProvider { * @since 3.7 */ isSelfConversationEnabled(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.wsAvailable('core_message_get_self_conversation'); } @@ -2133,7 +2133,7 @@ export class AddonMessagesProvider { */ async isSelfConversationEnabledInSite(siteId?: string): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isSelfConversationEnabled(site); } catch { @@ -2149,11 +2149,11 @@ export class AddonMessagesProvider { * @return Promise resolved with boolean marking success or not. */ async markMessageRead(messageId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesMarkMessageReadWSParams = { messageid: messageId, - timeread: CoreTimeUtils.instance.timestamp(), + timeread: CoreTimeUtils.timestamp(), }; return site.write('core_message_mark_message_read', params); @@ -2168,7 +2168,7 @@ export class AddonMessagesProvider { */ async markAllConversationMessagesRead(conversationId: number): Promise { const params: AddonMessagesMarkAllConversationMessagesAsReadWSParams = { - userid: CoreSites.instance.getCurrentSiteUserId(), + userid: CoreSites.getCurrentSiteUserId(), conversationid: conversationId, }; @@ -2176,7 +2176,7 @@ export class AddonMessagesProvider { responseExpected: false, }; - await CoreSites.instance.getCurrentSite()?.write('core_message_mark_all_conversation_messages_as_read', params, preSets); + await CoreSites.getCurrentSite()?.write('core_message_mark_all_conversation_messages_as_read', params, preSets); } /** @@ -2188,7 +2188,7 @@ export class AddonMessagesProvider { */ async markAllMessagesRead(userIdFrom?: number): Promise { const params: AddonMessagesMarkAllMessagesAsReadWSParams = { - useridto: CoreSites.instance.getCurrentSiteUserId(), + useridto: CoreSites.getCurrentSiteUserId(), useridfrom: userIdFrom, }; @@ -2196,7 +2196,7 @@ export class AddonMessagesProvider { typeExpected: 'boolean', }; - const site = CoreSites.instance.getCurrentSite(); + const site = CoreSites.getCurrentSite(); if (!site) { return false; @@ -2228,7 +2228,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async muteConversations(conversations: number[], set: boolean, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const params: AddonMessagesMuteConversationsWSParams = { @@ -2257,7 +2257,7 @@ export class AddonMessagesProvider { * @since 3.6 */ async refreshContactRequestsCount(siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); await this.invalidateContactRequestsCountCache(siteId); @@ -2273,7 +2273,7 @@ export class AddonMessagesProvider { async refreshUnreadConversationCounts( siteId?: string, ): Promise<{favourites: number; individual: number; group: number; orMore?: boolean}> { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); await this.invalidateUnreadConversationCounts(siteId); @@ -2288,7 +2288,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async removeContact(userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesDeleteContactsWSParams = { userids: [userId], @@ -2300,7 +2300,7 @@ export class AddonMessagesProvider { await site.write('core_message_delete_contacts', params, preSets); - return CoreUtils.instance.allPromises([ + return CoreUtils.allPromises([ this.invalidateUserContacts(site.id), this.invalidateAllMemberInfo(userId, site), this.invalidateContactsCache(site.id), @@ -2325,7 +2325,7 @@ export class AddonMessagesProvider { * @return Promise resolved with the contacts. */ async searchContacts(query: string, limit: number = 100, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesSearchContactsWSParams = { searchtext: query, @@ -2342,7 +2342,7 @@ export class AddonMessagesProvider { contacts = contacts.splice(0, limit); } - CoreUser.instance.storeUsers(contacts); + CoreUser.storeUsers(contacts); return contacts; } @@ -2364,7 +2364,7 @@ export class AddonMessagesProvider { limitNum: number = AddonMessagesProvider.LIMIT_SEARCH, siteId?: string, ): Promise<{messages: AddonMessagesMessageAreaContact[]; canLoadMore: boolean}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesDataForMessageareaSearchMessagesWSParams = { userid: userId || site.getUserId(), @@ -2389,7 +2389,7 @@ export class AddonMessagesProvider { profileimageurl: contact.profileimageurl, })); - CoreUser.instance.storeUsers(users, site.id); + CoreUser.storeUsers(users, site.id); if (limitNum <= 0) { return { messages: result.contacts, canLoadMore: false }; @@ -2422,7 +2422,7 @@ export class AddonMessagesProvider { canLoadMoreContacts: boolean; canLoadMoreNonContacts: boolean; }> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonMessagesMessageSearchUsersWSParams = { userid: site.getUserId(), @@ -2438,8 +2438,8 @@ export class AddonMessagesProvider { const contacts = result.contacts || []; const nonContacts = result.noncontacts || []; - CoreUser.instance.storeUsers(contacts, site.id); - CoreUser.instance.storeUsers(nonContacts, site.id); + CoreUser.storeUsers(contacts, site.id); + CoreUser.storeUsers(nonContacts, site.id); if (limitNum <= 0) { return { contacts, nonContacts, canLoadMoreContacts: false, canLoadMoreNonContacts: false }; @@ -2471,7 +2471,7 @@ export class AddonMessagesProvider { // Convenience function to store a message to be synchronized later. const storeOffline = async (): Promise => { - const entry = await AddonMessagesOffline.instance.saveMessage(toUserId, message, siteId); + const entry = await AddonMessagesOffline.saveMessage(toUserId, message, siteId); return { sent: false, @@ -2486,9 +2486,9 @@ export class AddonMessagesProvider { }; }; - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // App is offline, store the message. return storeOffline(); } @@ -2497,7 +2497,7 @@ export class AddonMessagesProvider { // If so, store this message since they need to be sent in order. let hasStoredMessages = false; try { - hasStoredMessages = await AddonMessagesOffline.instance.hasMessages(toUserId, siteId); + hasStoredMessages = await AddonMessagesOffline.hasMessages(toUserId, siteId); } catch { // Error, it's safer to assume it has messages. hasStoredMessages = true; @@ -2516,7 +2516,7 @@ export class AddonMessagesProvider { message: result, }; } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // It's a WebService error, the user cannot send the message so don't store it. throw error; } @@ -2535,7 +2535,7 @@ export class AddonMessagesProvider { * @return Promise resolved if success, rejected if failure. */ async sendMessageOnline(toUserId: number, message: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const messages = [ { @@ -2575,7 +2575,7 @@ export class AddonMessagesProvider { messages: AddonMessagesMessageData[], siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data: AddonMessagesSendInstantMessagesWSParams = { messages, @@ -2601,12 +2601,12 @@ export class AddonMessagesProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); // Convenience function to store a message to be synchronized later. const storeOffline = async(): Promise => { - const entry = await AddonMessagesOffline.instance.saveConversationMessage(conversation, message, siteId); + const entry = await AddonMessagesOffline.saveConversationMessage(conversation, message, siteId); return { sent: false, @@ -2619,7 +2619,7 @@ export class AddonMessagesProvider { }; }; - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // App is offline, store the message. return storeOffline(); } @@ -2628,7 +2628,7 @@ export class AddonMessagesProvider { // If so, store this message since they need to be sent in order. let hasStoredMessages = false; try { - hasStoredMessages = await AddonMessagesOffline.instance.hasConversationMessages(conversation.id, siteId); + hasStoredMessages = await AddonMessagesOffline.hasConversationMessages(conversation.id, siteId); } catch { // Error, it's safer to assume it has messages. hasStoredMessages = true; @@ -2647,7 +2647,7 @@ export class AddonMessagesProvider { message: result, }; } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // It's a WebService error, the user cannot send the message so don't store it. throw error; } @@ -2671,7 +2671,7 @@ export class AddonMessagesProvider { message: string, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const messages = [ { @@ -2706,7 +2706,7 @@ export class AddonMessagesProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreMessageSendMessagesToConversationWSParams = { conversationid: conversationId, messages: messages.map((message) => ({ @@ -2741,7 +2741,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async setFavouriteConversations(conversations: number[], set: boolean, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -2829,7 +2829,7 @@ export class AddonMessagesProvider { */ protected storeUsersFromAllContacts(contactTypes: AddonMessagesGetContactsWSResponse): void { for (const x in contactTypes) { - CoreUser.instance.storeUsers(contactTypes[x]); + CoreUser.storeUsers(contactTypes[x]); } } @@ -2849,7 +2849,7 @@ export class AddonMessagesProvider { profileimageurl: discussions[userId].profileimageurl, }); } - CoreUser.instance.storeUsers(users, siteId); + CoreUser.storeUsers(users, siteId); } /** @@ -2860,7 +2860,7 @@ export class AddonMessagesProvider { * @return Resolved when done. */ async unblockContact(userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); try { if (site.wsAvailable('core_message_unblock_user')) { @@ -2890,7 +2890,7 @@ export class AddonMessagesProvider { } -export class AddonMessages extends makeSingleton(AddonMessagesProvider) {} +export const AddonMessages = makeSingleton(AddonMessagesProvider); /** * Options to pass to getConversationMessages. diff --git a/src/addons/mod/assign/assign-lazy.module.ts b/src/addons/mod/assign/assign-lazy.module.ts index 90caa2792..67dde44fd 100644 --- a/src/addons/mod/assign/assign-lazy.module.ts +++ b/src/addons/mod/assign/assign-lazy.module.ts @@ -65,8 +65,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; @NgModule({ diff --git a/src/addons/mod/assign/assign.module.ts b/src/addons/mod/assign/assign.module.ts index fdbf18fd4..c7b8f32fb 100644 --- a/src/addons/mod/assign/assign.module.ts +++ b/src/addons/mod/assign/assign.module.ts @@ -57,12 +57,12 @@ const routes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreCourseModuleDelegate.instance.registerHandler(AddonModAssignModuleHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModAssignIndexLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModAssignListLinkHandler.instance); - CoreCourseModulePrefetchDelegate.instance.registerHandler(AddonModAssignPrefetchHandler.instance); - CoreCronDelegate.instance.register(AddonModAssignSyncCronHandler.instance); - CorePushNotificationsDelegate.instance.registerClickHandler(AddonModAssignPushClickHandler.instance); + CoreCourseModuleDelegate.registerHandler(AddonModAssignModuleHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModAssignIndexLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModAssignListLinkHandler.instance); + CoreCourseModulePrefetchDelegate.registerHandler(AddonModAssignPrefetchHandler.instance); + CoreCronDelegate.register(AddonModAssignSyncCronHandler.instance); + CorePushNotificationsDelegate.registerClickHandler(AddonModAssignPushClickHandler.instance); }, }, ], diff --git a/src/addons/mod/assign/components/edit-feedback-modal/edit-feedback-modal.ts b/src/addons/mod/assign/components/edit-feedback-modal/edit-feedback-modal.ts index 99177b118..a5c57e35d 100644 --- a/src/addons/mod/assign/components/edit-feedback-modal/edit-feedback-modal.ts +++ b/src/addons/mod/assign/components/edit-feedback-modal/edit-feedback-modal.ts @@ -45,12 +45,12 @@ export class AddonModAssignEditFeedbackModalComponent { async closeModal(): Promise { const changed = await this.hasDataChanged(); if (changed) { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.confirmcanceledit')); + await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); } - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); - ModalController.instance.dismiss(); + ModalController.dismiss(); } /** @@ -62,10 +62,10 @@ export class AddonModAssignEditFeedbackModalComponent { e.preventDefault(); e.stopPropagation(); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, false, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, false, CoreSites.getCurrentSiteId()); // Close the modal, sending the input data. - ModalController.instance.dismiss(this.getInputData()); + ModalController.dismiss(this.getInputData()); } /** @@ -74,7 +74,7 @@ export class AddonModAssignEditFeedbackModalComponent { * @return Object with the data. */ protected getInputData(): Record { - return CoreDomUtils.instance.getDataFromForm(document.forms['addon-mod_assign-edit-feedback-form']); + return CoreDomUtils.getDataFromForm(document.forms['addon-mod_assign-edit-feedback-form']); } /** @@ -83,8 +83,8 @@ export class AddonModAssignEditFeedbackModalComponent { * @return Promise resolved with boolean: whether the data has changed. */ protected async hasDataChanged(): Promise { - const changed = await CoreUtils.instance.ignoreErrors( - AddonModAssignFeedbackDelegate.instance.hasPluginDataChanged( + const changed = await CoreUtils.ignoreErrors( + AddonModAssignFeedbackDelegate.hasPluginDataChanged( this.assign, this.submission, this.plugin, diff --git a/src/addons/mod/assign/components/feedback-plugin/feedback-plugin.ts b/src/addons/mod/assign/components/feedback-plugin/feedback-plugin.ts index 650074442..39eae9e4f 100644 --- a/src/addons/mod/assign/components/feedback-plugin/feedback-plugin.ts +++ b/src/addons/mod/assign/components/feedback-plugin/feedback-plugin.ts @@ -67,7 +67,7 @@ export class AddonModAssignFeedbackPluginComponent implements OnInit { return; } - const name = AddonModAssignFeedbackDelegate.instance.getPluginName(this.plugin); + const name = AddonModAssignFeedbackDelegate.getPluginName(this.plugin); if (!name) { this.pluginLoaded = true; @@ -77,7 +77,7 @@ export class AddonModAssignFeedbackPluginComponent implements OnInit { this.plugin.name = name; // Check if the plugin has defined its own component to render itself. - this.pluginComponent = await AddonModAssignFeedbackDelegate.instance.getComponentForPlugin(this.plugin); + this.pluginComponent = await AddonModAssignFeedbackDelegate.getComponentForPlugin(this.plugin); if (this.pluginComponent) { // Prepare the data to pass to the component. @@ -86,15 +86,15 @@ export class AddonModAssignFeedbackPluginComponent implements OnInit { submission: this.submission, plugin: this.plugin, userId: this.userId, - configs: AddonModAssignHelper.instance.getPluginConfig(this.assign, 'assignfeedback', this.plugin.type), + configs: AddonModAssignHelper.getPluginConfig(this.assign, 'assignfeedback', this.plugin.type), edit: this.edit, canEdit: this.canEdit, }; } else { // Data to render the plugin. - this.text = AddonModAssign.instance.getSubmissionPluginText(this.plugin); - this.files = AddonModAssign.instance.getSubmissionPluginAttachments(this.plugin); - this.notSupported = AddonModAssignFeedbackDelegate.instance.isPluginSupported(this.plugin.type); + this.text = AddonModAssign.getSubmissionPluginText(this.plugin); + this.files = AddonModAssign.getSubmissionPluginAttachments(this.plugin); + this.notSupported = AddonModAssignFeedbackDelegate.isPluginSupported(this.plugin.type); this.pluginLoaded = true; } } @@ -110,7 +110,7 @@ export class AddonModAssignFeedbackPluginComponent implements OnInit { } // Create the navigation modal. - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: AddonModAssignEditFeedbackModalComponent, componentProps: { assign: this.assign, diff --git a/src/addons/mod/assign/components/index/index.ts b/src/addons/mod/assign/components/index/index.ts index bf23f6e15..e9fbcf9b5 100644 --- a/src/addons/mod/assign/components/index/index.ts +++ b/src/addons/mod/assign/components/index/index.ts @@ -103,8 +103,8 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo async ngOnInit(): Promise { super.ngOnInit(); - this.currentUserId = CoreSites.instance.getCurrentSiteUserId(); - this.currentSite = CoreSites.instance.getCurrentSite(); + this.currentUserId = CoreSites.getCurrentSiteUserId(); + this.currentSite = CoreSites.getCurrentSite(); // Listen to events. this.savedObserver = CoreEvents.on( @@ -123,7 +123,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo (data) => { if (this.assign && data.assignmentId == this.assign.id && data.userId == this.currentUserId) { // Assignment submitted, check completion. - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); // Reload data since it can have offline data now. this.showLoadingAndRefresh(true, false); @@ -142,18 +142,18 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo await this.loadContent(false, true); try { - await AddonModAssign.instance.logView(this.assign!.id, this.assign!.name); - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + await AddonModAssign.logView(this.assign!.id, this.assign!.name); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); } catch { // Ignore errors. Just don't check Module completion. } if (this.canViewAllSubmissions) { // User can see all submissions, log grading view. - CoreUtils.instance.ignoreErrors(AddonModAssign.instance.logGradingView(this.assign!.id, this.assign!.name)); + CoreUtils.ignoreErrors(AddonModAssign.logGradingView(this.assign!.id, this.assign!.name)); } else if (this.canViewOwnSubmission) { // User can only see their own submission, log view the user submission. - CoreUtils.instance.ignoreErrors(AddonModAssign.instance.logSubmissionView(this.assign!.id, this.assign!.name)); + CoreUtils.ignoreErrors(AddonModAssign.logSubmissionView(this.assign!.id, this.assign!.name)); } } @@ -165,7 +165,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo ev?.stopPropagation(); if (this.assign && (this.description || this.assign.introattachments)) { - CoreTextUtils.instance.viewText(Translate.instance.instant('core.description'), this.description || '', { + CoreTextUtils.viewText(Translate.instant('core.description'), this.description || '', { component: this.component, componentId: this.module!.id, files: this.assign.introattachments, @@ -189,22 +189,22 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo // Get assignment data. try { - this.assign = await AddonModAssign.instance.getAssignment(this.courseId!, this.module!.id); + this.assign = await AddonModAssign.getAssignment(this.courseId!, this.module!.id); this.dataRetrieved.emit(this.assign); this.description = this.assign.intro; if (sync) { // Try to synchronize the assign. - await CoreUtils.instance.ignoreErrors(this.syncActivity(showErrors)); + await CoreUtils.ignoreErrors(this.syncActivity(showErrors)); } // Check if there's any offline data for this assign. - this.hasOffline = await AddonModAssignOffline.instance.hasAssignOfflineData(this.assign.id); + this.hasOffline = await AddonModAssignOffline.hasAssignOfflineData(this.assign.id); // Get assignment submissions. - const submissions = await AddonModAssign.instance.getSubmissions(this.assign.id, { cmId: this.module!.id }); - const time = CoreTimeUtils.instance.timestamp(); + const submissions = await AddonModAssign.getSubmissions(this.assign.id, { cmId: this.module!.id }); + const time = CoreTimeUtils.timestamp(); this.canViewAllSubmissions = submissions.canviewsubmissions; @@ -213,18 +213,18 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo // Calculate the messages to display about time remaining and late submissions. if (this.assign.duedate > 0) { if (this.assign.duedate - time <= 0) { - this.timeRemaining = Translate.instance.instant('addon.mod_assign.assignmentisdue'); + this.timeRemaining = Translate.instant('addon.mod_assign.assignmentisdue'); } else { - this.timeRemaining = CoreTimeUtils.instance.formatDuration(this.assign.duedate - time, 3); + this.timeRemaining = CoreTimeUtils.formatDuration(this.assign.duedate - time, 3); if (this.assign.cutoffdate) { if (this.assign.cutoffdate > time) { - this.lateSubmissions = Translate.instance.instant( + this.lateSubmissions = Translate.instant( 'addon.mod_assign.latesubmissionsaccepted', - { $a: CoreTimeUtils.instance.userDate(this.assign.cutoffdate * 1000) }, + { $a: CoreTimeUtils.userDate(this.assign.cutoffdate * 1000) }, ); } else { - this.lateSubmissions = Translate.instance.instant('addon.mod_assign.nomoresubmissionsaccepted'); + this.lateSubmissions = Translate.instant('addon.mod_assign.nomoresubmissionsaccepted'); } } else { this.lateSubmissions = ''; @@ -236,18 +236,18 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo } // Check if groupmode is enabled to avoid showing wrong numbers. - this.groupInfo = await CoreGroups.instance.getActivityGroupInfo(this.assign.cmid, false); + this.groupInfo = await CoreGroups.getActivityGroupInfo(this.assign.cmid, false); this.showNumbers = (this.groupInfo.groups && this.groupInfo.groups.length == 0) || this.currentSite!.isVersionGreaterEqualThan('3.5'); - await this.setGroup(CoreGroups.instance.validateGroupId(this.group, this.groupInfo)); + await this.setGroup(CoreGroups.validateGroupId(this.group, this.groupInfo)); return; } try { // Check if the user can view their own submission. - await AddonModAssign.instance.getSubmissionStatus(this.assign.id, { cmId: this.module!.id }); + await AddonModAssign.getSubmissionStatus(this.assign.id, { cmId: this.module!.id }); this.canViewOwnSubmission = true; } catch (error) { this.canViewOwnSubmission = false; @@ -270,7 +270,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo async setGroup(groupId = 0): Promise { this.group = groupId; - const submissionStatus = await AddonModAssign.instance.getSubmissionStatus(this.assign!.id, { + const submissionStatus = await AddonModAssign.getSubmissionStatus(this.assign!.id, { groupId: this.group, cmId: this.module!.id, }); @@ -322,7 +322,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo if (typeof status != 'undefined') { params.status = status; } - CoreNavigator.instance.navigate('submission', { + CoreNavigator.navigate('submission', { params, }); } @@ -349,13 +349,13 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo protected async invalidateContent(): Promise { const promises: Promise[] = []; - promises.push(AddonModAssign.instance.invalidateAssignmentData(this.courseId!)); + promises.push(AddonModAssign.invalidateAssignmentData(this.courseId!)); if (this.assign) { - promises.push(AddonModAssign.instance.invalidateAllSubmissionData(this.assign.id)); + promises.push(AddonModAssign.invalidateAllSubmissionData(this.assign.id)); if (this.canViewAllSubmissions) { - promises.push(AddonModAssign.instance.invalidateSubmissionStatusData(this.assign.id, undefined, this.group)); + promises.push(AddonModAssign.invalidateSubmissionStatusData(this.assign.id, undefined, this.group)); } } @@ -392,7 +392,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo if (this.assign && syncEventData.assignId == this.assign.id) { if (syncEventData.warnings && syncEventData.warnings.length) { // Show warnings. - CoreDomUtils.instance.showErrorModal(syncEventData.warnings[0]); + CoreDomUtils.showErrorModal(syncEventData.warnings[0]); } return true; @@ -407,7 +407,7 @@ export class AddonModAssignIndexComponent extends CoreCourseModuleMainActivityCo * @return Promise resolved when done. */ protected async sync(): Promise { - await AddonModAssignSync.instance.syncAssign(this.assign!.id); + await AddonModAssignSync.syncAssign(this.assign!.id); } /** diff --git a/src/addons/mod/assign/components/submission-plugin/submission-plugin.ts b/src/addons/mod/assign/components/submission-plugin/submission-plugin.ts index fcbb25bec..c54e39cdb 100644 --- a/src/addons/mod/assign/components/submission-plugin/submission-plugin.ts +++ b/src/addons/mod/assign/components/submission-plugin/submission-plugin.ts @@ -63,7 +63,7 @@ export class AddonModAssignSubmissionPluginComponent implements OnInit { return; } - const name = AddonModAssignSubmissionDelegate.instance.getPluginName(this.plugin); + const name = AddonModAssignSubmissionDelegate.getPluginName(this.plugin); if (!name) { this.pluginLoaded = true; @@ -73,7 +73,7 @@ export class AddonModAssignSubmissionPluginComponent implements OnInit { this.plugin.name = name; // Check if the plugin has defined its own component to render itself. - this.pluginComponent = await AddonModAssignSubmissionDelegate.instance.getComponentForPlugin(this.plugin, this.edit); + this.pluginComponent = await AddonModAssignSubmissionDelegate.getComponentForPlugin(this.plugin, this.edit); if (this.pluginComponent) { // Prepare the data to pass to the component. @@ -81,15 +81,15 @@ export class AddonModAssignSubmissionPluginComponent implements OnInit { assign: this.assign, submission: this.submission, plugin: this.plugin, - configs: AddonModAssignHelper.instance.getPluginConfig(this.assign, 'assignsubmission', this.plugin.type), + configs: AddonModAssignHelper.getPluginConfig(this.assign, 'assignsubmission', this.plugin.type), edit: this.edit, allowOffline: this.allowOffline, }; } else { // Data to render the plugin. - this.text = AddonModAssign.instance.getSubmissionPluginText(this.plugin); - this.files = AddonModAssign.instance.getSubmissionPluginAttachments(this.plugin); - this.notSupported = AddonModAssignSubmissionDelegate.instance.isPluginSupported(this.plugin.type); + this.text = AddonModAssign.getSubmissionPluginText(this.plugin); + this.files = AddonModAssign.getSubmissionPluginAttachments(this.plugin); + this.notSupported = AddonModAssignSubmissionDelegate.isPluginSupported(this.plugin.type); this.pluginLoaded = true; } } diff --git a/src/addons/mod/assign/components/submission/submission.ts b/src/addons/mod/assign/components/submission/submission.ts index 3a2c906c6..0e3afc1ee 100644 --- a/src/addons/mod/assign/components/submission/submission.ts +++ b/src/addons/mod/assign/components/submission/submission.ts @@ -147,9 +147,9 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { constructor( @Optional() protected splitviewCtrl: CoreSplitViewComponent, ) { - this.siteId = CoreSites.instance.getCurrentSiteId(); - this.currentUserId = CoreSites.instance.getCurrentSiteUserId(); - this.maxAttemptsText = Translate.instance.instant('addon.mod_assign.unlimitedattempts'); + this.siteId = CoreSites.getCurrentSiteId(); + this.currentUserId = CoreSites.getCurrentSiteUserId(); + this.maxAttemptsText = Translate.instant('addon.mod_assign.unlimitedattempts'); // Refresh data if this assign is synchronized and it's grading. const events = [AddonModAssignSyncProvider.AUTO_SYNCED, AddonModAssignSyncProvider.MANUAL_SYNCED]; @@ -199,14 +199,14 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { return; } - const time = CoreTimeUtils.instance.timestamp(); + const time = CoreTimeUtils.timestamp(); const dueDate = response.lastattempt?.extensionduedate ? response.lastattempt.extensionduedate : this.assign!.duedate; const timeRemaining = dueDate - time; if (timeRemaining > 0) { - this.timeRemaining = CoreTimeUtils.instance.formatDuration(timeRemaining, 3); + this.timeRemaining = CoreTimeUtils.formatDuration(timeRemaining, 3); this.timeRemainingClass = ''; return; @@ -216,16 +216,16 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { if (!this.userSubmission || this.userSubmission.status != AddonModAssignProvider.SUBMISSION_STATUS_SUBMITTED) { if (response.lastattempt?.submissionsenabled || response.gradingsummary?.submissionsenabled) { - this.timeRemaining = Translate.instance.instant( + this.timeRemaining = Translate.instant( 'addon.mod_assign.overdue', - { $a: CoreTimeUtils.instance.formatDuration(-timeRemaining, 3) }, + { $a: CoreTimeUtils.formatDuration(-timeRemaining, 3) }, ); this.timeRemainingClass = 'overdue'; return; } - this.timeRemaining = Translate.instance.instant('addon.mod_assign.duedatereached'); + this.timeRemaining = Translate.instant('addon.mod_assign.duedatereached'); this.timeRemainingClass = ''; return; @@ -233,18 +233,18 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { const timeSubmittedDiff = this.userSubmission.timemodified - dueDate; if (timeSubmittedDiff > 0) { - this.timeRemaining = Translate.instance.instant( + this.timeRemaining = Translate.instant( 'addon.mod_assign.submittedlate', - { $a: CoreTimeUtils.instance.formatDuration(timeSubmittedDiff, 2) }, + { $a: CoreTimeUtils.formatDuration(timeSubmittedDiff, 2) }, ); this.timeRemainingClass = 'latesubmission'; return; } - this.timeRemaining = Translate.instance.instant( + this.timeRemaining = Translate.instant( 'addon.mod_assign.submittedearly', - { $a: CoreTimeUtils.instance.formatDuration(-timeSubmittedDiff, 2) }, + { $a: CoreTimeUtils.formatDuration(-timeSubmittedDiff, 2) }, ); this.timeRemainingClass = 'earlysubmission'; } @@ -261,7 +261,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { if (modified) { // Modified, confirm user wants to go back. try { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.confirmcanceledit')); + await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); await this.discardDrafts(); } catch { // Cancelled by the user. @@ -273,8 +273,8 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { * Copy a previous attempt and then go to edit. */ async copyPrevious(): Promise { - if (!CoreApp.instance.isOnline()) { - CoreDomUtils.instance.showErrorModal('core.networkerrormsg', true); + if (!CoreApp.isOnline()) { + CoreDomUtils.showErrorModal('core.networkerrormsg', true); return; } @@ -285,10 +285,10 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { } const previousSubmission = this.previousAttempt.submission; - let modal = await CoreDomUtils.instance.showModalLoading(); + let modal = await CoreDomUtils.showModalLoading(); - const size = await CoreUtils.instance.ignoreErrors( - AddonModAssignHelper.instance.getSubmissionSizeForCopy(this.assign!, previousSubmission), + const size = await CoreUtils.ignoreErrors( + AddonModAssignHelper.getSubmissionSizeForCopy(this.assign!, previousSubmission), -1, ); // Error calculating size, return -1. @@ -296,17 +296,17 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { try { // Confirm action. - await CoreFileUploaderHelper.instance.confirmUploadFile(size, true); + await CoreFileUploaderHelper.confirmUploadFile(size, true); } catch { // Cancelled. return; } // User confirmed, copy the attempt. - modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - await AddonModAssignHelper.instance.copyPreviousAttempt(this.assign!, previousSubmission); + await AddonModAssignHelper.copyPreviousAttempt(this.assign!, previousSubmission); // Now go to edit. this.goToEdit(); @@ -322,7 +322,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { await this.invalidateAndRefresh(true); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); } finally { modal.dismiss(); } @@ -335,7 +335,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { */ protected async discardDrafts(): Promise { if (this.feedback && this.feedback.plugins) { - await AddonModAssignHelper.instance.discardFeedbackPluginData(this.assign!.id, this.submitId, this.feedback); + await AddonModAssignHelper.discardFeedbackPluginData(this.assign!.id, this.submitId, this.feedback); } } @@ -343,7 +343,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { * Go to the page to add or edit submission. */ goToEdit(): void { - CoreNavigator.instance.navigateToSitePath( + CoreNavigator.navigateToSitePath( AddonModAssignModuleHandlerService.PAGE_NAME + '/' + this.courseId + '/' + this.moduleId + '/edit', { params: { @@ -392,7 +392,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { } try { - return AddonModAssignHelper.instance.hasFeedbackDataChanged( + return AddonModAssignHelper.hasFeedbackDataChanged( this.assign!, this.userSubmission, this.feedback, @@ -429,19 +429,19 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { const promises: Promise[] = []; - promises.push(AddonModAssign.instance.invalidateAssignmentData(this.courseId)); + promises.push(AddonModAssign.invalidateAssignmentData(this.courseId)); if (this.assign) { - promises.push(AddonModAssign.instance.invalidateSubmissionStatusData( + promises.push(AddonModAssign.invalidateSubmissionStatusData( this.assign!.id, this.submitId, undefined, !!this.blindId, )); - promises.push(AddonModAssign.instance.invalidateAssignmentUserMappingsData(this.assign!.id)); - promises.push(AddonModAssign.instance.invalidateListParticipantsData(this.assign!.id)); + promises.push(AddonModAssign.invalidateAssignmentUserMappingsData(this.assign!.id)); + promises.push(AddonModAssign.invalidateListParticipantsData(this.assign!.id)); } - promises.push(CoreGradesHelper.instance.invalidateGradeModuleItems(this.courseId, this.submitId)); - promises.push(CoreCourse.instance.invalidateModule(this.moduleId)); + promises.push(CoreGradesHelper.invalidateGradeModuleItems(this.courseId, this.submitId)); + promises.push(CoreCourse.invalidateModule(this.moduleId)); // Invalidate plugins. if (this.submissionComponents && this.submissionComponents.length) { @@ -450,7 +450,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { }); } - await CoreUtils.instance.ignoreErrors(Promise.all(promises)); + await CoreUtils.ignoreErrors(Promise.all(promises)); await this.loadData(sync); } @@ -474,12 +474,12 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { try { // Get the assignment. - this.assign = await AddonModAssign.instance.getAssignment(this.courseId, this.moduleId); + this.assign = await AddonModAssign.getAssignment(this.courseId, this.moduleId); if (this.submitId != this.currentUserId && sync) { // Teacher viewing a student submission. Try to sync the assign, there could be offline grades stored. try { - const result = await AddonModAssignSync.instance.syncAssign(this.assign.id); + const result = await AddonModAssignSync.syncAssign(this.assign.id); if (result && result.updated) { CoreEvents.trigger(AddonModAssignSyncProvider.MANUAL_SYNCED, { @@ -495,11 +495,11 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { } } - const time = CoreTimeUtils.instance.timestamp(); + const time = CoreTimeUtils.timestamp(); let promises: Promise[] = []; if (this.assign.allowsubmissionsfromdate && this.assign.allowsubmissionsfromdate >= time) { - this.fromDate = CoreTimeUtils.instance.userDate(this.assign.allowsubmissionsfromdate * 1000); + this.fromDate = CoreTimeUtils.userDate(this.assign.allowsubmissionsfromdate * 1000); } this.blindMarking = this.isSubmittedForGrading && !!this.assign.blindmarking && !this.assign.revealidentities; @@ -515,7 +515,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { // Get submission status. const submissionStatus = - await AddonModAssign.instance.getSubmissionStatusWithRetry(this.assign, { userId: this.submitId, isBlind }); + await AddonModAssign.getSubmissionStatusWithRetry(this.assign, { userId: this.submitId, isBlind }); this.submissionStatusAvailable = true; this.lastAttempt = submissionStatus.lastattempt; @@ -527,7 +527,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { const previousAttempts = submissionStatus.previousattempts.sort((a, b) => a.attemptnumber - b.attemptnumber); this.previousAttempt = previousAttempts[previousAttempts.length - 1]; this.isPreviousAttemptEmpty = - AddonModAssignHelper.instance.isSubmissionEmpty(this.assign, this.previousAttempt.submission); + AddonModAssignHelper.isSubmissionEmpty(this.assign, this.previousAttempt.submission); } // Treat last attempt. @@ -542,8 +542,8 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { // Check if there's any unsupported plugin for editing. if (!this.userSubmission || !this.userSubmission.plugins) { // Submission not created yet, we have to use assign configs to detect the plugins used. - this.userSubmission = AddonModAssignHelper.instance.createEmptySubmission(); - this.userSubmission.plugins = AddonModAssignHelper.instance.getPluginsEnabled(this.assign, 'assignsubmission'); + this.userSubmission = AddonModAssignHelper.createEmptySubmission(); + this.userSubmission.plugins = AddonModAssignHelper.getPluginsEnabled(this.assign, 'assignsubmission'); } // Get the submission plugins that don't support editing. @@ -551,7 +551,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { await Promise.all(promises); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting assigment data.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting assigment data.'); } finally { this.loaded = true; } @@ -563,7 +563,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { * @return Promise resolved when done. */ protected async loadSubmissionUserProfile(): Promise { - this.user = await CoreUser.instance.getProfile(this.submitId, this.courseId); + this.user = await CoreUser.getProfile(this.submitId, this.courseId); } /** @@ -573,7 +573,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { */ protected async loadSubmissionOfflineData(): Promise { try { - const submission = await AddonModAssignOffline.instance.getSubmission(this.assign!.id, this.submitId); + const submission = await AddonModAssignOffline.getSubmission(this.assign!.id, this.submitId); this.hasOffline = submission && submission.plugindata && Object.keys(submission.plugindata).length > 0; @@ -613,7 +613,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { // If we have data about the grader, get its profile. if (feedback.grade && feedback.grade.grader > 0) { try { - this.grader = await CoreUser.instance.getProfile(feedback.grade.grader, this.courseId); + this.grader = await CoreUser.getProfile(feedback.grade.grader, this.courseId); } catch { // Ignore errors. } @@ -634,7 +634,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { const parsedGrade = parseFloat(feedback.grade.grade); this.grade!.grade = parsedGrade >= 0 ? parsedGrade : undefined; - this.grade.gradebookGrade = CoreUtils.instance.formatFloat(this.grade.grade); + this.grade.gradebookGrade = CoreUtils.formatFloat(this.grade.grade); this.originalGrades.grade = this.grade.grade; } } else { @@ -646,7 +646,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { this.grade.gradingStatus = this.lastAttempt?.gradingstatus; // Get the grade for the assign. - this.gradeInfo = await CoreCourse.instance.getModuleBasicGradeInfo(this.moduleId); + this.gradeInfo = await CoreCourse.getModuleBasicGradeInfo(this.moduleId); if (!this.gradeInfo) { // It won't get gradeinfo on 3.1. @@ -668,7 +668,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { } if (this.assign!.markingworkflow && this.grade.gradingStatus) { this.workflowStatusTranslationId = - AddonModAssign.instance.getSubmissionGradingStatusTranslationId(this.grade.gradingStatus); + AddonModAssign.getSubmissionGradingStatusTranslationId(this.grade.gradingStatus); } if (this.lastAttempt?.gradingstatus == 'graded' && !this.assign!.markingworkflow) { @@ -676,24 +676,24 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { this.lastAttempt.gradingstatus = AddonModAssignProvider.GRADED_FOLLOWUP_SUBMIT; // Get grading text and color. - this.gradingStatusTranslationId = AddonModAssign.instance.getSubmissionGradingStatusTranslationId( + this.gradingStatusTranslationId = AddonModAssign.getSubmissionGradingStatusTranslationId( this.lastAttempt.gradingstatus, ); - this.gradingColor = AddonModAssign.instance.getSubmissionGradingStatusColor(this.lastAttempt.gradingstatus); + this.gradingColor = AddonModAssign.getSubmissionGradingStatusColor(this.lastAttempt.gradingstatus); } } if (!this.feedback || !this.feedback.plugins) { // Feedback plugins not present, we have to use assign configs to detect the plugins used. - this.feedback = AddonModAssignHelper.instance.createEmptyFeedback(); - this.feedback.plugins = AddonModAssignHelper.instance.getPluginsEnabled(this.assign!, 'assignfeedback'); + this.feedback = AddonModAssignHelper.createEmptyFeedback(); + this.feedback.plugins = AddonModAssignHelper.getPluginsEnabled(this.assign!, 'assignfeedback'); } // Check if there's any offline data for this submission. if (!this.canSaveGrades) { // User cannot save grades in the app. Load the URL to grade it in browser. - const mod = await CoreCourse.instance.getModule(this.moduleId, this.courseId, undefined, true); + const mod = await CoreCourse.getModule(this.moduleId, this.courseId, undefined, true); this.gradeUrl = mod.url + '&action=grader&userid=' + this.submitId; return; @@ -701,8 +701,8 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { // Submission grades aren't identified by attempt number so it can retrieve the feedback for a previous attempt. // The app will not treat that as an special case. - const submissionGrade = await CoreUtils.instance.ignoreErrors( - AddonModAssignOffline.instance.getSubmissionGrade(this.assign!.id, this.submitId), + const submissionGrade = await CoreUtils.ignoreErrors( + AddonModAssignOffline.getSubmissionGrade(this.assign!.id, this.submitId), ); this.hasOfflineGrade = false; @@ -713,7 +713,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { if ((this.grade.modified || 0) < submissionGrade.timemodified) { this.hasOfflineGrade = true; this.grade.grade = !this.grade.scale - ? CoreUtils.instance.formatFloat(submissionGrade.grade) + ? CoreUtils.formatFloat(submissionGrade.grade) : submissionGrade.grade; this.gradingStatusTranslationId = 'addon.mod_assign.gradenotsynced'; this.gradingColor = ''; @@ -745,7 +745,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { * @return Promise resolved when done. */ protected async loadUnsupportedPlugins(): Promise { - this.unsupportedEditPlugins = await AddonModAssign.instance.getUnsupportedEditPlugins(this.userSubmission?.plugins || []); + this.unsupportedEditPlugins = await AddonModAssign.getUnsupportedEditPlugins(this.userSubmission?.plugins || []); } /** @@ -765,14 +765,14 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { // Single submission. if (this.userSubmission && this.userSubmission.status != this.statusNew) { this.statusTranslated = translateService.instant('addon.mod_assign.submissionstatus_' + this.userSubmission.status); - this.statusColor = AddonModAssign.instance.getSubmissionStatusColor(this.userSubmission.status); + this.statusColor = AddonModAssign.getSubmissionStatusColor(this.userSubmission.status); } else { if (!status.lastattempt?.submissionsenabled) { this.statusTranslated = translateService.instant('addon.mod_assign.noonlinesubmissions'); - this.statusColor = AddonModAssign.instance.getSubmissionStatusColor('noonlinesubmissions'); + this.statusColor = AddonModAssign.getSubmissionStatusColor('noonlinesubmissions'); } else { this.statusTranslated = translateService.instant('addon.mod_assign.noattempt'); - this.statusColor = AddonModAssign.instance.getSubmissionStatusColor('noattempt'); + this.statusColor = AddonModAssign.getSubmissionStatusColor('noattempt'); } } } else { @@ -780,17 +780,17 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { // Team submission. if (!status.lastattempt?.submissiongroup && this.assign!.preventsubmissionnotingroup) { this.statusTranslated = translateService.instant('addon.mod_assign.nosubmission'); - this.statusColor = AddonModAssign.instance.getSubmissionStatusColor('nosubmission'); + this.statusColor = AddonModAssign.getSubmissionStatusColor('nosubmission'); } else if (this.userSubmission && this.userSubmission.status != this.statusNew) { this.statusTranslated = translateService.instant('addon.mod_assign.submissionstatus_' + this.userSubmission.status); - this.statusColor = AddonModAssign.instance.getSubmissionStatusColor(this.userSubmission.status); + this.statusColor = AddonModAssign.getSubmissionStatusColor(this.userSubmission.status); } else { if (!status.lastattempt?.submissionsenabled) { this.statusTranslated = translateService.instant('addon.mod_assign.noonlinesubmissions'); - this.statusColor = AddonModAssign.instance.getSubmissionStatusColor('noonlinesubmissions'); + this.statusColor = AddonModAssign.getSubmissionStatusColor('noonlinesubmissions'); } else { this.statusTranslated = translateService.instant('addon.mod_assign.nosubmission'); - this.statusColor = AddonModAssign.instance.getSubmissionStatusColor('nosubmission'); + this.statusColor = AddonModAssign.getSubmissionStatusColor('nosubmission'); } } } @@ -801,8 +801,8 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { */ showAdvancedGrade(): void { if (this.feedback && this.feedback.advancedgrade) { - CoreTextUtils.instance.viewText( - Translate.instance.instant('core.grades.grade'), + CoreTextUtils.viewText( + Translate.instant('core.grades.grade'), this.feedback.gradefordisplay, { component: AddonModAssignProvider.COMPONENT, @@ -819,19 +819,19 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { */ async submitForGrading(acceptStatement: boolean): Promise { if (this.assign!.requiresubmissionstatement && !acceptStatement) { - CoreDomUtils.instance.showErrorModal('addon.mod_assign.acceptsubmissionstatement', true); + CoreDomUtils.showErrorModal('addon.mod_assign.acceptsubmissionstatement', true); return; } try { // Ask for confirmation. @todo plugin precheck_submission - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('addon.mod_assign.confirmsubmission')); + await CoreDomUtils.showConfirm(Translate.instant('addon.mod_assign.confirmsubmission')); - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - await AddonModAssign.instance.submitForGrading( + await AddonModAssign.submitForGrading( this.assign!.id, this.courseId, acceptStatement, @@ -846,7 +846,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { userId: this.currentUserId, }, this.siteId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); } finally { modal.dismiss(); } @@ -872,14 +872,14 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { // Scale "no grade" uses -1 instead of 0. const grade = this.grade.scale && this.grade.grade == 0 ? -1 - : CoreUtils.instance.unformatFloat(this.grade.grade, true); + : CoreUtils.unformatFloat(this.grade.grade, true); if (grade === false) { // Grade is invalid. - throw new CoreError(Translate.instance.instant('core.grades.badgrade')); + throw new CoreError(Translate.instant('core.grades.badgrade')); } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); (this.gradeInfo?.outcomes || []).forEach((outcome) => { if (outcome.itemNumber) { @@ -891,12 +891,12 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { try { if (this.feedback && this.feedback.plugins) { pluginData = - await AddonModAssignHelper.instance.prepareFeedbackPluginData(this.assign!.id, this.submitId, this.feedback); + await AddonModAssignHelper.prepareFeedbackPluginData(this.assign!.id, this.submitId, this.feedback); } try { // We have all the data, now send it. - await AddonModAssign.instance.submitGradingForm( + await AddonModAssign.submitGradingForm( this.assign!.id, this.submitId, this.courseId, @@ -955,24 +955,24 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { if (this.gradeInfo.scale) { this.grade.scale = - CoreUtils.instance.makeMenuFromList(this.gradeInfo.scale, Translate.instance.instant('core.nograde')); + CoreUtils.makeMenuFromList(this.gradeInfo.scale, Translate.instant('core.nograde')); } else { // Format the grade. - this.grade.grade = CoreUtils.instance.formatFloat(this.grade.grade); + this.grade.grade = CoreUtils.formatFloat(this.grade.grade); this.originalGrades.grade = this.grade.grade; // Get current language to format grade input field. - this.grade.lang = await CoreLang.instance.getCurrentLanguage(); + this.grade.lang = await CoreLang.getCurrentLanguage(); } // Treat outcomes. - if (this.gradeInfo.outcomes && AddonModAssign.instance.isOutcomesEditEnabled()) { + if (this.gradeInfo.outcomes && AddonModAssign.isOutcomesEditEnabled()) { this.gradeInfo.outcomes.forEach((outcome) => { if (outcome.scale) { outcome.options = - CoreUtils.instance.makeMenuFromList( + CoreUtils.makeMenuFromList( outcome.scale, - Translate.instance.instant('core.grades.nooutcome'), + Translate.instant('core.grades.nooutcome'), ); } outcome.selectedId = 0; @@ -982,7 +982,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { // Get grade items. const grades = - await CoreGradesHelper.instance.getGradeModuleItems(this.courseId, this.moduleId, this.submitId); + await CoreGradesHelper.getGradeModuleItems(this.courseId, this.moduleId, this.submitId); const outcomes: AddonModAssignGradeOutcome[] = []; @@ -992,13 +992,13 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { const gradeFormatted = grade.gradeformatted || ''; // Not using outcomes or scale, get the numeric grade. if (this.grade.scale) { - this.grade.gradebookGrade = CoreUtils.instance.formatFloat( - CoreGradesHelper.instance.getGradeValueFromLabel(this.grade.scale, gradeFormatted), + this.grade.gradebookGrade = CoreUtils.formatFloat( + CoreGradesHelper.getGradeValueFromLabel(this.grade.scale, gradeFormatted), ); } else { const parsedGrade = parseFloat(gradeFormatted); this.grade.gradebookGrade = parsedGrade || parsedGrade == 0 - ? CoreUtils.instance.formatFloat(parsedGrade) + ? CoreUtils.formatFloat(parsedGrade) : undefined; } @@ -1013,7 +1013,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { outcome.modified = grade.gradedategraded; if (outcome.options) { outcome.selectedId = - CoreGradesHelper.instance.getGradeValueFromLabel(outcome.options, outcome.selected || ''); + CoreGradesHelper.getGradeValueFromLabel(outcome.options, outcome.selected || ''); this.originalGrades.outcomes[outcome.id] = outcome.selectedId; outcome.itemNumber = grade.itemnumber; } @@ -1044,7 +1044,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { typeof this.assign!.submissionstatement == 'undefined'; this.canSubmit = !this.isSubmittedForGrading && !this.submittedOffline && (submissionStatus.lastattempt.cansubmit || - (this.hasOffline && AddonModAssign.instance.canSubmitOffline(this.assign!, submissionStatus))); + (this.hasOffline && AddonModAssign.canSubmitOffline(this.assign!, submissionStatus))); this.canEdit = !this.isSubmittedForGrading && submissionStatus.lastattempt.canedit && (!this.submittedOffline || !this.assign!.submissiondrafts); @@ -1064,7 +1064,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { this.showErrorStatementSubmit = submissionStatementMissing && !!this.assign!.submissiondrafts; - this.userSubmission = AddonModAssign.instance.getSubmissionObjectFromAttempt(this.assign!, submissionStatus.lastattempt); + this.userSubmission = AddonModAssign.getSubmissionObjectFromAttempt(this.assign!, submissionStatus.lastattempt); if (this.assign!.attemptreopenmethod != this.attemptReopenMethodNone && this.userSubmission) { this.currentAttempt = this.userSubmission.attemptnumber + 1; @@ -1075,7 +1075,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { if (this.assign!.teamsubmission) { if (submissionStatus.lastattempt.submissiongroup) { // Get the name of the group. - promises.push(CoreGroups.instance.getActivityAllowedGroups(this.assign!.cmid).then((result) => { + promises.push(CoreGroups.getActivityAllowedGroups(this.assign!.cmid).then((result) => { const group = result.groups.find((group) => group.id == submissionStatus.lastattempt!.submissiongroup); if (group) { this.lastAttempt!.submissiongroupname = group.name; @@ -1093,7 +1093,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { submissionStatus.lastattempt.submissiongroupmemberswhoneedtosubmit.forEach((member) => { if (this.blindMarking) { // Users not blinded! (Moodle < 3.1.1, 3.2). - promises.push(AddonModAssign.instance.getAssignmentUserMappings(this.assign!.id, member, { + promises.push(AddonModAssign.getAssignmentUserMappings(this.assign!.id, member, { cmId: this.moduleId, }).then((blindId) => { this.membersToSubmitBlind.push(blindId); @@ -1101,7 +1101,7 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { return; })); } else { - promises.push(CoreUser.instance.getProfile(member, this.courseId).then((profile) => { + promises.push(CoreUser.getProfile(member, this.courseId).then((profile) => { this.membersToSubmit.push(profile); return; @@ -1112,10 +1112,10 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { } // Get grading text and color. - this.gradingStatusTranslationId = AddonModAssign.instance.getSubmissionGradingStatusTranslationId( + this.gradingStatusTranslationId = AddonModAssign.getSubmissionGradingStatusTranslationId( submissionStatus.lastattempt.gradingstatus, ); - this.gradingColor = AddonModAssign.instance.getSubmissionGradingStatusColor(submissionStatus.lastattempt.gradingstatus); + this.gradingColor = AddonModAssign.getSubmissionGradingStatusColor(submissionStatus.lastattempt.gradingstatus); // Get the submission plugins. if (this.userSubmission) { @@ -1146,12 +1146,12 @@ export class AddonModAssignSubmissionComponent implements OnInit, OnDestroy { return; } - const syncId = AddonModAssignSync.instance.getGradeSyncId(this.assign!.id, this.submitId); + const syncId = AddonModAssignSync.getGradeSyncId(this.assign!.id, this.submitId); if (block) { - CoreSync.instance.blockOperation(AddonModAssignProvider.COMPONENT, syncId); + CoreSync.blockOperation(AddonModAssignProvider.COMPONENT, syncId); } else { - CoreSync.instance.unblockOperation(AddonModAssignProvider.COMPONENT, syncId); + CoreSync.unblockOperation(AddonModAssignProvider.COMPONENT, syncId); } } diff --git a/src/addons/mod/assign/feedback/comments/comments.module.ts b/src/addons/mod/assign/feedback/comments/comments.module.ts index 3cf1f28a5..ff01066df 100644 --- a/src/addons/mod/assign/feedback/comments/comments.module.ts +++ b/src/addons/mod/assign/feedback/comments/comments.module.ts @@ -33,7 +33,7 @@ import { AddonModAssignFeedbackDelegate } from '../../services/feedback-delegate multi: true, deps: [], useFactory: () => () => { - AddonModAssignFeedbackDelegate.instance.registerHandler(AddonModAssignFeedbackCommentsHandler.instance); + AddonModAssignFeedbackDelegate.registerHandler(AddonModAssignFeedbackCommentsHandler.instance); }, }, ], diff --git a/src/addons/mod/assign/feedback/comments/component/comments.ts b/src/addons/mod/assign/feedback/comments/component/comments.ts index 0bfbf4384..7646562ad 100644 --- a/src/addons/mod/assign/feedback/comments/component/comments.ts +++ b/src/addons/mod/assign/feedback/comments/component/comments.ts @@ -65,7 +65,7 @@ export class AddonModAssignFeedbackCommentsComponent extends AddonModAssignFeedb if (this.text) { // Open a new state with the text. - CoreTextUtils.instance.viewText(this.plugin.name, this.text, { + CoreTextUtils.viewText(this.plugin.name, this.text, { component: this.component, componentId: this.assign.cmid, filter: true, @@ -89,12 +89,12 @@ export class AddonModAssignFeedbackCommentsComponent extends AddonModAssignFeedb async editComment(): Promise { try { const inputData = await this.editFeedback(); - const text = AddonModAssignFeedbackCommentsHandler.instance.getTextFromInputData(this.plugin, inputData); + const text = AddonModAssignFeedbackCommentsHandler.getTextFromInputData(this.plugin, inputData); // Update the text and save it as draft. this.isSent = false; this.text = this.replacePluginfileUrls(text); - AddonModAssignFeedbackDelegate.instance.saveFeedbackDraft(this.assign.id, this.userId, this.plugin, { + AddonModAssignFeedbackDelegate.saveFeedbackDraft(this.assign.id, this.userId, this.plugin, { text: text, format: 1, }); @@ -111,7 +111,7 @@ export class AddonModAssignFeedbackCommentsComponent extends AddonModAssignFeedb protected async getText(): Promise { // Check if the user already modified the comment. const draft: AddonModAssignFeedbackCommentsDraftData | undefined = - await AddonModAssignFeedbackDelegate.instance.getPluginDraftData(this.assign.id, this.userId, this.plugin); + await AddonModAssignFeedbackDelegate.getPluginDraftData(this.assign.id, this.userId, this.plugin); if (draft) { this.isSent = false; @@ -120,8 +120,8 @@ export class AddonModAssignFeedbackCommentsComponent extends AddonModAssignFeedb } // There is no draft saved. Check if we have anything offline. - const offlineData = await CoreUtils.instance.ignoreErrors( - AddonModAssignOffline.instance.getSubmissionGrade(this.assign.id, this.userId), + const offlineData = await CoreUtils.ignoreErrors( + AddonModAssignOffline.getSubmissionGrade(this.assign.id, this.userId), undefined, ); @@ -130,7 +130,7 @@ export class AddonModAssignFeedbackCommentsComponent extends AddonModAssignFeedb // Save offline as draft. this.isSent = false; - AddonModAssignFeedbackDelegate.instance.saveFeedbackDraft( + AddonModAssignFeedbackDelegate.saveFeedbackDraft( this.assign.id, this.userId, this.plugin, @@ -143,7 +143,7 @@ export class AddonModAssignFeedbackCommentsComponent extends AddonModAssignFeedb // No offline data found, return online text. this.isSent = true; - return AddonModAssign.instance.getSubmissionPluginText(this.plugin); + return AddonModAssign.getSubmissionPluginText(this.plugin); } /** @@ -155,7 +155,7 @@ export class AddonModAssignFeedbackCommentsComponent extends AddonModAssignFeedb replacePluginfileUrls(text: string): string { const files = this.plugin.fileareas && this.plugin.fileareas[0] && this.plugin.fileareas[0].files; - return CoreTextUtils.instance.replacePluginfileUrls(text, files || []); + return CoreTextUtils.replacePluginfileUrls(text, files || []); } } diff --git a/src/addons/mod/assign/feedback/comments/services/handler.ts b/src/addons/mod/assign/feedback/comments/services/handler.ts index 22852c3b5..c952f961c 100644 --- a/src/addons/mod/assign/feedback/comments/services/handler.ts +++ b/src/addons/mod/assign/feedback/comments/services/handler.ts @@ -55,7 +55,7 @@ export class AddonModAssignFeedbackCommentsHandlerService implements AddonModAss // The input data can have a string or an object with text and format. Get the text. const text = inputData.assignfeedbackcomments_editor || ''; - return CoreTextUtils.instance.restorePluginfileUrls(text, files || []); + return CoreTextUtils.restorePluginfileUrls(text, files || []); } /** @@ -108,7 +108,7 @@ export class AddonModAssignFeedbackCommentsHandlerService implements AddonModAss * @return Draft ID. */ protected getDraftId(assignId: number, userId: number, siteId?: string): string { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); return siteId + '#' + assignId + '#' + userId; } @@ -127,7 +127,7 @@ export class AddonModAssignFeedbackCommentsHandlerService implements AddonModAss submission: AddonModAssignSubmission, plugin: AddonModAssignPlugin, ): CoreWSExternalFile[] { - return AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + return AddonModAssign.getSubmissionPluginAttachments(plugin); } /** @@ -148,8 +148,8 @@ export class AddonModAssignFeedbackCommentsHandlerService implements AddonModAss userId: number, ): Promise { // Get it from plugin or offline. - const offlineData = await CoreUtils.instance.ignoreErrors( - AddonModAssignOffline.instance.getSubmissionGrade(assign.id, userId), + const offlineData = await CoreUtils.ignoreErrors( + AddonModAssignOffline.getSubmissionGrade(assign.id, userId), undefined, ); @@ -160,8 +160,8 @@ export class AddonModAssignFeedbackCommentsHandlerService implements AddonModAss } // No offline data found, get text from plugin. - const initialText = AddonModAssign.instance.getSubmissionPluginText(plugin); - const newText = AddonModAssignFeedbackCommentsHandler.instance.getTextFromInputData(plugin, inputData); + const initialText = AddonModAssign.getSubmissionPluginText(plugin); + const newText = AddonModAssignFeedbackCommentsHandler.getTextFromInputData(plugin, inputData); if (typeof newText == 'undefined') { return false; @@ -219,7 +219,7 @@ export class AddonModAssignFeedbackCommentsHandlerService implements AddonModAss if (draft) { // Add some HTML to the text if needed. - draft.text = CoreTextUtils.instance.formatHtmlLines(draft.text); + draft.text = CoreTextUtils.formatHtmlLines(draft.text); pluginData.assignfeedbackcomments_editor = draft; } diff --git a/src/addons/mod/assign/feedback/editpdf/component/editpdf.ts b/src/addons/mod/assign/feedback/editpdf/component/editpdf.ts index f77089ec6..df1ff86ea 100644 --- a/src/addons/mod/assign/feedback/editpdf/component/editpdf.ts +++ b/src/addons/mod/assign/feedback/editpdf/component/editpdf.ts @@ -34,7 +34,7 @@ export class AddonModAssignFeedbackEditPdfComponent extends AddonModAssignFeedba */ async ngOnInit(): Promise { if (this.plugin) { - this.files = AddonModAssign.instance.getSubmissionPluginAttachments(this.plugin); + this.files = AddonModAssign.getSubmissionPluginAttachments(this.plugin); } } diff --git a/src/addons/mod/assign/feedback/editpdf/editpdf.module.ts b/src/addons/mod/assign/feedback/editpdf/editpdf.module.ts index c91596cb2..b9004c861 100644 --- a/src/addons/mod/assign/feedback/editpdf/editpdf.module.ts +++ b/src/addons/mod/assign/feedback/editpdf/editpdf.module.ts @@ -31,7 +31,7 @@ import { AddonModAssignFeedbackDelegate } from '../../services/feedback-delegate multi: true, deps: [], useFactory: () => () => { - AddonModAssignFeedbackDelegate.instance.registerHandler(AddonModAssignFeedbackEditPdfHandler.instance); + AddonModAssignFeedbackDelegate.registerHandler(AddonModAssignFeedbackEditPdfHandler.instance); }, }, ], diff --git a/src/addons/mod/assign/feedback/editpdf/services/handler.ts b/src/addons/mod/assign/feedback/editpdf/services/handler.ts index 216ba11c1..dc9cb02d7 100644 --- a/src/addons/mod/assign/feedback/editpdf/services/handler.ts +++ b/src/addons/mod/assign/feedback/editpdf/services/handler.ts @@ -57,7 +57,7 @@ export class AddonModAssignFeedbackEditPdfHandlerService implements AddonModAssi submission: AddonModAssignSubmission, plugin: AddonModAssignPlugin, ): CoreWSExternalFile[] { - return AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + return AddonModAssign.getSubmissionPluginAttachments(plugin); } /** diff --git a/src/addons/mod/assign/feedback/file/component/file.ts b/src/addons/mod/assign/feedback/file/component/file.ts index 45c0bb9b3..64d2af54f 100644 --- a/src/addons/mod/assign/feedback/file/component/file.ts +++ b/src/addons/mod/assign/feedback/file/component/file.ts @@ -34,7 +34,7 @@ export class AddonModAssignFeedbackFileComponent extends AddonModAssignFeedbackP */ async ngOnInit(): Promise { if (this.plugin) { - this.files = AddonModAssign.instance.getSubmissionPluginAttachments(this.plugin); + this.files = AddonModAssign.getSubmissionPluginAttachments(this.plugin); } } diff --git a/src/addons/mod/assign/feedback/file/file.module.ts b/src/addons/mod/assign/feedback/file/file.module.ts index 45bfddd28..9a005629d 100644 --- a/src/addons/mod/assign/feedback/file/file.module.ts +++ b/src/addons/mod/assign/feedback/file/file.module.ts @@ -31,7 +31,7 @@ import { AddonModAssignFeedbackDelegate } from '../../services/feedback-delegate multi: true, deps: [], useFactory: () => () => { - AddonModAssignFeedbackDelegate.instance.registerHandler(AddonModAssignFeedbackFileHandler.instance); + AddonModAssignFeedbackDelegate.registerHandler(AddonModAssignFeedbackFileHandler.instance); }, }, ], diff --git a/src/addons/mod/assign/feedback/file/services/handler.ts b/src/addons/mod/assign/feedback/file/services/handler.ts index 9e12e4fd2..d8854bb13 100644 --- a/src/addons/mod/assign/feedback/file/services/handler.ts +++ b/src/addons/mod/assign/feedback/file/services/handler.ts @@ -57,7 +57,7 @@ export class AddonModAssignFeedbackFileHandlerService implements AddonModAssignF submission: AddonModAssignSubmission, plugin: AddonModAssignPlugin, ): CoreWSExternalFile[] { - return AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + return AddonModAssign.getSubmissionPluginAttachments(plugin); } /** diff --git a/src/addons/mod/assign/pages/edit/edit.ts b/src/addons/mod/assign/pages/edit/edit.ts index 0b6b1075d..6eb7739ac 100644 --- a/src/addons/mod/assign/pages/edit/edit.ts +++ b/src/addons/mod/assign/pages/edit/edit.ts @@ -69,8 +69,8 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { constructor( protected route: ActivatedRoute, ) { - this.userId = CoreSites.instance.getCurrentSiteUserId(); // Right now we can only edit current user's submissions. - this.editText = Translate.instance.instant('addon.mod_assign.editsubmission'); + this.userId = CoreSites.getCurrentSiteUserId(); // Right now we can only edit current user's submissions. + this.editText = Translate.instant('addon.mod_assign.editsubmission'); this.title = this.editText; } @@ -78,9 +78,9 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { * Component being initialized. */ ngOnInit(): void { - this.moduleId = CoreNavigator.instance.getRouteNumberParam('cmId')!; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.isBlind = !!CoreNavigator.instance.getRouteNumberParam('blindId'); + this.moduleId = CoreNavigator.getRouteNumberParam('cmId')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.isBlind = !!CoreNavigator.getRouteNumberParam('blindId'); this.fetchAssignment().finally(() => { this.loaded = true; @@ -100,13 +100,13 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { // Check if data has changed. const changed = await this.hasDataChanged(); if (changed) { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.confirmcanceledit')); + await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); } // Nothing has changed or user confirmed to leave. Clear temporary data from plugins. - AddonModAssignHelper.instance.clearSubmissionPluginTmpData(this.assign!, this.userSubmission, this.getInputData()); + AddonModAssignHelper.clearSubmissionPluginTmpData(this.assign!, this.userSubmission, this.getInputData()); - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); } /** @@ -115,20 +115,20 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ protected async fetchAssignment(): Promise { - const currentUserId = CoreSites.instance.getCurrentSiteUserId(); + const currentUserId = CoreSites.getCurrentSiteUserId(); try { // Get assignment data. - this.assign = await AddonModAssign.instance.getAssignment(this.courseId, this.moduleId); + this.assign = await AddonModAssign.getAssignment(this.courseId, this.moduleId); this.title = this.assign.name || this.title; if (!this.isDestroyed) { // Block the assignment. - CoreSync.instance.blockOperation(AddonModAssignProvider.COMPONENT, this.assign.id); + CoreSync.blockOperation(AddonModAssignProvider.COMPONENT, this.assign.id); } // Wait for sync to be over (if any). - await AddonModAssignSync.instance.waitForSync(this.assign.id); + await AddonModAssignSync.waitForSync(this.assign.id); // Get submission status. Ignore cache to get the latest data. const options: AddonModAssignSubmissionStatusOptions = { @@ -141,21 +141,21 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { let submissionStatus: AddonModAssignGetSubmissionStatusWSResponse; try { - submissionStatus = await AddonModAssign.instance.getSubmissionStatus(this.assign.id, options); + submissionStatus = await AddonModAssign.getSubmissionStatus(this.assign.id, options); this.userSubmission = - AddonModAssign.instance.getSubmissionObjectFromAttempt(this.assign, submissionStatus.lastattempt); + AddonModAssign.getSubmissionObjectFromAttempt(this.assign, submissionStatus.lastattempt); } catch (error) { // Cannot connect. Get cached data. options.filter = true; options.readingStrategy = CoreSitesReadingStrategy.PreferCache; - submissionStatus = await AddonModAssign.instance.getSubmissionStatus(this.assign.id, options); + submissionStatus = await AddonModAssign.getSubmissionStatus(this.assign.id, options); this.userSubmission = - AddonModAssign.instance.getSubmissionObjectFromAttempt(this.assign, submissionStatus.lastattempt); + AddonModAssign.getSubmissionObjectFromAttempt(this.assign, submissionStatus.lastattempt); // Check if the user can edit it in offline. const canEditOffline = - await AddonModAssignHelper.instance.canEditSubmissionOffline(this.assign, this.userSubmission); + await AddonModAssignHelper.canEditSubmissionOffline(this.assign, this.userSubmission); if (!canEditOffline) { // Submission cannot be edited in offline, reject. this.allowOffline = false; @@ -165,7 +165,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { if (!submissionStatus.lastattempt?.canedit) { // Can't edit. Reject. - throw new CoreError(Translate.instance.instant('core.nopermissions', { $a: this.editText })); + throw new CoreError(Translate.instant('core.nopermissions', { $a: this.editText })); } this.allowOffline = true; // If offline isn't allowed we shouldn't have reached this point. @@ -178,7 +178,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { try { // Check if there's any offline data for this submission. - const offlineData = await AddonModAssignOffline.instance.getSubmission(this.assign.id, this.userId); + const offlineData = await AddonModAssignOffline.getSubmission(this.assign.id, this.userId); this.hasOffline = offlineData?.plugindata && Object.keys(offlineData.plugindata).length > 0; } catch { @@ -186,7 +186,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { this.hasOffline = false; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting assigment data.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting assigment data.'); // Leave the player. this.leaveWithoutCheck(); @@ -199,7 +199,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { * @return Input data. */ protected getInputData(): Record { - return CoreDomUtils.instance.getDataFromForm(document.forms['addon-mod_assign-edit-form']); + return CoreDomUtils.getDataFromForm(document.forms['addon-mod_assign-edit-form']); } /** @@ -210,11 +210,11 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { protected async hasDataChanged(): Promise { // Usually the hasSubmissionDataChanged call will be resolved inmediately, causing the modal to be shown just an instant. // We'll wait a bit before showing it to prevent this "blink". - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); const data = this.getInputData(); - return AddonModAssignHelper.instance.hasSubmissionDataChanged(this.assign!, this.userSubmission, data).finally(() => { + return AddonModAssignHelper.hasSubmissionDataChanged(this.assign!, this.userSubmission, data).finally(() => { modal.dismiss(); }); } @@ -224,7 +224,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { */ protected leaveWithoutCheck(): void { this.forceLeave = true; - CoreNavigator.instance.back(); + CoreNavigator.back(); } /** @@ -238,7 +238,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { this.saveOffline = this.hasOffline; try { - return AddonModAssignHelper.instance.prepareSubmissionPluginData( + return AddonModAssignHelper.prepareSubmissionPluginData( this.assign!, this.userSubmission, inputData, @@ -249,7 +249,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { // Cannot submit in online, prepare for offline usage. this.saveOffline = true; - return AddonModAssignHelper.instance.prepareSubmissionPluginData( + return AddonModAssignHelper.prepareSubmissionPluginData( this.assign!, this.userSubmission, inputData, @@ -277,7 +277,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { await this.saveSubmission(); this.leaveWithoutCheck(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error saving submission.'); + CoreDomUtils.showErrorModalDefault(error, 'Error saving submission.'); } } @@ -290,15 +290,15 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { const inputData = this.getInputData(); if (this.submissionStatement && (!inputData.submissionstatement || inputData.submissionstatement === 'false')) { - throw Translate.instance.instant('addon.mod_assign.acceptsubmissionstatement'); + throw Translate.instant('addon.mod_assign.acceptsubmissionstatement'); } - let modal = await CoreDomUtils.instance.showModalLoading(); + let modal = await CoreDomUtils.showModalLoading(); let size = -1; // Get size to ask for confirmation. try { - size = await AddonModAssignHelper.instance.getSubmissionSizeForEdit(this.assign!, this.userSubmission!, inputData); + size = await AddonModAssignHelper.getSubmissionSizeForEdit(this.assign!, this.userSubmission!, inputData); } catch (error) { // Error calculating size, return -1. size = -1; @@ -308,9 +308,9 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { try { // Confirm action. - await CoreFileUploaderHelper.instance.confirmUploadFile(size, true, this.allowOffline); + await CoreFileUploaderHelper.confirmUploadFile(size, true, this.allowOffline); - modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + modal = await CoreDomUtils.showModalLoading('core.sending', true); const pluginData = await this.prepareSubmissionData(inputData); if (!Object.keys(pluginData).length) { @@ -323,7 +323,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { if (this.saveOffline) { // Save submission in offline. sent = false; - await AddonModAssignOffline.instance.saveSubmission( + await AddonModAssignOffline.saveSubmission( this.assign!.id, this.courseId, pluginData, @@ -333,7 +333,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { ); } else { // Try to send it to server. - sent = await AddonModAssign.instance.saveSubmission( + sent = await AddonModAssign.saveSubmission( this.assign!.id, this.courseId, pluginData, @@ -345,14 +345,14 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { } // Clear temporary data from plugins. - AddonModAssignHelper.instance.clearSubmissionPluginTmpData(this.assign!, this.userSubmission, inputData); + AddonModAssignHelper.clearSubmissionPluginTmpData(this.assign!, this.userSubmission, inputData); if (sent) { CoreEvents.trigger(CoreEvents.ACTIVITY_DATA_SENT, { module: 'assign' }); } // Submission saved, trigger events. - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, sent, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, sent, CoreSites.getCurrentSiteId()); CoreEvents.trigger( AddonModAssignProvider.SUBMISSION_SAVED_EVENT, @@ -361,7 +361,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { submissionId: this.userSubmission!.id, userId: this.userId, }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); if (!this.assign!.submissiondrafts) { @@ -373,7 +373,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { submissionId: this.userSubmission!.id, userId: this.userId, }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } } finally { @@ -389,7 +389,7 @@ export class AddonModAssignEditPage implements OnInit, OnDestroy { // Unblock the assignment. if (this.assign) { - CoreSync.instance.unblockOperation(AddonModAssignProvider.COMPONENT, this.assign.id); + CoreSync.unblockOperation(AddonModAssignProvider.COMPONENT, this.assign.id); } } diff --git a/src/addons/mod/assign/pages/index/index.page.ts b/src/addons/mod/assign/pages/index/index.page.ts index 3a7635582..e1e59f9fe 100644 --- a/src/addons/mod/assign/pages/index/index.page.ts +++ b/src/addons/mod/assign/pages/index/index.page.ts @@ -37,8 +37,8 @@ export class AddonModAssignIndexPage implements OnInit { * Component being initialized. */ ngOnInit(): void { - this.module = CoreNavigator.instance.getRouteParam('module'); - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId'); + this.module = CoreNavigator.getRouteParam('module'); + this.courseId = CoreNavigator.getRouteNumberParam('courseId'); this.title = this.module?.name; } diff --git a/src/addons/mod/assign/pages/submission-list/submission-list.page.ts b/src/addons/mod/assign/pages/submission-list/submission-list.page.ts index 2e3e3e435..4fd8f42f6 100644 --- a/src/addons/mod/assign/pages/submission-list/submission-list.page.ts +++ b/src/addons/mod/assign/pages/submission-list/submission-list.page.ts @@ -88,7 +88,7 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro this.loaded && this.assign && data.assignmentId == this.assign.id && - data.userId == CoreSites.instance.getCurrentSiteUserId() + data.userId == CoreSites.getCurrentSiteUserId() ) { // Grade changed, refresh the data. this.loaded = false; @@ -98,7 +98,7 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro }); } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); // Refresh data if this assign is synchronized. @@ -116,7 +116,7 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro this.loaded = true; }); }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } @@ -124,19 +124,19 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro * Component being initialized. */ ngAfterViewInit(): void { - this.moduleId = CoreNavigator.instance.getRouteNumberParam('cmId')!; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.groupId = CoreNavigator.instance.getRouteNumberParam('groupId') || 0; - this.selectedStatus = CoreNavigator.instance.getRouteParam('status'); + this.moduleId = CoreNavigator.getRouteNumberParam('cmId')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.groupId = CoreNavigator.getRouteNumberParam('groupId') || 0; + this.selectedStatus = CoreNavigator.getRouteParam('status'); if (this.selectedStatus) { if (this.selectedStatus == AddonModAssignProvider.NEED_GRADING) { - this.title = Translate.instance.instant('addon.mod_assign.numberofsubmissionsneedgrading'); + this.title = Translate.instant('addon.mod_assign.numberofsubmissionsneedgrading'); } else { - this.title = Translate.instance.instant('addon.mod_assign.submissionstatus_' + this.selectedStatus); + this.title = Translate.instant('addon.mod_assign.submissionstatus_' + this.selectedStatus); } } else { - this.title = Translate.instance.instant('addon.mod_assign.numberofparticipants'); + this.title = Translate.instant('addon.mod_assign.numberofparticipants'); } this.fetchAssignment(true).finally(() => { this.loaded = true; @@ -153,14 +153,14 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro protected async fetchAssignment(sync = false): Promise { try { // Get assignment data. - this.assign = await AddonModAssign.instance.getAssignment(this.courseId, this.moduleId); + this.assign = await AddonModAssign.getAssignment(this.courseId, this.moduleId); this.title = this.assign.name || this.title; if (sync) { try { // Try to synchronize data. - const result = await AddonModAssignSync.instance.syncAssign(this.assign.id); + const result = await AddonModAssignSync.syncAssign(this.assign.id); if (result && result.updated) { CoreEvents.trigger( @@ -171,7 +171,7 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro gradesBlocked: result.gradesBlocked, context: 'submission-list', }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } } catch (error) { @@ -180,7 +180,7 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro } // Get assignment submissions. - this.submissionsData = await AddonModAssign.instance.getSubmissions(this.assign.id, { cmId: this.assign.cmid }); + this.submissionsData = await AddonModAssign.getSubmissions(this.assign.id, { cmId: this.assign.cmid }); if (!this.submissionsData.canviewsubmissions) { // User shouldn't be able to reach here. @@ -188,11 +188,11 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro } // Check if groupmode is enabled to avoid showing wrong numbers. - this.groupInfo = await CoreGroups.instance.getActivityGroupInfo(this.assign.cmid, false); + this.groupInfo = await CoreGroups.getActivityGroupInfo(this.assign.cmid, false); - await this.setGroup(CoreGroups.instance.validateGroupId(this.groupId, this.groupInfo)); + await this.setGroup(CoreGroups.validateGroupId(this.groupId, this.groupInfo)); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting assigment data.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting assigment data.'); } } @@ -207,7 +207,7 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro this.haveAllParticipants = true; - if (!CoreSites.instance.getCurrentSite()?.wsAvailable('mod_assign_list_participants')) { + if (!CoreSites.getCurrentSite()?.wsAvailable('mod_assign_list_participants')) { // Submissions are not displayed in Moodle 3.1 without the local plugin, see MOBILE-2968. this.haveAllParticipants = false; this.submissions.resetItems(); @@ -217,14 +217,14 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro // Fetch submissions and grades. const submissions = - await AddonModAssignHelper.instance.getSubmissionsUserData( + await AddonModAssignHelper.getSubmissionsUserData( this.assign!, this.submissionsData.submissions, this.groupId, ); // Get assignment grades only if workflow is not enabled to check grading date. const grades = !this.assign!.markingworkflow - ? await AddonModAssign.instance.getAssignmentGrades(this.assign!.id, { cmId: this.assign!.cmid }) + ? await AddonModAssign.getAssignmentGrades(this.assign!.id, { cmId: this.assign!.cmid }) : []; // Filter the submissions to get only the ones with the right status and add some extra data. @@ -237,12 +237,12 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro submissions.forEach((submission: AddonModAssignSubmissionForList) => { if (!searchStatus || searchStatus == submission.status) { promises.push( - CoreUtils.instance.ignoreErrors( - AddonModAssignOffline.instance.getSubmissionGrade(this.assign!.id, submission.userid), + CoreUtils.ignoreErrors( + AddonModAssignOffline.getSubmissionGrade(this.assign!.id, submission.userid), ).then(async (data) => { if (getNeedGrading) { // Only show the submissions that need to be graded. - const add = await AddonModAssign.instance.needsSubmissionToBeGraded(submission, this.assign!.id); + const add = await AddonModAssign.needsSubmissionToBeGraded(submission, this.assign!.id); if (!add) { return; @@ -262,14 +262,14 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro submission.gradingstatus = AddonModAssignProvider.GRADED_FOLLOWUP_SUBMIT; } } - submission.statusColor = AddonModAssign.instance.getSubmissionStatusColor(submission.status); - submission.gradingColor = AddonModAssign.instance.getSubmissionGradingStatusColor( + submission.statusColor = AddonModAssign.getSubmissionStatusColor(submission.status); + submission.gradingColor = AddonModAssign.getSubmissionGradingStatusColor( submission.gradingstatus, ); // Show submission status if not submitted for grading. if (submission.statusColor != 'success' || !submission.gradingstatus) { - submission.statusTranslated = Translate.instance.instant( + submission.statusTranslated = Translate.instant( 'addon.mod_assign.submissionstatus_' + submission.status, ); } else { @@ -281,7 +281,7 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro submission.gradingColor = ''; } else if (submission.statusColor != 'danger' || submission.gradingColor != 'danger') { // Show grading status if one of the statuses is not done. - submission.gradingStatusTranslationId = AddonModAssign.instance.getSubmissionGradingStatusTranslationId( + submission.gradingStatusTranslationId = AddonModAssign.getSubmissionGradingStatusTranslationId( submission.gradingstatus, ); } else { @@ -310,12 +310,12 @@ export class AddonModAssignSubmissionListPage implements AfterViewInit, OnDestro protected async refreshAllData(sync?: boolean): Promise { const promises: Promise[] = []; - promises.push(AddonModAssign.instance.invalidateAssignmentData(this.courseId)); + promises.push(AddonModAssign.invalidateAssignmentData(this.courseId)); if (this.assign) { - promises.push(AddonModAssign.instance.invalidateAllSubmissionData(this.assign.id)); - promises.push(AddonModAssign.instance.invalidateAssignmentUserMappingsData(this.assign.id)); - promises.push(AddonModAssign.instance.invalidateAssignmentGradesData(this.assign.id)); - promises.push(AddonModAssign.instance.invalidateListParticipantsData(this.assign.id)); + promises.push(AddonModAssign.invalidateAllSubmissionData(this.assign.id)); + promises.push(AddonModAssign.invalidateAssignmentUserMappingsData(this.assign.id)); + promises.push(AddonModAssign.invalidateAssignmentGradesData(this.assign.id)); + promises.push(AddonModAssign.invalidateListParticipantsData(this.assign.id)); } try { diff --git a/src/addons/mod/assign/pages/submission-review/submission-review.ts b/src/addons/mod/assign/pages/submission-review/submission-review.ts index bca89ffa0..8446a9c45 100644 --- a/src/addons/mod/assign/pages/submission-review/submission-review.ts +++ b/src/addons/mod/assign/pages/submission-review/submission-review.ts @@ -55,10 +55,10 @@ export class AddonModAssignSubmissionReviewPage implements OnInit { */ ngOnInit(): void { this.route.queryParams.subscribe((params) => { - this.moduleId = CoreNavigator.instance.getRouteNumberParam('cmId')!; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.submitId = CoreNavigator.instance.getRouteNumberParam('submitId') || 0; - this.blindId = CoreNavigator.instance.getRouteNumberParam('blindId', params); + this.moduleId = CoreNavigator.getRouteNumberParam('cmId')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.submitId = CoreNavigator.getRouteNumberParam('submitId') || 0; + this.blindId = CoreNavigator.getRouteNumberParam('blindId', params); this.fetchSubmission().finally(() => { this.loaded = true; @@ -100,12 +100,12 @@ export class AddonModAssignSubmissionReviewPage implements OnInit { * @return Promise resolved when done. */ protected async fetchSubmission(): Promise { - this.assign = await AddonModAssign.instance.getAssignment(this.courseId, this.moduleId); + this.assign = await AddonModAssign.getAssignment(this.courseId, this.moduleId); this.title = this.assign.name; this.blindMarking = !!this.assign.blindmarking && !this.assign.revealidentities; - const gradeInfo = await CoreCourse.instance.getModuleBasicGradeInfo(this.moduleId); + const gradeInfo = await CoreCourse.getModuleBasicGradeInfo(this.moduleId); if (!gradeInfo) { return; } @@ -129,11 +129,11 @@ export class AddonModAssignSubmissionReviewPage implements OnInit { protected async refreshAllData(): Promise { const promises: Promise[] = []; - promises.push(AddonModAssign.instance.invalidateAssignmentData(this.courseId)); + promises.push(AddonModAssign.invalidateAssignmentData(this.courseId)); if (this.assign) { - promises.push(AddonModAssign.instance.invalidateSubmissionData(this.assign.id)); - promises.push(AddonModAssign.instance.invalidateAssignmentUserMappingsData(this.assign.id)); - promises.push(AddonModAssign.instance.invalidateSubmissionStatusData( + promises.push(AddonModAssign.invalidateSubmissionData(this.assign.id)); + promises.push(AddonModAssign.invalidateAssignmentUserMappingsData(this.assign.id)); + promises.push(AddonModAssign.invalidateSubmissionStatusData( this.assign.id, this.submitId, undefined, @@ -172,12 +172,12 @@ export class AddonModAssignSubmissionReviewPage implements OnInit { try { await this.submissionComponent.submitGrade(); // Grade submitted, leave the view if not in tablet. - if (!CoreScreen.instance.isTablet) { + if (!CoreScreen.isTablet) { this.forceLeave = true; - CoreNavigator.instance.back(); + CoreNavigator.back(); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); } } diff --git a/src/addons/mod/assign/services/assign-helper.ts b/src/addons/mod/assign/services/assign-helper.ts index 178408d8b..5367e59c0 100644 --- a/src/addons/mod/assign/services/assign-helper.ts +++ b/src/addons/mod/assign/services/assign-helper.ts @@ -64,7 +64,7 @@ export class AddonModAssignHelperProvider { const promises = submission.plugins ? submission.plugins.map((plugin) => - AddonModAssignSubmissionDelegate.instance.canPluginEditOffline(assign, submission, plugin).then((canEditPlugin) => { + AddonModAssignSubmissionDelegate.canPluginEditOffline(assign, submission, plugin).then((canEditPlugin) => { if (!canEditPlugin) { canEdit = false; } @@ -95,7 +95,7 @@ export class AddonModAssignHelperProvider { } submission.plugins?.forEach((plugin) => { - AddonModAssignSubmissionDelegate.instance.clearTmpData(assign, submission, plugin, inputData); + AddonModAssignSubmissionDelegate.clearTmpData(assign, submission, plugin, inputData); }); } @@ -111,7 +111,7 @@ export class AddonModAssignHelperProvider { const pluginData: AddonModAssignSavePluginData = {}; const promises = previousSubmission.plugins ? previousSubmission.plugins.map((plugin) => - AddonModAssignSubmissionDelegate.instance.copyPluginSubmissionData(assign, plugin, pluginData)) + AddonModAssignSubmissionDelegate.copyPluginSubmissionData(assign, plugin, pluginData)) : []; await Promise.all(promises); @@ -119,7 +119,7 @@ export class AddonModAssignHelperProvider { // We got the plugin data. Now we need to submit it. if (Object.keys(pluginData).length) { // There's something to save. - return AddonModAssign.instance.saveSubmissionOnline(assign.id, pluginData); + return AddonModAssign.saveSubmissionOnline(assign.id, pluginData); } } @@ -163,9 +163,9 @@ export class AddonModAssignHelperProvider { * @return Promise resolved when done. */ async deleteStoredSubmissionFiles(assignId: number, folderName: string, userId?: number, siteId?: string): Promise { - const folderPath = await AddonModAssignOffline.instance.getSubmissionPluginFolder(assignId, folderName, userId, siteId); + const folderPath = await AddonModAssignOffline.getSubmissionPluginFolder(assignId, folderName, userId, siteId); - await CoreFile.instance.removeDir(folderPath); + await CoreFile.removeDir(folderPath); } /** @@ -186,7 +186,7 @@ export class AddonModAssignHelperProvider { const promises = feedback.plugins ? feedback.plugins.map((plugin) => - AddonModAssignFeedbackDelegate.instance.discardPluginFeedbackData(assignId, userId, plugin, siteId)) + AddonModAssignFeedbackDelegate.discardPluginFeedbackData(assignId, userId, plugin, siteId)) : []; await Promise.all(promises); @@ -205,7 +205,7 @@ export class AddonModAssignHelperProvider { } const anyNotEmpty = submission.plugins?.some((plugin) => - !AddonModAssignSubmissionDelegate.instance.isPluginEmpty(assign, plugin)); + !AddonModAssignSubmissionDelegate.isPluginEmpty(assign, plugin)); // If any plugin is not empty, we consider that the submission is not empty either. if (anyNotEmpty) { @@ -232,25 +232,25 @@ export class AddonModAssignHelperProvider { ): Promise { groupId = groupId || 0; - options.siteId = options.siteId || CoreSites.instance.getCurrentSiteId(); + options.siteId = options.siteId || CoreSites.getCurrentSiteId(); // Create new options including all existing ones. const modOptions: CoreCourseCommonModWSOptions = { cmId: assign.cmid, ...options }; - const participants = await AddonModAssign.instance.listParticipants(assign.id, groupId, modOptions); + const participants = await AddonModAssign.listParticipants(assign.id, groupId, modOptions); if (groupId || participants && participants.length > 0) { return participants; } // If no participants returned and all groups specified, get participants by groups. - const groupsInfo = await CoreGroups.instance.getActivityGroupInfo(assign.cmid, false, undefined, modOptions.siteId); + const groupsInfo = await CoreGroups.getActivityGroupInfo(assign.cmid, false, undefined, modOptions.siteId); const participantsIndexed: {[id: number]: AddonModAssignParticipant} = {}; const promises = groupsInfo.groups ? groupsInfo.groups.map((userGroup) => - AddonModAssign.instance.listParticipants(assign.id, userGroup.id, modOptions).then((participantsFromList) => { + AddonModAssign.listParticipants(assign.id, userGroup.id, modOptions).then((participantsFromList) => { // Do not get repeated users. participantsFromList.forEach((participant) => { participantsIndexed[participant.id] = participant; @@ -262,7 +262,7 @@ export class AddonModAssignHelperProvider { await Promise.all(promises); - return CoreUtils.instance.objectToArray(participantsIndexed); + return CoreUtils.objectToArray(participantsIndexed); } /** @@ -323,9 +323,9 @@ export class AddonModAssignHelperProvider { userId?: number, siteId?: string, ): Promise<(FileEntry | DirectoryEntry)[]> { - const folderPath = await AddonModAssignOffline.instance.getSubmissionPluginFolder(assignId, folderName, userId, siteId); + const folderPath = await AddonModAssignOffline.getSubmissionPluginFolder(assignId, folderName, userId, siteId); - return CoreFile.instance.getDirectoryContents(folderPath); + return CoreFile.getDirectoryContents(folderPath); } /** @@ -340,7 +340,7 @@ export class AddonModAssignHelperProvider { const promises = previousSubmission.plugins ? previousSubmission.plugins.map((plugin) => - AddonModAssignSubmissionDelegate.instance.getPluginSizeForCopy(assign, plugin).then((size) => { + AddonModAssignSubmissionDelegate.getPluginSizeForCopy(assign, plugin).then((size) => { totalSize += (size || 0); return; @@ -370,7 +370,7 @@ export class AddonModAssignHelperProvider { const promises = submission.plugins ? submission.plugins.map((plugin) => - AddonModAssignSubmissionDelegate.instance.getPluginSizeForEdit(assign, submission, plugin, inputData) + AddonModAssignSubmissionDelegate.getPluginSizeForEdit(assign, submission, plugin, inputData) .then((size) => { totalSize += (size || 0); @@ -406,7 +406,7 @@ export class AddonModAssignHelperProvider { const blind = assign.blindmarking && !assign.revealidentities; const promises: Promise[] = []; const result: AddonModAssignSubmissionFormatted[] = []; - const participants: {[id: number]: AddonModAssignParticipant} = CoreUtils.instance.arrayToObject(parts, 'id'); + const participants: {[id: number]: AddonModAssignParticipant} = CoreUtils.arrayToObject(parts, 'id'); submissions.forEach((submission) => { submission.submitid = submission.userid && submission.userid > 0 ? submission.userid : submission.blindid; @@ -439,7 +439,7 @@ export class AddonModAssignHelperProvider { // Blind but not blinded! (Moodle < 3.1.1, 3.2). delete submission.userid; - promise = AddonModAssign.instance.getAssignmentUserMappings(assign.id, submission.submitid, modOptions) + promise = AddonModAssign.getAssignmentUserMappings(assign.id, submission.submitid, modOptions) .then((blindId) => { submission.blindid = blindId; @@ -460,7 +460,7 @@ export class AddonModAssignHelperProvider { await Promise.all(promises); // Create a submission for each participant left in the list (the participants already treated were removed). - CoreUtils.instance.objectToArray(participants).forEach((participant: AddonModAssignParticipant) => { + CoreUtils.objectToArray(participants).forEach((participant: AddonModAssignParticipant) => { const submission = this.createEmptySubmission(); submission.submitid = participant.id; @@ -511,8 +511,8 @@ export class AddonModAssignHelperProvider { const promises = feedback.plugins.map((plugin) => this.prepareFeedbackPluginData(assign.id, userId, feedback).then(async (inputData) => { - const changed = await CoreUtils.instance.ignoreErrors( - AddonModAssignFeedbackDelegate.instance.hasPluginDataChanged(assign, submission, plugin, inputData, userId), + const changed = await CoreUtils.ignoreErrors( + AddonModAssignFeedbackDelegate.hasPluginDataChanged(assign, submission, plugin, inputData, userId), false, ); if (changed) { @@ -522,7 +522,7 @@ export class AddonModAssignHelperProvider { return; })); - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); return hasChanged; } @@ -548,7 +548,7 @@ export class AddonModAssignHelperProvider { const promises = submission.plugins ? submission.plugins.map((plugin) => - AddonModAssignSubmissionDelegate.instance.hasPluginDataChanged(assign, submission, plugin, inputData) + AddonModAssignSubmissionDelegate.hasPluginDataChanged(assign, submission, plugin, inputData) .then((changed) => { if (changed) { hasChanged = true; @@ -560,7 +560,7 @@ export class AddonModAssignHelperProvider { })) : []; - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); return hasChanged; } @@ -584,7 +584,7 @@ export class AddonModAssignHelperProvider { const pluginData: Record = {}; const promises = feedback.plugins ? feedback.plugins.map((plugin) => - AddonModAssignFeedbackDelegate.instance.preparePluginFeedbackData(assignId, userId, plugin, pluginData, siteId)) + AddonModAssignFeedbackDelegate.preparePluginFeedbackData(assignId, userId, plugin, pluginData, siteId)) : []; await Promise.all(promises); @@ -614,7 +614,7 @@ export class AddonModAssignHelperProvider { const pluginData: AddonModAssignSavePluginData = {}; const promises = submission.plugins.map((plugin) => - AddonModAssignSubmissionDelegate.instance.preparePluginSubmissionData( + AddonModAssignSubmissionDelegate.preparePluginSubmissionData( assign, submission, plugin, @@ -647,9 +647,9 @@ export class AddonModAssignHelperProvider { siteId?: string, ): Promise { // Get the folder where to store the files. - const folderPath = await AddonModAssignOffline.instance.getSubmissionPluginFolder(assignId, folderName, userId, siteId); + const folderPath = await AddonModAssignOffline.getSubmissionPluginFolder(assignId, folderName, userId, siteId); - return CoreFileUploader.instance.storeFilesToUpload(folderPath, files); + return CoreFileUploader.storeFilesToUpload(folderPath, files); } /** @@ -662,7 +662,7 @@ export class AddonModAssignHelperProvider { * @return Promise resolved with the itemId. */ uploadFile(assignId: number, file: CoreWSExternalFile | FileEntry, itemId?: number, siteId?: string): Promise { - return CoreFileUploader.instance.uploadOrReuploadFile(file, itemId, AddonModAssignProvider.COMPONENT, assignId, siteId); + return CoreFileUploader.uploadOrReuploadFile(file, itemId, AddonModAssignProvider.COMPONENT, assignId, siteId); } /** @@ -676,7 +676,7 @@ export class AddonModAssignHelperProvider { * @return Promise resolved with the itemId. */ uploadFiles(assignId: number, files: (CoreWSExternalFile | FileEntry)[], siteId?: string): Promise { - return CoreFileUploader.instance.uploadOrReuploadFiles(files, AddonModAssignProvider.COMPONENT, assignId, siteId); + return CoreFileUploader.uploadOrReuploadFiles(files, AddonModAssignProvider.COMPONENT, assignId, siteId); } /** diff --git a/src/addons/mod/assign/services/assign-offline.ts b/src/addons/mod/assign/services/assign-offline.ts index 81a56a300..3c339dd63 100644 --- a/src/addons/mod/assign/services/assign-offline.ts +++ b/src/addons/mod/assign/services/assign-offline.ts @@ -43,7 +43,7 @@ export class AddonModAssignOfflineProvider { * @return Promise resolved if deleted, rejected if failure. */ async deleteSubmission(assignId: number, userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.getDb().deleteRecords( @@ -61,7 +61,7 @@ export class AddonModAssignOfflineProvider { * @return Promise resolved if deleted, rejected if failure. */ async deleteSubmissionGrade(assignId: number, userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.getDb().deleteRecords( @@ -128,7 +128,7 @@ export class AddonModAssignOfflineProvider { conditions: SQLiteDBRecordValues = {}, siteId?: string, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const submissions: AddonModAssignSubmissionsDBRecord[] = await db.getRecords(SUBMISSIONS_TABLE, conditions); @@ -137,7 +137,7 @@ export class AddonModAssignOfflineProvider { assignid: submission.assignid, userid: submission.userid, courseid: submission.courseid, - plugindata: CoreTextUtils.instance.parseJSON(submission.plugindata, {}), + plugindata: CoreTextUtils.parseJSON(submission.plugindata, {}), onlinetimemodified: submission.onlinetimemodified, timecreated: submission.timecreated, timemodified: submission.timemodified, @@ -181,7 +181,7 @@ export class AddonModAssignOfflineProvider { conditions: SQLiteDBRecordValues = {}, siteId?: string, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const submissions: AddonModAssignSubmissionsGradingDBRecord[] = await db.getRecords(SUBMISSIONS_GRADES_TABLE, conditions); @@ -195,8 +195,8 @@ export class AddonModAssignOfflineProvider { addattempt: submission.addattempt, workflowstate: submission.workflowstate, applytoall: submission.applytoall, - outcomes: CoreTextUtils.instance.parseJSON(submission.outcomes, {}), - plugindata: CoreTextUtils.instance.parseJSON(submission.plugindata, {}), + outcomes: CoreTextUtils.parseJSON(submission.outcomes, {}), + plugindata: CoreTextUtils.parseJSON(submission.plugindata, {}), timemodified: submission.timemodified, })); } @@ -210,7 +210,7 @@ export class AddonModAssignOfflineProvider { * @return Promise resolved with submission. */ async getSubmission(assignId: number, userId?: number, siteId?: string): Promise { - userId = userId || CoreSites.instance.getCurrentSiteUserId(); + userId = userId || CoreSites.getCurrentSiteUserId(); const submissions = await this.getAssignSubmissionsFormatted({ assignid: assignId, userid: userId }, siteId); @@ -230,13 +230,13 @@ export class AddonModAssignOfflineProvider { * @return Promise resolved with the path. */ async getSubmissionFolder(assignId: number, userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); - const siteFolderPath = CoreFile.instance.getSiteFolder(site.getId()); + const siteFolderPath = CoreFile.getSiteFolder(site.getId()); const submissionFolderPath = 'offlineassign/' + assignId + '/' + userId; - return CoreTextUtils.instance.concatenatePaths(siteFolderPath, submissionFolderPath); + return CoreTextUtils.concatenatePaths(siteFolderPath, submissionFolderPath); } /** @@ -253,7 +253,7 @@ export class AddonModAssignOfflineProvider { userId?: number, siteId?: string, ): Promise { - userId = userId || CoreSites.instance.getCurrentSiteUserId(); + userId = userId || CoreSites.getCurrentSiteUserId(); const submissions = await this.getAssignSubmissionsGradeFormatted({ assignid: assignId, userid: userId }, siteId); @@ -276,7 +276,7 @@ export class AddonModAssignOfflineProvider { async getSubmissionPluginFolder(assignId: number, pluginName: string, userId?: number, siteId?: string): Promise { const folderPath = await this.getSubmissionFolder(assignId, userId, siteId); - return CoreTextUtils.instance.concatenatePaths(folderPath, pluginName); + return CoreTextUtils.concatenatePaths(folderPath, pluginName); } /** @@ -325,7 +325,7 @@ export class AddonModAssignOfflineProvider { userId?: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); let submission: AddonModAssignSubmissionsDBRecord; @@ -339,7 +339,7 @@ export class AddonModAssignOfflineProvider { }); } catch { // No submission, create an empty one. - const now = CoreTimeUtils.instance.timestamp(); + const now = CoreTimeUtils.timestamp(); submission = { assignid: assignId, courseid: courseId, @@ -377,11 +377,11 @@ export class AddonModAssignOfflineProvider { userId?: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); - const now = CoreTimeUtils.instance.timestamp(); + const now = CoreTimeUtils.timestamp(); const entry: AddonModAssignSubmissionsDBRecord = { assignid: assignId, courseid: courseId, @@ -425,9 +425,9 @@ export class AddonModAssignOfflineProvider { pluginData: AddonModAssignSavePluginData, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - const now = CoreTimeUtils.instance.timestamp(); + const now = CoreTimeUtils.timestamp(); const entry: AddonModAssignSubmissionsGradingDBRecord = { assignid: assignId, userid: userId, diff --git a/src/addons/mod/assign/services/assign-sync.ts b/src/addons/mod/assign/services/assign-sync.ts index cf78c7603..6cc49c328 100644 --- a/src/addons/mod/assign/services/assign-sync.ts +++ b/src/addons/mod/assign/services/assign-sync.ts @@ -55,7 +55,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid constructor() { super('AddonModLessonSyncProvider'); - this.componentTranslate = CoreCourse.instance.translateModuleName('assign'); + this.componentTranslate = CoreCourse.translateModuleName('assign'); } /** @@ -99,7 +99,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid * @return Promise resolved with boolean: whether it has data to sync. */ hasDataToSync(assignId: number, siteId?: string): Promise { - return AddonModAssignOffline.instance.hasAssignOfflineData(assignId, siteId); + return AddonModAssignOffline.hasAssignOfflineData(assignId, siteId); } /** @@ -122,7 +122,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid */ protected async syncAllAssignmentsFunc(force: boolean, siteId: string): Promise { // Get all assignments that have offline data. - const assignIds = await AddonModAssignOffline.instance.getAllAssigns(siteId); + const assignIds = await AddonModAssignOffline.getAllAssigns(siteId); // Try to sync all assignments. await Promise.all(assignIds.map(async (assignId) => { @@ -163,8 +163,8 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid * @return Promise resolved in success. */ async syncAssign(assignId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); - this.componentTranslate = this.componentTranslate || CoreCourse.instance.translateModuleName('assign'); + siteId = siteId || CoreSites.getCurrentSiteId(); + this.componentTranslate = this.componentTranslate || CoreCourse.translateModuleName('assign'); if (this.isSyncing(assignId, siteId)) { // There's already a sync ongoing for this assign, return the promise. @@ -172,10 +172,10 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid } // Verify that assign isn't blocked. - if (CoreSync.instance.isBlocked(AddonModAssignProvider.COMPONENT, assignId, siteId)) { + if (CoreSync.isBlocked(AddonModAssignProvider.COMPONENT, assignId, siteId)) { this.logger.debug('Cannot sync assign ' + assignId + ' because it is blocked.'); - throw new CoreSyncBlockedError(Translate.instance.instant('core.errorsyncblocked', { $a: this.componentTranslate })); + throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); } @@ -195,8 +195,8 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid */ protected async performSyncAssign(assignId: number, siteId: string): Promise { // Sync offline logs. - await CoreUtils.instance.ignoreErrors( - CoreCourseLogHelper.instance.syncActivity(AddonModAssignProvider.COMPONENT, assignId, siteId), + await CoreUtils.ignoreErrors( + CoreCourseLogHelper.syncActivity(AddonModAssignProvider.COMPONENT, assignId, siteId), ); const result: AddonModAssignSyncResult = { @@ -213,19 +213,19 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid if (!submissions.length && !grades.length) { // Nothing to sync. - await CoreUtils.instance.ignoreErrors(this.setSyncTime(assignId, siteId)); + await CoreUtils.ignoreErrors(this.setSyncTime(assignId, siteId)); return result; } - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // Cannot sync in offline. throw new CoreNetworkError(); } const courseId = submissions.length > 0 ? submissions[0].courseid : grades[0].courseid; - const assign = await AddonModAssign.instance.getAssignmentById(courseId, assignId, { siteId }); + const assign = await AddonModAssign.getAssignmentById(courseId, assignId, { siteId }); let promises: Promise[] = []; @@ -252,15 +252,15 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid } })); - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); if (result.updated) { // Data has been sent to server. Now invalidate the WS calls. - await CoreUtils.instance.ignoreErrors(AddonModAssign.instance.invalidateContent(assign.cmid, courseId, siteId)); + await CoreUtils.ignoreErrors(AddonModAssign.invalidateContent(assign.cmid, courseId, siteId)); } // Sync finished, set sync time. - await CoreUtils.instance.ignoreErrors(this.setSyncTime(assignId, siteId)); + await CoreUtils.ignoreErrors(this.setSyncTime(assignId, siteId)); // All done, return the result. return result; @@ -278,7 +278,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid siteId: string, ): Promise { // If no offline data found, return empty array. - return CoreUtils.instance.ignoreErrors(AddonModAssignOffline.instance.getAssignSubmissionsGrade(assignId, siteId), []); + return CoreUtils.ignoreErrors(AddonModAssignOffline.getAssignSubmissionsGrade(assignId, siteId), []); } /** @@ -293,7 +293,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid siteId: string, ): Promise { // If no offline data found, return empty array. - return CoreUtils.instance.ignoreErrors(AddonModAssignOffline.instance.getAssignSubmissions(assignId, siteId), []); + return CoreUtils.ignoreErrors(AddonModAssignOffline.getAssignSubmissions(assignId, siteId), []); } /** @@ -321,9 +321,9 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid siteId, }; - const status = await AddonModAssign.instance.getSubmissionStatus(assign.id, options); + const status = await AddonModAssign.getSubmissionStatus(assign.id, options); - const submission = AddonModAssign.instance.getSubmissionObjectFromAttempt(assign, status.lastattempt); + const submission = AddonModAssign.getSubmissionObjectFromAttempt(assign, status.lastattempt); if (submission && submission.timemodified != offlineData.onlinetimemodified) { // The submission was modified in Moodle, discard the submission. @@ -331,7 +331,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid warnings, this.componentTranslate, assign.name, - Translate.instance.instant('addon.mod_assign.warningsubmissionmodified'), + Translate.instant('addon.mod_assign.warningsubmissionmodified'), ); return this.deleteSubmissionData(assign, offlineData, submission, siteId); @@ -341,7 +341,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid if (submission?.plugins) { // Prepare plugins data. await Promise.all(submission.plugins.map((plugin) => - AddonModAssignSubmissionDelegate.instance.preparePluginSyncData( + AddonModAssignSubmissionDelegate.preparePluginSyncData( assign, submission, plugin, @@ -353,18 +353,18 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid // Now save the submission. if (Object.keys(pluginData).length > 0) { - await AddonModAssign.instance.saveSubmissionOnline(assign.id, pluginData, siteId); + await AddonModAssign.saveSubmissionOnline(assign.id, pluginData, siteId); } if (assign.submissiondrafts && offlineData.submitted) { // The user submitted the assign manually. Submit it for grading. - await AddonModAssign.instance.submitForGradingOnline(assign.id, !!offlineData.submissionstatement, siteId); + await AddonModAssign.submitForGradingOnline(assign.id, !!offlineData.submissionstatement, siteId); } // Submission data sent, update cached data. No need to block the user for this. - AddonModAssign.instance.getSubmissionStatus(assign.id, options); + AddonModAssign.getSubmissionStatus(assign.id, options); } catch (error) { - if (!error || !CoreUtils.instance.isWebServiceError(error)) { + if (!error || !CoreUtils.isWebServiceError(error)) { // Local error, reject. throw error; } @@ -374,7 +374,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid warnings, this.componentTranslate, assign.name, - CoreTextUtils.instance.getErrorMessageFromError(error) || '', + CoreTextUtils.getErrorMessageFromError(error) || '', ); } @@ -399,12 +399,12 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid ): Promise { // Delete the offline data. - await AddonModAssignOffline.instance.deleteSubmission(assign.id, offlineData.userid, siteId); + await AddonModAssignOffline.deleteSubmission(assign.id, offlineData.userid, siteId); if (submission?.plugins){ // Delete plugins data. await Promise.all(submission.plugins.map((plugin) => - AddonModAssignSubmissionDelegate.instance.deletePluginOfflineData( + AddonModAssignSubmissionDelegate.deletePluginOfflineData( assign, submission, plugin, @@ -442,16 +442,16 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid }; // Check if this grade sync is blocked. - if (CoreSync.instance.isBlocked(AddonModAssignProvider.COMPONENT, syncId, siteId)) { + if (CoreSync.isBlocked(AddonModAssignProvider.COMPONENT, syncId, siteId)) { this.logger.error(`Cannot sync grade for assign ${assign.id} and user ${userId} because it is blocked.!!!!`); - throw new CoreSyncBlockedError(Translate.instance.instant( + throw new CoreSyncBlockedError(Translate.instant( 'core.errorsyncblocked', - { $a: Translate.instance.instant('addon.mod_assign.syncblockedusercomponent') }, + { $a: Translate.instant('addon.mod_assign.syncblockedusercomponent') }, )); } - const status = await AddonModAssign.instance.getSubmissionStatus(assign.id, options); + const status = await AddonModAssign.getSubmissionStatus(assign.id, options); const timemodified = (status.feedback && (status.feedback.gradeddate || status.feedback.grade?.timemodified)) || 0; @@ -461,17 +461,17 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid warnings, this.componentTranslate, assign.name, - Translate.instance.instant('addon.mod_assign.warningsubmissiongrademodified'), + Translate.instant('addon.mod_assign.warningsubmissiongrademodified'), ); - return AddonModAssignOffline.instance.deleteSubmissionGrade(assign.id, userId, siteId); + return AddonModAssignOffline.deleteSubmissionGrade(assign.id, userId, siteId); } // If grade has been modified from gradebook, do not use offline. const grades: CoreGradesFormattedItem[] | CoreGradesFormattedRow[] = - await CoreGradesHelper.instance.getGradeModuleItems(courseId, assign.cmid, userId, undefined, siteId, true); + await CoreGradesHelper.getGradeModuleItems(courseId, assign.cmid, userId, undefined, siteId, true); - const gradeInfo = await CoreCourse.instance.getModuleBasicGradeInfo(assign.cmid, siteId); + const gradeInfo = await CoreCourse.getModuleBasicGradeInfo(assign.cmid, siteId); // Override offline grade and outcomes based on the gradebook data. grades.forEach((grade: CoreGradesFormattedItem | CoreGradesFormattedRow) => { @@ -482,7 +482,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid } else { offlineData.grade = parseFloat(grade.grade || ''); } - } else if (gradeInfo && grade.outcomeid && AddonModAssign.instance.isOutcomesEditEnabled() && gradeInfo.outcomes) { + } else if (gradeInfo && grade.outcomeid && AddonModAssign.isOutcomesEditEnabled() && gradeInfo.outcomes) { gradeInfo.outcomes.forEach((outcome, index) => { if (outcome.scale && grade.itemnumber == index) { offlineData.outcomes[grade.itemnumber] = this.getSelectedScaleId( @@ -497,7 +497,7 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid try { // Now submit the grade. - await AddonModAssign.instance.submitGradingFormOnline( + await AddonModAssign.submitGradingFormOnline( assign.id, userId, offlineData.grade, @@ -514,15 +514,15 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid let promises: Promise[] = []; if (status.feedback && status.feedback.plugins) { promises = status.feedback.plugins.map((plugin) => - AddonModAssignFeedbackDelegate.instance.discardPluginFeedbackData(assign.id, userId, plugin, siteId)); + AddonModAssignFeedbackDelegate.discardPluginFeedbackData(assign.id, userId, plugin, siteId)); } // Update cached data. - promises.push(AddonModAssign.instance.getSubmissionStatus(assign.id, options)); + promises.push(AddonModAssign.getSubmissionStatus(assign.id, options)); - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); } catch (error) { - if (!error || !CoreUtils.instance.isWebServiceError(error)) { + if (!error || !CoreUtils.isWebServiceError(error)) { // Local error, reject. throw error; } @@ -532,16 +532,16 @@ export class AddonModAssignSyncProvider extends CoreCourseActivitySyncBaseProvid warnings, this.componentTranslate, assign.name, - CoreTextUtils.instance.getErrorMessageFromError(error) || '', + CoreTextUtils.getErrorMessageFromError(error) || '', ); } // Delete the offline data. - await AddonModAssignOffline.instance.deleteSubmissionGrade(assign.id, userId, siteId); + await AddonModAssignOffline.deleteSubmissionGrade(assign.id, userId, siteId); } } -export const AddonModAssignSync = makeSingleton(AddonModAssignSyncProvider); +export const AddonModAssignSync = makeSingleton(AddonModAssignSyncProvider, ['component', 'syncInterval']); /** * Data returned by a assign sync. diff --git a/src/addons/mod/assign/services/assign.ts b/src/addons/mod/assign/services/assign.ts index 3a11c8b94..82590a2f9 100644 --- a/src/addons/mod/assign/services/assign.ts +++ b/src/addons/mod/assign/services/assign.ts @@ -164,7 +164,7 @@ export class AddonModAssignProvider { value: number, options: CoreSitesCommonWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModAssignGetAssignmentsWSParams = { courseids: [courseId], @@ -175,7 +175,7 @@ export class AddonModAssignProvider { cacheKey: this.getAssignmentCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModAssignProvider.COMPONENT, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; let response: AddonModAssignGetAssignmentsWSResponse; @@ -238,7 +238,7 @@ export class AddonModAssignProvider { return -1; } - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModAssignGetUserMappingsWSParams = { assignmentids: [assignId], @@ -248,7 +248,7 @@ export class AddonModAssignProvider { updateFrequency: CoreSite.FREQUENCY_OFTEN, component: AddonModAssignProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; const response = await site.read('mod_assign_get_user_mappings', params, preSets); @@ -285,7 +285,7 @@ export class AddonModAssignProvider { * @return Resolved with requested info when done. */ async getAssignmentGrades(assignId: number, options: CoreCourseCommonModWSOptions = {}): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModAssignGetGradesWSParams = { assignmentids: [assignId], @@ -294,7 +294,7 @@ export class AddonModAssignProvider { cacheKey: this.getAssignmentGradesCacheKey(assignId), component: AddonModAssignProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; const response = await site.read('mod_assign_get_grades', params, preSets); @@ -430,7 +430,7 @@ export class AddonModAssignProvider { }); if (!keepUrls && submissionPlugin.fileareas && submissionPlugin.fileareas[0]) { - text = CoreTextUtils.instance.replacePluginfileUrls(text, submissionPlugin.fileareas[0].files || []); + text = CoreTextUtils.replacePluginfileUrls(text, submissionPlugin.fileareas[0].files || []); } return text; @@ -447,7 +447,7 @@ export class AddonModAssignProvider { assignId: number, options: CoreCourseCommonModWSOptions = {}, ): Promise<{ canviewsubmissions: boolean; submissions?: AddonModAssignSubmission[] }> { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: ModAssignGetSubmissionsWSParams = { assignmentids: [assignId], @@ -457,7 +457,7 @@ export class AddonModAssignProvider { updateFrequency: CoreSite.FREQUENCY_OFTEN, component: AddonModAssignProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; const response = await site.read('mod_assign_get_submissions', params, preSets); @@ -497,7 +497,7 @@ export class AddonModAssignProvider { assignId: number, options: AddonModAssignSubmissionStatusOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); options = { filter: true, @@ -528,7 +528,7 @@ export class AddonModAssignProvider { // Don't cache when getting text without filters. // @todo Change this to support offline editing. saveToCache: options.filter, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; return site.read('mod_assign_get_submission_status', params, preSets); @@ -613,7 +613,7 @@ export class AddonModAssignProvider { async getUnsupportedEditPlugins(plugins: AddonModAssignPlugin[]): Promise { const notSupported: string[] = []; const promises = plugins.map((plugin) => - AddonModAssignSubmissionDelegate.instance.isPluginSupportedForEdit(plugin.type).then((enabled) => { + AddonModAssignSubmissionDelegate.isPluginSupportedForEdit(plugin.type).then((enabled) => { if (!enabled) { notSupported.push(plugin.name); } @@ -642,7 +642,7 @@ export class AddonModAssignProvider { groupId = groupId || 0; - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); if (!site.wsAvailable('mod_assign_list_participants')) { // Silently fail if is not available. (needs Moodle version >= 3.2) throw new CoreError('mod_assign_list_participants WS is only available 3.2 onwards'); @@ -659,7 +659,7 @@ export class AddonModAssignProvider { updateFrequency: CoreSite.FREQUENCY_OFTEN, component: AddonModAssignProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; return site.read('mod_assign_list_participants', params, preSets); @@ -694,7 +694,7 @@ export class AddonModAssignProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAllSubmissionData(assignId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getSubmissionsCacheKey(assignId)); } @@ -707,7 +707,7 @@ export class AddonModAssignProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAssignmentData(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAssignmentCacheKey(courseId)); } @@ -720,7 +720,7 @@ export class AddonModAssignProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAssignmentUserMappingsData(assignId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAssignmentUserMappingsCacheKey(assignId)); } @@ -733,7 +733,7 @@ export class AddonModAssignProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAssignmentGradesData(assignId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAssignmentGradesCacheKey(assignId)); } @@ -748,7 +748,7 @@ export class AddonModAssignProvider { * @return Promise resolved when the data is invalidated. */ async invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const assign = await this.getAssignment(courseId, moduleId, { siteId }); const promises: Promise[] = []; @@ -757,9 +757,9 @@ export class AddonModAssignProvider { promises.push(this.invalidateAssignmentUserMappingsData(assign.id, siteId)); promises.push(this.invalidateAssignmentGradesData(assign.id, siteId)); promises.push(this.invalidateListParticipantsData(assign.id, siteId)); - promises.push(CoreComments.instance.invalidateCommentsByInstance('module', assign.id, siteId)); + promises.push(CoreComments.invalidateCommentsByInstance('module', assign.id, siteId)); promises.push(this.invalidateAssignmentData(courseId, siteId)); - promises.push(CoreGrades.instance.invalidateAllCourseGradesData(courseId)); + promises.push(CoreGrades.invalidateAllCourseGradesData(courseId)); await Promise.all(promises); @@ -772,8 +772,8 @@ export class AddonModAssignProvider { * @return Promise resolved when the files are invalidated. */ async invalidateFiles(moduleId: number): Promise { - await CoreFilepool.instance.invalidateFilesByComponent( - CoreSites.instance.getCurrentSiteId(), + await CoreFilepool.invalidateFilesByComponent( + CoreSites.getCurrentSiteId(), AddonModAssignProvider.COMPONENT, moduleId, ); @@ -787,7 +787,7 @@ export class AddonModAssignProvider { * @return Promise resolved when the data is invalidated. */ async invalidateSubmissionData(assignId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getSubmissionsCacheKey(assignId)); } @@ -809,7 +809,7 @@ export class AddonModAssignProvider { isBlind = false, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const fixedParams = this.fixSubmissionStatusParams(site, userId, groupId, isBlind); await site.invalidateWsCacheForKey(this.getSubmissionStatusCacheKey( @@ -828,7 +828,7 @@ export class AddonModAssignProvider { * @return Promise resolved when the data is invalidated. */ async invalidateListParticipantsData(assignId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.listParticipantsPrefixCacheKey(assignId)); } @@ -840,13 +840,13 @@ export class AddonModAssignProvider { * @return Promise resolved with boolean: whether grading offline is enabled. */ protected async isGradingOfflineEnabled(siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (typeof this.gradingOfflineEnabled[siteId] != 'undefined') { return this.gradingOfflineEnabled[siteId]; } - this.gradingOfflineEnabled[siteId] = await CoreGrades.instance.isGradeItemsAvalaible(siteId); + this.gradingOfflineEnabled[siteId] = await CoreGrades.isGradeItemsAvalaible(siteId); return this.gradingOfflineEnabled[siteId]; } @@ -859,7 +859,7 @@ export class AddonModAssignProvider { * @since 3.2 */ async isOutcomesEditEnabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.wsAvailable('mod_assign_submit_grading_form'); } @@ -886,7 +886,7 @@ export class AddonModAssignProvider { return false; } - const time = CoreTimeUtils.instance.timestamp(); + const time = CoreTimeUtils.timestamp(); const lastAttempt = submissionStatus.lastattempt; const submission = this.getSubmissionObjectFromAttempt(assign, lastAttempt); @@ -944,7 +944,7 @@ export class AddonModAssignProvider { assignid, }; - await CoreCourseLogHelper.instance.logSingle( + await CoreCourseLogHelper.logSingle( 'mod_assign_view_submission_status', params, AddonModAssignProvider.COMPONENT, @@ -969,7 +969,7 @@ export class AddonModAssignProvider { assignid, }; - await CoreCourseLogHelper.instance.logSingle( + await CoreCourseLogHelper.logSingle( 'mod_assign_view_grading_table', params, AddonModAssignProvider.COMPONENT, @@ -994,7 +994,7 @@ export class AddonModAssignProvider { assignid, }; - await CoreCourseLogHelper.instance.logSingle( + await CoreCourseLogHelper.logSingle( 'mod_assign_view_assign', params, AddonModAssignProvider.COMPONENT, @@ -1063,11 +1063,11 @@ export class AddonModAssignProvider { siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Function to store the submission to be synchronized later. const storeOffline = async (): Promise => { - await AddonModAssignOffline.instance.saveSubmission( + await AddonModAssignOffline.saveSubmission( assignId, courseId, pluginData, @@ -1080,19 +1080,19 @@ export class AddonModAssignProvider { return false; }; - if (allowOffline && !CoreApp.instance.isOnline()) { + if (allowOffline && !CoreApp.isOnline()) { // App is offline, store the action. return storeOffline(); } try { // If there's already a submission to be sent to the server, discard it first. - await AddonModAssignOffline.instance.deleteSubmission(assignId, userId, siteId); + await AddonModAssignOffline.deleteSubmission(assignId, userId, siteId); await this.saveSubmissionOnline(assignId, pluginData, siteId); return true; } catch (error) { - if (allowOffline && error && !CoreUtils.instance.isWebServiceError(error)) { + if (allowOffline && error && !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server, store in offline. return storeOffline(); } else { @@ -1111,7 +1111,7 @@ export class AddonModAssignProvider { * @return Promise resolved when saved, rejected otherwise. */ async saveSubmissionOnline(assignId: number, pluginData: AddonModAssignSavePluginData, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModAssignSaveSubmissionWSParams = { assignmentid: assignId, plugindata: pluginData, @@ -1144,11 +1144,11 @@ export class AddonModAssignProvider { siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Function to store the submission to be synchronized later. const storeOffline = async (): Promise => { - await AddonModAssignOffline.instance.markSubmitted( + await AddonModAssignOffline.markSubmitted( assignId, courseId, true, @@ -1161,19 +1161,19 @@ export class AddonModAssignProvider { return false; }; - if (forceOffline || !CoreApp.instance.isOnline()) { + if (forceOffline || !CoreApp.isOnline()) { // App is offline, store the action. return storeOffline(); } try { // If there's already a submission to be sent to the server, discard it first. - await AddonModAssignOffline.instance.deleteSubmission(assignId, undefined, siteId); + await AddonModAssignOffline.deleteSubmission(assignId, undefined, siteId); await this.submitForGradingOnline(assignId, acceptStatement, siteId); return true; } catch (error) { - if (error && !CoreUtils.instance.isWebServiceError(error)) { + if (error && !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server, store in offline. return storeOffline(); } else { @@ -1192,7 +1192,7 @@ export class AddonModAssignProvider { * @return Promise resolved when submitted, rejected otherwise. */ async submitForGradingOnline(assignId: number, acceptStatement: boolean, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModAssignSubmitForGradingWSParams = { assignmentid: assignId, @@ -1237,11 +1237,11 @@ export class AddonModAssignProvider { siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Function to store the grading to be synchronized later. const storeOffline = async (): Promise => { - await AddonModAssignOffline.instance.submitGradingForm( + await AddonModAssignOffline.submitGradingForm( assignId, userId, courseId, @@ -1277,14 +1277,14 @@ export class AddonModAssignProvider { return true; } - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // App is offline, store the action. return storeOffline(); } try { // If there's already a grade to be sent to the server, discard it first. - await AddonModAssignOffline.instance.deleteSubmissionGrade(assignId, userId, siteId); + await AddonModAssignOffline.deleteSubmissionGrade(assignId, userId, siteId); await this.submitGradingFormOnline( assignId, userId, @@ -1300,7 +1300,7 @@ export class AddonModAssignProvider { return true; } catch (error) { - if (error && !CoreUtils.instance.isWebServiceError(error)) { + if (error && !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server, store in offline. return storeOffline(); } else { @@ -1339,7 +1339,7 @@ export class AddonModAssignProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); if (site.wsAvailable('mod_assign_submit_grading_form')) { diff --git a/src/addons/mod/assign/services/handlers/default-feedback.ts b/src/addons/mod/assign/services/handlers/default-feedback.ts index de0cdd3f3..62c394bdb 100644 --- a/src/addons/mod/assign/services/handlers/default-feedback.ts +++ b/src/addons/mod/assign/services/handlers/default-feedback.ts @@ -65,7 +65,7 @@ export class AddonModAssignDefaultFeedbackHandler implements AddonModAssignFeedb getPluginName(plugin: AddonModAssignPlugin): string { // Check if there's a translated string for the plugin. const translationId = 'addon.mod_assign_feedback_' + plugin.type + '.pluginname'; - const translation = Translate.instance.instant(translationId); + const translation = Translate.instant(translationId); if (translationId != translation) { // Translation found, use it. diff --git a/src/addons/mod/assign/services/handlers/default-submission.ts b/src/addons/mod/assign/services/handlers/default-submission.ts index 55e838efc..db3791205 100644 --- a/src/addons/mod/assign/services/handlers/default-submission.ts +++ b/src/addons/mod/assign/services/handlers/default-submission.ts @@ -92,7 +92,7 @@ export class AddonModAssignDefaultSubmissionHandler implements AddonModAssignSub getPluginName(plugin: AddonModAssignPlugin): string { // Check if there's a translated string for the plugin. const translationId = 'addon.mod_assign_submission_' + plugin.type + '.pluginname'; - const translation = Translate.instance.instant(translationId); + const translation = Translate.instant(translationId); if (translationId != translation) { // Translation found, use it. diff --git a/src/addons/mod/assign/services/handlers/module.ts b/src/addons/mod/assign/services/handlers/module.ts index bd74d4468..8ef54dc73 100644 --- a/src/addons/mod/assign/services/handlers/module.ts +++ b/src/addons/mod/assign/services/handlers/module.ts @@ -54,7 +54,7 @@ export class AddonModAssignModuleHandlerService implements CoreCourseModuleHandl * @return Whether or not the handler is enabled on a site level. */ async isEnabled(): Promise { - return AddonModAssign.instance.isPluginEnabled(); + return AddonModAssign.isPluginEnabled(); } /** @@ -65,7 +65,7 @@ export class AddonModAssignModuleHandlerService implements CoreCourseModuleHandl */ getData(module: CoreCourseAnyModuleData): CoreCourseModuleHandlerData { return { - icon: CoreCourse.instance.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), + icon: CoreCourse.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), title: module.name, class: 'addon-mod_assign-handler', showDownloadButton: true, @@ -75,7 +75,7 @@ export class AddonModAssignModuleHandlerService implements CoreCourseModuleHandl Object.assign(options.params, { module }); const routeParams = '/' + courseId + '/' + module.id; - CoreNavigator.instance.navigateToSitePath(AddonModAssignModuleHandlerService.PAGE_NAME + routeParams, options); + CoreNavigator.navigateToSitePath(AddonModAssignModuleHandlerService.PAGE_NAME + routeParams, options); }, }; } diff --git a/src/addons/mod/assign/services/handlers/prefetch.ts b/src/addons/mod/assign/services/handlers/prefetch.ts index 966e7e842..f2f092d28 100644 --- a/src/addons/mod/assign/services/handlers/prefetch.ts +++ b/src/addons/mod/assign/services/handlers/prefetch.ts @@ -59,15 +59,15 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref async canUseCheckUpdates(module: CoreCourseAnyModuleData, courseId: number): Promise { // Teachers cannot use the WS because it doesn't check student submissions. try { - const assign = await AddonModAssign.instance.getAssignment(courseId, module.id); + const assign = await AddonModAssign.getAssignment(courseId, module.id); - const data = await AddonModAssign.instance.getSubmissions(assign.id, { cmId: module.id }); + const data = await AddonModAssign.getSubmissions(assign.id, { cmId: module.id }); if (data.canviewsubmissions) { return false; } // Check if the user can view their own submission. - await AddonModAssign.instance.getSubmissionStatus(assign.id, { cmId: module.id }); + await AddonModAssign.getSubmissionStatus(assign.id, { cmId: module.id }); return true; } catch { @@ -83,21 +83,21 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref * @return Promise resolved with the list of files. */ async getFiles(module: CoreCourseAnyModuleData, courseId: number): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); try { - const assign = await AddonModAssign.instance.getAssignment(courseId, module.id, { siteId }); + const assign = await AddonModAssign.getAssignment(courseId, module.id, { siteId }); // Get intro files and attachments. let files = assign.introattachments || []; files = files.concat(this.getIntroFilesFromInstance(module, assign)); // Now get the files in the submissions. - const submissionData = await AddonModAssign.instance.getSubmissions(assign.id, { cmId: module.id, siteId }); + const submissionData = await AddonModAssign.getSubmissions(assign.id, { cmId: module.id, siteId }); if (submissionData.canviewsubmissions) { // Teacher, get all submissions. const submissions = - await AddonModAssignHelper.instance.getSubmissionsUserData(assign, submissionData.submissions, 0, { siteId }); + await AddonModAssignHelper.getSubmissionsUserData(assign, submissionData.submissions, 0, { siteId }); // Get all the files in the submissions. const promises = submissions.map((submission) => @@ -117,7 +117,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref await Promise.all(promises); } else { // Student, get only his/her submissions. - const userId = CoreSites.instance.getCurrentSiteUserId(); + const userId = CoreSites.getCurrentSiteUserId(); const blindMarking = !!assign.blindmarking && !assign.revealidentities; const submissionFiles = await this.getSubmissionFiles(assign, userId, blindMarking, siteId); @@ -147,12 +147,12 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref siteId?: string, ): Promise { - const submissionStatus = await AddonModAssign.instance.getSubmissionStatusWithRetry(assign, { + const submissionStatus = await AddonModAssign.getSubmissionStatusWithRetry(assign, { userId: submitId, isBlind: blindMarking, siteId, }); - const userSubmission = AddonModAssign.instance.getSubmissionObjectFromAttempt(assign, submissionStatus.lastattempt); + const userSubmission = AddonModAssign.getSubmissionObjectFromAttempt(assign, submissionStatus.lastattempt); if (!submissionStatus.lastattempt || !userSubmission) { return []; @@ -163,14 +163,14 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref if (userSubmission.plugins) { // Add submission plugin files. userSubmission.plugins.forEach((plugin) => { - promises.push(AddonModAssignSubmissionDelegate.instance.getPluginFiles(assign, userSubmission, plugin, siteId)); + promises.push(AddonModAssignSubmissionDelegate.getPluginFiles(assign, userSubmission, plugin, siteId)); }); } if (submissionStatus.feedback && submissionStatus.feedback.plugins) { // Add feedback plugin files. submissionStatus.feedback.plugins.forEach((plugin) => { - promises.push(AddonModAssignFeedbackDelegate.instance.getPluginFiles(assign, userSubmission, plugin, siteId)); + promises.push(AddonModAssignFeedbackDelegate.getPluginFiles(assign, userSubmission, plugin, siteId)); }); } @@ -187,7 +187,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref * @return Promise resolved when the data is invalidated. */ async invalidateContent(moduleId: number, courseId: number): Promise { - await AddonModAssign.instance.invalidateContent(moduleId, courseId); + await AddonModAssign.invalidateContent(moduleId, courseId); } /** @@ -198,7 +198,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref * @return Promise resolved when invalidated. */ async invalidateModule(module: CoreCourseAnyModuleData): Promise { - return CoreCourse.instance.invalidateModule(module.id); + return CoreCourse.invalidateModule(module.id); } /** @@ -207,7 +207,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref * @return A boolean, or a promise resolved with a boolean, indicating if the handler is enabled. */ async isEnabled(): Promise { - return AddonModAssign.instance.isPluginEnabled(); + return AddonModAssign.isPluginEnabled(); } /** @@ -229,9 +229,9 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref * @return Promise resolved when done. */ protected async prefetchAssign(module: CoreCourseAnyModuleData, courseId?: number): Promise { - const userId = CoreSites.instance.getCurrentSiteUserId(); - courseId = courseId || module.course || CoreSites.instance.getCurrentSiteHomeId(); - const siteId = CoreSites.instance.getCurrentSiteId(); + const userId = CoreSites.getCurrentSiteUserId(); + courseId = courseId || module.course || CoreSites.getCurrentSiteHomeId(); + const siteId = CoreSites.getCurrentSiteId(); const options: CoreSitesCommonWSOptions = { readingStrategy: CoreSitesReadingStrategy.OnlyNetwork, @@ -244,25 +244,25 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref }; // Get assignment to retrieve all its submissions. - const assign = await AddonModAssign.instance.getAssignment(courseId, module.id, options); + const assign = await AddonModAssign.getAssignment(courseId, module.id, options); const promises: Promise[] = []; const blindMarking = assign.blindmarking && !assign.revealidentities; if (blindMarking) { promises.push( - CoreUtils.instance.ignoreErrors(AddonModAssign.instance.getAssignmentUserMappings(assign.id, -1, modOptions)), + CoreUtils.ignoreErrors(AddonModAssign.getAssignmentUserMappings(assign.id, -1, modOptions)), ); } promises.push(this.prefetchSubmissions(assign, courseId, module.id, userId, siteId)); - promises.push(CoreCourseHelper.instance.getModuleCourseIdByInstance(assign.id, 'assign', siteId)); + promises.push(CoreCourseHelper.getModuleCourseIdByInstance(assign.id, 'assign', siteId)); // Download intro files and attachments. Do not call getFiles because it'd call some WS twice. let files = assign.introattachments || []; files = files.concat(this.getIntroFilesFromInstance(module, assign)); - promises.push(CoreFilepool.instance.addFilesToQueue(siteId, files, this.component, module.id)); + promises.push(CoreFilepool.addFilesToQueue(siteId, files, this.component, module.id)); await Promise.all(promises); @@ -292,7 +292,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref }; // Get submissions. - const submissions = await AddonModAssign.instance.getSubmissions(assign.id, modOptions); + const submissions = await AddonModAssign.getSubmissions(assign.id, modOptions); const promises: Promise[] = []; promises.push(this.prefetchParticipantSubmissions( @@ -344,7 +344,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref }; // Always prefetch groupInfo. - const groupInfo = await CoreGroups.instance.getActivityGroupInfo(assign.cmid, false, undefined, siteId); + const groupInfo = await CoreGroups.getActivityGroupInfo(assign.cmid, false, undefined, siteId); if (!canviewsubmissions) { return; @@ -356,7 +356,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref } const promises = groupInfo.groups.map((group) => - AddonModAssignHelper.instance.getSubmissionsUserData(assign, submissions, group.id, options) + AddonModAssignHelper.getSubmissionsUserData(assign, submissions, group.id, options) .then((submissions: AddonModAssignSubmissionFormatted[]) => { const subPromises: Promise[] = submissions.map((submission) => { @@ -373,7 +373,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref if (!assign.markingworkflow) { // Get assignment grades only if workflow is not enabled to check grading date. - subPromises.push(AddonModAssign.instance.getAssignmentGrades(assign.id, modOptions)); + subPromises.push(AddonModAssign.getAssignmentGrades(assign.id, modOptions)); } // Prefetch the submission of the current user even if it does not exist, this will be create it. @@ -391,11 +391,11 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref return Promise.all(subPromises); }).then(async () => { // Participiants already fetched, we don't need to ignore cache now. - const participants = await AddonModAssignHelper.instance.getParticipants(assign, group.id, { siteId }); + const participants = await AddonModAssignHelper.getParticipants(assign, group.id, { siteId }); // Fail silently (Moodle < 3.2). - await CoreUtils.instance.ignoreErrors( - CoreUser.instance.prefetchUserAvatars(participants, 'profileimageurl', siteId), + await CoreUtils.ignoreErrors( + CoreUser.prefetchUserAvatars(participants, 'profileimageurl', siteId), ); return; @@ -421,7 +421,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref options: AddonModAssignSubmissionStatusOptions = {}, resolveOnNoPermission = false, ): Promise { - const submission = await AddonModAssign.instance.getSubmissionStatusWithRetry(assign, options); + const submission = await AddonModAssign.getSubmissionStatusWithRetry(assign, options); const siteId = options.siteId!; const userId = options.userId; @@ -429,7 +429,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref const promises: Promise[] = []; const blindMarking = !!assign.blindmarking && !assign.revealidentities; let userIds: number[] = []; - const userSubmission = AddonModAssign.instance.getSubmissionObjectFromAttempt(assign, submission.lastattempt); + const userSubmission = AddonModAssign.getSubmissionObjectFromAttempt(assign, submission.lastattempt); if (submission.lastattempt) { // Get IDs of the members who need to submit. @@ -443,14 +443,14 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref userSubmission.plugins.forEach((plugin) => { // Prefetch the plugin WS data. promises.push( - AddonModAssignSubmissionDelegate.instance.prefetch(assign, userSubmission, plugin, siteId), + AddonModAssignSubmissionDelegate.prefetch(assign, userSubmission, plugin, siteId), ); // Prefetch the plugin files. promises.push( - AddonModAssignSubmissionDelegate.instance.getPluginFiles(assign, userSubmission, plugin, siteId) + AddonModAssignSubmissionDelegate.getPluginFiles(assign, userSubmission, plugin, siteId) .then((files) => - CoreFilepool.instance.addFilesToQueue(siteId, files, this.component, module.id)) + CoreFilepool.addFilesToQueue(siteId, files, this.component, module.id)) .catch(() => { // Ignore errors. }), @@ -467,10 +467,10 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref // Prefetch grade items. if (userId) { - promises.push(CoreCourse.instance.getModuleBasicGradeInfo(moduleId, siteId).then((gradeInfo) => { + promises.push(CoreCourse.getModuleBasicGradeInfo(moduleId, siteId).then((gradeInfo) => { if (gradeInfo) { promises.push( - CoreGradesHelper.instance.getGradeModuleItems(courseId, moduleId, userId, undefined, siteId, true), + CoreGradesHelper.getGradeModuleItems(courseId, moduleId, userId, undefined, siteId, true), ); } @@ -489,12 +489,12 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref if (submission.feedback.plugins && userSubmission && userSubmission.id) { submission.feedback.plugins.forEach((plugin) => { // Prefetch the plugin WS data. - promises.push(AddonModAssignFeedbackDelegate.instance.prefetch(assign, userSubmission, plugin, siteId)); + promises.push(AddonModAssignFeedbackDelegate.prefetch(assign, userSubmission, plugin, siteId)); // Prefetch the plugin files. promises.push( - AddonModAssignFeedbackDelegate.instance.getPluginFiles(assign, userSubmission, plugin, siteId) - .then((files) => CoreFilepool.instance.addFilesToQueue(siteId, files, this.component, module.id)) + AddonModAssignFeedbackDelegate.getPluginFiles(assign, userSubmission, plugin, siteId) + .then((files) => CoreFilepool.addFilesToQueue(siteId, files, this.component, module.id)) .catch(() => { // Ignore errors. }), @@ -504,7 +504,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref } // Prefetch user profiles. - promises.push(CoreUser.instance.prefetchProfiles(userIds, courseId, siteId)); + promises.push(CoreUser.prefetchProfiles(userIds, courseId, siteId)); await Promise.all(promises); } catch (error) { @@ -524,7 +524,7 @@ export class AddonModAssignPrefetchHandlerService extends CoreCourseActivityPref * @return Promise resolved when done. */ sync(module: CoreCourseAnyModuleData, courseId: number, siteId?: string): Promise { - return AddonModAssignSync.instance.syncAssign(module.instance!, siteId); + return AddonModAssignSync.syncAssign(module.instance!, siteId); } } diff --git a/src/addons/mod/assign/services/handlers/push-click.ts b/src/addons/mod/assign/services/handlers/push-click.ts index 57a0e49b1..1973435e2 100644 --- a/src/addons/mod/assign/services/handlers/push-click.ts +++ b/src/addons/mod/assign/services/handlers/push-click.ts @@ -38,7 +38,7 @@ export class AddonModAssignPushClickHandlerService implements CorePushNotificati * @return Whether the notification click is handled by this handler */ async handles(notification: NotificationData): Promise { - return CoreUtils.instance.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'mod_assign' && + return CoreUtils.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'mod_assign' && notification.name == 'assign_notification'; } @@ -49,12 +49,12 @@ export class AddonModAssignPushClickHandlerService implements CorePushNotificati * @return Promise resolved when done. */ async handleClick(notification: NotificationData): Promise { - const contextUrlParams = CoreUrlUtils.instance.extractUrlParams(notification.contexturl); + const contextUrlParams = CoreUrlUtils.extractUrlParams(notification.contexturl); const courseId = Number(notification.courseid); const moduleId = Number(contextUrlParams.id); - await CoreUtils.instance.ignoreErrors(AddonModAssign.instance.invalidateContent(moduleId, courseId, notification.site)); - await CoreCourseHelper.instance.navigateToModule(moduleId, notification.site, courseId); + await CoreUtils.ignoreErrors(AddonModAssign.invalidateContent(moduleId, courseId, notification.site)); + await CoreCourseHelper.navigateToModule(moduleId, notification.site, courseId); } } diff --git a/src/addons/mod/assign/services/handlers/sync-cron.ts b/src/addons/mod/assign/services/handlers/sync-cron.ts index b0092185f..cdda6e33b 100644 --- a/src/addons/mod/assign/services/handlers/sync-cron.ts +++ b/src/addons/mod/assign/services/handlers/sync-cron.ts @@ -34,7 +34,7 @@ export class AddonModAssignSyncCronHandlerService implements CoreCronHandler { * @return Promise resolved when done, rejected if failure. */ execute(siteId?: string, force?: boolean): Promise { - return AddonModAssignSync.instance.syncAllAssignments(siteId, force); + return AddonModAssignSync.syncAllAssignments(siteId, force); } /** @@ -43,7 +43,7 @@ export class AddonModAssignSyncCronHandlerService implements CoreCronHandler { * @return Time between consecutive executions (in ms). */ getInterval(): number { - return AddonModAssignSync.instance.syncInterval; + return AddonModAssignSync.syncInterval; } } diff --git a/src/addons/mod/assign/submission/comments/comments.module.ts b/src/addons/mod/assign/submission/comments/comments.module.ts index 91faee3aa..4dfc1d641 100644 --- a/src/addons/mod/assign/submission/comments/comments.module.ts +++ b/src/addons/mod/assign/submission/comments/comments.module.ts @@ -33,7 +33,7 @@ import { CoreCommentsComponentsModule } from '@features/comments/components/comp multi: true, deps: [], useFactory: () => () => { - AddonModAssignSubmissionDelegate.instance.registerHandler(AddonModAssignSubmissionCommentsHandler.instance); + AddonModAssignSubmissionDelegate.registerHandler(AddonModAssignSubmissionCommentsHandler.instance); }, }, ], diff --git a/src/addons/mod/assign/submission/comments/component/comments.ts b/src/addons/mod/assign/submission/comments/component/comments.ts index 38bf30cc0..13cfd965d 100644 --- a/src/addons/mod/assign/submission/comments/component/comments.ts +++ b/src/addons/mod/assign/submission/comments/component/comments.ts @@ -33,7 +33,7 @@ export class AddonModAssignSubmissionCommentsComponent extends AddonModAssignSub constructor() { super(); - this.commentsEnabled = !CoreComments.instance.areCommentsDisabledInSite(); + this.commentsEnabled = !CoreComments.areCommentsDisabledInSite(); } /** @@ -42,7 +42,7 @@ export class AddonModAssignSubmissionCommentsComponent extends AddonModAssignSub * @return Promise resolved when done. */ invalidate(): Promise { - return CoreComments.instance.invalidateCommentsData( + return CoreComments.invalidateCommentsData( 'module', this.assign.cmid, 'assignsubmission_comments', diff --git a/src/addons/mod/assign/submission/comments/services/handler.ts b/src/addons/mod/assign/submission/comments/services/handler.ts index b32bd290d..25f409c03 100644 --- a/src/addons/mod/assign/submission/comments/services/handler.ts +++ b/src/addons/mod/assign/submission/comments/services/handler.ts @@ -90,8 +90,8 @@ export class AddonModAssignSubmissionCommentsHandlerService implements AddonModA ): Promise { // Fail silently (Moodle < 3.1.1, 3.2) - await CoreUtils.instance.ignoreErrors( - CoreComments.instance.getComments( + await CoreUtils.ignoreErrors( + CoreComments.getComments( 'module', assign.cmid, 'assignsubmission_comments', diff --git a/src/addons/mod/assign/submission/file/component/file.ts b/src/addons/mod/assign/submission/file/component/file.ts index c6e545e11..e7e2fb471 100644 --- a/src/addons/mod/assign/submission/file/component/file.ts +++ b/src/addons/mod/assign/submission/file/component/file.ts @@ -43,8 +43,8 @@ export class AddonModAssignSubmissionFileComponent extends AddonModAssignSubmiss */ async ngOnInit(): Promise { // Get the offline data. - const filesData = await CoreUtils.instance.ignoreErrors( - AddonModAssignOffline.instance.getSubmission(this.assign.id), + const filesData = await CoreUtils.ignoreErrors( + AddonModAssignOffline.getSubmission(this.assign.id), undefined, ); @@ -62,8 +62,8 @@ export class AddonModAssignSubmissionFileComponent extends AddonModAssignSubmiss // It has offline data. let offlineFiles: FileEntry[] = []; if (offlineDataFiles.offline) { - offlineFiles = await CoreUtils.instance.ignoreErrors( - AddonModAssignHelper.instance.getStoredSubmissionFiles( + offlineFiles = await CoreUtils.ignoreErrors( + AddonModAssignHelper.getStoredSubmissionFiles( this.assign.id, AddonModAssignSubmissionFileHandlerService.FOLDER_NAME, ), @@ -75,10 +75,10 @@ export class AddonModAssignSubmissionFileComponent extends AddonModAssignSubmiss this.files = this.files.concat(offlineFiles); } else { // No offline data, get the online files. - this.files = AddonModAssign.instance.getSubmissionPluginAttachments(this.plugin); + this.files = AddonModAssign.getSubmissionPluginAttachments(this.plugin); } } finally { - CoreFileSession.instance.setFiles(this.component, this.assign.id, this.files); + CoreFileSession.setFiles(this.component, this.assign.id, this.files); } } diff --git a/src/addons/mod/assign/submission/file/file.module.ts b/src/addons/mod/assign/submission/file/file.module.ts index be02d065a..1c4f1f238 100644 --- a/src/addons/mod/assign/submission/file/file.module.ts +++ b/src/addons/mod/assign/submission/file/file.module.ts @@ -31,7 +31,7 @@ import { AddonModAssignSubmissionDelegate } from '../../services/submission-dele multi: true, deps: [], useFactory: () => () => { - AddonModAssignSubmissionDelegate.instance.registerHandler(AddonModAssignSubmissionFileHandler.instance); + AddonModAssignSubmissionDelegate.registerHandler(AddonModAssignSubmissionFileHandler.instance); }, }, ], diff --git a/src/addons/mod/assign/submission/file/services/handler.ts b/src/addons/mod/assign/submission/file/services/handler.ts index 344b8cc3a..00333791c 100644 --- a/src/addons/mod/assign/submission/file/services/handler.ts +++ b/src/addons/mod/assign/submission/file/services/handler.ts @@ -63,7 +63,7 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig * @return Whether the plugin is empty. */ isEmpty(assign: AddonModAssignAssign, plugin: AddonModAssignPlugin): boolean { - const files = AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + const files = AddonModAssign.getSubmissionPluginAttachments(plugin); return files.length === 0; } @@ -74,13 +74,13 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig * @param assign The assignment. */ clearTmpData(assign: AddonModAssignAssign): void { - const files = CoreFileSession.instance.getFiles(AddonModAssignProvider.COMPONENT, assign.id); + const files = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id); // Clear the files in session for this assign. - CoreFileSession.instance.clearFiles(AddonModAssignProvider.COMPONENT, assign.id); + CoreFileSession.clearFiles(AddonModAssignProvider.COMPONENT, assign.id); // Now delete the local files from the tmp folder. - CoreFileUploader.instance.clearTmpFiles(files); + CoreFileUploader.clearTmpFiles(files); } /** @@ -98,10 +98,10 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig pluginData: AddonModAssignSubmissionFilePluginData, ): Promise { // We need to re-upload all the existing files. - const files = AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + const files = AddonModAssign.getSubmissionPluginAttachments(plugin); // Get the itemId. - pluginData.files_filemanager = await AddonModAssignHelper.instance.uploadFiles(assign.id, files); + pluginData.files_filemanager = await AddonModAssignHelper.uploadFiles(assign.id, files); } /** @@ -132,8 +132,8 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig siteId?: string, ): Promise { - await CoreUtils.instance.ignoreErrors( - AddonModAssignHelper.instance.deleteStoredSubmissionFiles( + await CoreUtils.ignoreErrors( + AddonModAssignHelper.deleteStoredSubmissionFiles( assign.id, AddonModAssignSubmissionFileHandlerService.FOLDER_NAME, submission.userid, @@ -157,7 +157,7 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig submission: AddonModAssignSubmission, plugin: AddonModAssignPlugin, ): CoreWSExternalFile[] { - return AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + return AddonModAssign.getSubmissionPluginAttachments(plugin); } /** @@ -168,9 +168,9 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig * @return The size (or promise resolved with size). */ async getSizeForCopy(assign: AddonModAssignAssign, plugin: AddonModAssignPlugin): Promise { - const files = AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + const files = AddonModAssign.getSubmissionPluginAttachments(plugin); - return CoreFileHelper.instance.getTotalFilesSize(files); + return CoreFileHelper.getTotalFilesSize(files); } /** @@ -188,9 +188,9 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig ): Promise { // Check if there's any change. if (this.hasDataChanged(assign, submission, plugin)) { - const files = CoreFileSession.instance.getFiles(AddonModAssignProvider.COMPONENT, assign.id); + const files = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id); - return CoreFileHelper.instance.getTotalFilesSize(files); + return CoreFileHelper.getTotalFilesSize(files); } else { // Nothing has changed, we won't upload any file. return 0; @@ -210,9 +210,9 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig submission: AddonModAssignSubmission, plugin: AddonModAssignPlugin, ): Promise { - const offlineData = await CoreUtils.instance.ignoreErrors( + const offlineData = await CoreUtils.ignoreErrors( // Check if there's any offline data. - AddonModAssignOffline.instance.getSubmission(assign.id, submission.userid), + AddonModAssignOffline.getSubmission(assign.id, submission.userid), undefined, ); @@ -223,12 +223,12 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig numFiles = offlineDataFiles.offline + offlineDataFiles.online.length; } else { // No offline data, return the number of online files. - const pluginFiles = AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + const pluginFiles = AddonModAssign.getSubmissionPluginAttachments(plugin); numFiles = pluginFiles && pluginFiles.length; } - const currentFiles = CoreFileSession.instance.getFiles(AddonModAssignProvider.COMPONENT, assign.id); + const currentFiles = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id); if (currentFiles.length != numFiles) { // Number of files has changed. @@ -238,7 +238,7 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig const files = await this.getSubmissionFilesToSync(assign, submission, offlineData); // Check if there is any local file added and list has changed. - return CoreFileUploader.instance.areFileListDifferent(currentFiles, files); + return CoreFileUploader.areFileListDifferent(currentFiles, files); } /** @@ -289,14 +289,14 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig } // Data has changed, we need to upload new files and re-upload all the existing files. - const currentFiles = CoreFileSession.instance.getFiles(AddonModAssignProvider.COMPONENT, assign.id); - const error = CoreUtils.instance.hasRepeatedFilenames(currentFiles); + const currentFiles = CoreFileSession.getFiles(AddonModAssignProvider.COMPONENT, assign.id); + const error = CoreUtils.hasRepeatedFilenames(currentFiles); if (error) { throw error; } - pluginData.files_filemanager = await AddonModAssignHelper.instance.uploadOrStoreFiles( + pluginData.files_filemanager = await AddonModAssignHelper.uploadOrStoreFiles( assign.id, AddonModAssignSubmissionFileHandlerService.FOLDER_NAME, currentFiles, @@ -333,7 +333,7 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig return; } - pluginData.files_filemanager = await AddonModAssignHelper.instance.uploadFiles(assign.id, files, siteId); + pluginData.files_filemanager = await AddonModAssignHelper.uploadFiles(assign.id, files, siteId); } /** @@ -361,8 +361,8 @@ export class AddonModAssignSubmissionFileHandlerService implements AddonModAssig if (filesData.offline) { // Has offline files, get them and add them to the list. - const storedFiles = await CoreUtils.instance.ignoreErrors( - AddonModAssignHelper.instance.getStoredSubmissionFiles( + const storedFiles = await CoreUtils.ignoreErrors( + AddonModAssignHelper.getStoredSubmissionFiles( assign.id, AddonModAssignSubmissionFileHandlerService.FOLDER_NAME, submission.userid, diff --git a/src/addons/mod/assign/submission/onlinetext/component/onlinetext.ts b/src/addons/mod/assign/submission/onlinetext/component/onlinetext.ts index 0a152e314..ac1b381ec 100644 --- a/src/addons/mod/assign/submission/onlinetext/component/onlinetext.ts +++ b/src/addons/mod/assign/submission/onlinetext/component/onlinetext.ts @@ -50,7 +50,7 @@ export class AddonModAssignSubmissionOnlineTextComponent extends AddonModAssignS ) { super(); this.element = element.nativeElement; - this.currentUserId = CoreSites.instance.getCurrentSiteUserId(); + this.currentUserId = CoreSites.getCurrentSiteUserId(); } /** @@ -58,8 +58,8 @@ export class AddonModAssignSubmissionOnlineTextComponent extends AddonModAssignS */ async ngOnInit(): Promise { // Get the text. Check if we have anything offline. - const offlineData = await CoreUtils.instance.ignoreErrors( - AddonModAssignOffline.instance.getSubmission(this.assign.id), + const offlineData = await CoreUtils.ignoreErrors( + AddonModAssignOffline.getSubmission(this.assign.id), undefined, ); @@ -71,7 +71,7 @@ export class AddonModAssignSubmissionOnlineTextComponent extends AddonModAssignS this.text = (offlineData.plugindata).onlinetext_editor.text; } else { // No offline data found, return online text. - this.text = AddonModAssign.instance.getSubmissionPluginText(this.plugin); + this.text = AddonModAssign.getSubmissionPluginText(this.plugin); } @@ -84,7 +84,7 @@ export class AddonModAssignSubmissionOnlineTextComponent extends AddonModAssignS if (this.text) { // Open a new state with the interpolated contents. - CoreTextUtils.instance.viewText(this.plugin.name, this.text, { + CoreTextUtils.viewText(this.plugin.name, this.text, { component: this.component, componentId: this.assign.cmid, filter: true, @@ -101,7 +101,7 @@ export class AddonModAssignSubmissionOnlineTextComponent extends AddonModAssignS // Calculate initial words. if (this.wordLimitEnabled) { - this.words = CoreTextUtils.instance.countWords(this.text); + this.words = CoreTextUtils.countWords(this.text); } } finally { this.loaded = true; @@ -122,7 +122,7 @@ export class AddonModAssignSubmissionOnlineTextComponent extends AddonModAssignS // Wait before calculating, if the user keeps inputing we won't calculate. // This is to prevent slowing down devices, this calculation can be slow if the text is long. this.wordCountTimeout = window.setTimeout(() => { - this.words = CoreTextUtils.instance.countWords(text); + this.words = CoreTextUtils.countWords(text); }, 1500); } } diff --git a/src/addons/mod/assign/submission/onlinetext/onlinetext.module.ts b/src/addons/mod/assign/submission/onlinetext/onlinetext.module.ts index 77a69e767..cda9519cb 100644 --- a/src/addons/mod/assign/submission/onlinetext/onlinetext.module.ts +++ b/src/addons/mod/assign/submission/onlinetext/onlinetext.module.ts @@ -33,7 +33,7 @@ import { AddonModAssignSubmissionDelegate } from '../../services/submission-dele multi: true, deps: [], useFactory: () => () => { - AddonModAssignSubmissionDelegate.instance.registerHandler(AddonModAssignSubmissionOnlineTextHandler.instance); + AddonModAssignSubmissionDelegate.registerHandler(AddonModAssignSubmissionOnlineTextHandler.instance); }, }, ], diff --git a/src/addons/mod/assign/submission/onlinetext/services/handler.ts b/src/addons/mod/assign/submission/onlinetext/services/handler.ts index 97696f2d5..36e4c04c5 100644 --- a/src/addons/mod/assign/submission/onlinetext/services/handler.ts +++ b/src/addons/mod/assign/submission/onlinetext/services/handler.ts @@ -60,7 +60,7 @@ export class AddonModAssignSubmissionOnlineTextHandlerService implements AddonMo * @return Whether the plugin is empty. */ isEmpty(assign: AddonModAssignAssign, plugin: AddonModAssignPlugin): boolean { - const text = AddonModAssign.instance.getSubmissionPluginText(plugin, true); + const text = AddonModAssign.getSubmissionPluginText(plugin, true); // If the text is empty, we can ignore files because they won't be visible anyways. return text.trim().length === 0; @@ -85,13 +85,13 @@ export class AddonModAssignSubmissionOnlineTextHandlerService implements AddonMo siteId?: string, ): Promise { - const text = AddonModAssign.instance.getSubmissionPluginText(plugin, true); - const files = AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + const text = AddonModAssign.getSubmissionPluginText(plugin, true); + const files = AddonModAssign.getSubmissionPluginAttachments(plugin); let itemId = 0; if (files.length) { // Re-upload the files. - itemId = await AddonModAssignHelper.instance.uploadFiles(assign.id, files, siteId); + itemId = await AddonModAssignHelper.uploadFiles(assign.id, files, siteId); } pluginData.onlinetext_editor = { @@ -125,7 +125,7 @@ export class AddonModAssignSubmissionOnlineTextHandlerService implements AddonMo submission: AddonModAssignSubmission, plugin: AddonModAssignPlugin, ): CoreWSExternalFile[] { - return AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + return AddonModAssign.getSubmissionPluginAttachments(plugin); } /** @@ -136,10 +136,10 @@ export class AddonModAssignSubmissionOnlineTextHandlerService implements AddonMo * @return The size (or promise resolved with size). */ async getSizeForCopy(assign: AddonModAssignAssign, plugin: AddonModAssignPlugin): Promise { - const text = AddonModAssign.instance.getSubmissionPluginText(plugin, true); - const files = AddonModAssign.instance.getSubmissionPluginAttachments(plugin); + const text = AddonModAssign.getSubmissionPluginText(plugin, true); + const files = AddonModAssign.getSubmissionPluginAttachments(plugin); - const filesSize = await CoreFileHelper.instance.getTotalFilesSize(files); + const filesSize = await CoreFileHelper.getTotalFilesSize(files); return text.length + filesSize; } @@ -158,7 +158,7 @@ export class AddonModAssignSubmissionOnlineTextHandlerService implements AddonMo submission: AddonModAssignSubmission, plugin: AddonModAssignPlugin, ): number { - const text = AddonModAssign.instance.getSubmissionPluginText(plugin, true); + const text = AddonModAssign.getSubmissionPluginText(plugin, true); return text.length; } @@ -174,7 +174,7 @@ export class AddonModAssignSubmissionOnlineTextHandlerService implements AddonMo const text = inputData.onlinetext_editor_text; const files = plugin.fileareas && plugin.fileareas[0] && plugin.fileareas[0].files || []; - return CoreTextUtils.instance.restorePluginfileUrls(text, files || []); + return CoreTextUtils.restorePluginfileUrls(text, files || []); } /** @@ -195,7 +195,7 @@ export class AddonModAssignSubmissionOnlineTextHandlerService implements AddonMo // Get the original text from plugin or offline. const offlineData = - await CoreUtils.instance.ignoreErrors(AddonModAssignOffline.instance.getSubmission(assign.id, submission.userid)); + await CoreUtils.ignoreErrors(AddonModAssignOffline.getSubmission(assign.id, submission.userid)); let initialText = ''; if (offlineData && offlineData.plugindata && offlineData.plugindata.onlinetext_editor) { @@ -226,7 +226,7 @@ export class AddonModAssignSubmissionOnlineTextHandlerService implements AddonMo isEnabledForEdit(): boolean { // There's a bug in Moodle 3.1.0 that doesn't allow submitting HTML, so we'll disable this plugin in that case. // Bug was fixed in 3.1.1 minor release and in 3.2. - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); return !!currentSite?.isVersionGreaterEqualThan('3.1.1') || !!currentSite?.checkIfAppUsesLocalMobile(); } @@ -255,20 +255,20 @@ export class AddonModAssignSubmissionOnlineTextHandlerService implements AddonMo let text = this.getTextToSubmit(plugin, inputData); // Check word limit. - const configs = AddonModAssignHelper.instance.getPluginConfig(assign, 'assignsubmission', plugin.type); + const configs = AddonModAssignHelper.getPluginConfig(assign, 'assignsubmission', plugin.type); if (parseInt(configs.wordlimitenabled, 10)) { - const words = CoreTextUtils.instance.countWords(text); + const words = CoreTextUtils.countWords(text); const wordlimit = parseInt(configs.wordlimit, 10); if (words > wordlimit) { const params = { $a: { count: words, limit: wordlimit } }; - const message = Translate.instance.instant('addon.mod_assign_submission_onlinetext.wordlimitexceeded', params); + const message = Translate.instant('addon.mod_assign_submission_onlinetext.wordlimitexceeded', params); throw new CoreError(message); } } // Add some HTML to the text if needed. - text = CoreTextUtils.instance.formatHtmlLines(text); + text = CoreTextUtils.formatHtmlLines(text); pluginData.onlinetext_editor = { text: text, diff --git a/src/addons/mod/book/book.module.ts b/src/addons/mod/book/book.module.ts index af8ec5278..bde5f4860 100644 --- a/src/addons/mod/book/book.module.ts +++ b/src/addons/mod/book/book.module.ts @@ -45,11 +45,11 @@ const routes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreCourseModuleDelegate.instance.registerHandler(AddonModBookModuleHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModBookIndexLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModBookListLinkHandler.instance); - CoreCourseModulePrefetchDelegate.instance.registerHandler(AddonModBookPrefetchHandler.instance); - CoreTagAreaDelegate.instance.registerHandler(AddonModBookTagAreaHandler.instance); + CoreCourseModuleDelegate.registerHandler(AddonModBookModuleHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModBookIndexLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModBookListLinkHandler.instance); + CoreCourseModulePrefetchDelegate.registerHandler(AddonModBookPrefetchHandler.instance); + CoreTagAreaDelegate.registerHandler(AddonModBookTagAreaHandler.instance); }, }, ], diff --git a/src/addons/mod/book/components/index/index.ts b/src/addons/mod/book/components/index/index.ts index 3951b9242..e64c21196 100644 --- a/src/addons/mod/book/components/index/index.ts +++ b/src/addons/mod/book/components/index/index.ts @@ -75,7 +75,7 @@ export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComp async ngOnInit(): Promise { super.ngOnInit(); - this.tagsEnabled = CoreTag.instance.areTagsAvailableInSite(); + this.tagsEnabled = CoreTag.areTagsAvailableInSite(); this.loadContent(); } @@ -84,7 +84,7 @@ export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComp */ async showToc(): Promise { // Create the toc modal. - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: AddonModBookTocComponent, componentProps: { moduleId: this.module!.id, @@ -130,7 +130,7 @@ export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComp * @return Resolved when done. */ protected invalidateContent(): Promise { - return AddonModBook.instance.invalidateContent(this.module!.id, this.courseId!); + return AddonModBook.invalidateContent(this.module!.id, this.courseId!); } /** @@ -144,7 +144,7 @@ export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComp let downloadResult: CoreCourseResourceDownloadResult | undefined; // Try to get the book data. Ignore errors since this WS isn't available in some Moodle versions. - promises.push(CoreUtils.instance.ignoreErrors(AddonModBook.instance.getBook(this.courseId!, this.module!.id)) + promises.push(CoreUtils.ignoreErrors(AddonModBook.getBook(this.courseId!, this.module!.id)) .then((book) => { if (!book) { return; @@ -170,8 +170,8 @@ export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComp try { await Promise.all(promises); - this.contentsMap = AddonModBook.instance.getContentsMap(this.module!.contents); - this.chapters = AddonModBook.instance.getTocList(this.module!.contents); + this.contentsMap = AddonModBook.getContentsMap(this.module!.contents); + this.chapters = AddonModBook.getTocList(this.module!.contents); if (typeof this.currentChapter == 'undefined' && typeof this.initialChapterId != 'undefined' && this.chapters) { // Initial chapter set. Validate that the chapter exists. @@ -184,7 +184,7 @@ export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComp if (typeof this.currentChapter == 'undefined') { // Load the first chapter. - this.currentChapter = AddonModBook.instance.getFirstChapter(this.chapters); + this.currentChapter = AddonModBook.getFirstChapter(this.chapters); } // Show chapter. @@ -212,23 +212,23 @@ export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComp this.content?.scrollToTop(); try { - const content = await AddonModBook.instance.getChapterContent(this.contentsMap, chapterId, this.module!.id); + const content = await AddonModBook.getChapterContent(this.contentsMap, chapterId, this.module!.id); this.tags = this.tagsEnabled ? this.contentsMap[this.currentChapter].tags : []; this.chapterContent = content; - this.previousChapter = AddonModBook.instance.getPreviousChapter(this.chapters, chapterId); - this.nextChapter = AddonModBook.instance.getNextChapter(this.chapters, chapterId); + this.previousChapter = AddonModBook.getPreviousChapter(this.chapters, chapterId); + this.nextChapter = AddonModBook.getNextChapter(this.chapters, chapterId); this.previousNavBarTitle = this.previousChapter && this.displayTitlesInNavBar - ? Translate.instance.instant('addon.mod_book.navprevtitle', { $a: this.previousChapter.title }) + ? Translate.instant('addon.mod_book.navprevtitle', { $a: this.previousChapter.title }) : ''; this.nextNavBarTitle = this.nextChapter && this.displayTitlesInNavBar - ? Translate.instance.instant('addon.mod_book.navnexttitle', { $a: this.nextChapter.title }) + ? Translate.instant('addon.mod_book.navnexttitle', { $a: this.nextChapter.title }) : ''; // Chapter loaded, log view. We don't return the promise because we don't want to block the user for this. - await CoreUtils.instance.ignoreErrors(AddonModBook.instance.logView( + await CoreUtils.ignoreErrors(AddonModBook.logView( this.module!.instance!, logChapterId ? chapterId : undefined, this.module!.name, @@ -236,10 +236,10 @@ export class AddonModBookIndexComponent extends CoreCourseModuleMainResourceComp // Module is completed when last chapter is viewed, so we only check completion if the last is reached. if (!this.nextChapter) { - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_book.errorchapter', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_book.errorchapter', true); throw error; } finally { diff --git a/src/addons/mod/book/components/toc/toc.ts b/src/addons/mod/book/components/toc/toc.ts index d83c59e25..dc3bf5c3b 100644 --- a/src/addons/mod/book/components/toc/toc.ts +++ b/src/addons/mod/book/components/toc/toc.ts @@ -53,14 +53,14 @@ export class AddonModBookTocComponent implements OnInit { * @param id ID of the clicked chapter. */ loadChapter(id: number): void { - ModalController.instance.dismiss(id); + ModalController.dismiss(id); } /** * Close modal. */ closeModal(): void { - ModalController.instance.dismiss(); + ModalController.dismiss(); } } diff --git a/src/addons/mod/book/pages/index/index.ts b/src/addons/mod/book/pages/index/index.ts index 102fd5a94..abd59810e 100644 --- a/src/addons/mod/book/pages/index/index.ts +++ b/src/addons/mod/book/pages/index/index.ts @@ -39,9 +39,9 @@ export class AddonModBookIndexPage implements OnInit { * Component being initialized. */ ngOnInit(): void { - this.module = CoreNavigator.instance.getRouteParam('module'); - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId'); - this.chapterId = CoreNavigator.instance.getRouteNumberParam('chapterId'); + this.module = CoreNavigator.getRouteParam('module'); + this.courseId = CoreNavigator.getRouteNumberParam('courseId'); + this.chapterId = CoreNavigator.getRouteNumberParam('chapterId'); this.title = this.module?.name; } diff --git a/src/addons/mod/book/services/book.ts b/src/addons/mod/book/services/book.ts index 0cf5edb14..7f7fa5bc6 100644 --- a/src/addons/mod/book/services/book.ts +++ b/src/addons/mod/book/services/book.ts @@ -85,7 +85,7 @@ export class AddonModBookProvider { options: CoreSitesCommonWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModBookGetBooksByCoursesWSParams = { courseids: [courseId], }; @@ -93,7 +93,7 @@ export class AddonModBookProvider { cacheKey: this.getBookDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModBookProvider.COMPONENT, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; const response: AddonModBookGetBooksByCoursesWSResponse = await site.read('mod_book_get_books_by_courses', params, preSets); @@ -133,19 +133,19 @@ export class AddonModBookProvider { throw new CoreWSError('Could not locate the index chapter.'); } - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { // We return the live URL. - return CoreSites.instance.getCurrentSite()!.checkAndFixPluginfileURL(indexUrl); + return CoreSites.getCurrentSite()!.checkAndFixPluginfileURL(indexUrl); } - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); - const url = await CoreFilepool.instance.downloadUrl(siteId, indexUrl, false, AddonModBookProvider.COMPONENT, moduleId); + const url = await CoreFilepool.downloadUrl(siteId, indexUrl, false, AddonModBookProvider.COMPONENT, moduleId); - const content = await CoreWS.instance.getText(url); + const content = await CoreWS.getText(url); // Now that we have the content, we update the SRC to point back to the external resource. - return CoreDomUtils.instance.restoreSourcesInHtml(content, contentsMap[chapterId].paths); + return CoreDomUtils.restoreSourcesInHtml(content, contentsMap[chapterId].paths); } /** @@ -197,7 +197,7 @@ export class AddonModBookProvider { key = content.filepath.replace('/' + chapter + '/', '') + content.filename; } - map[chapter].paths[CoreTextUtils.instance.decodeURIComponent(key)] = content.fileurl; + map[chapter].paths[CoreTextUtils.decodeURIComponent(key)] = content.fileurl; }); return map; @@ -258,7 +258,7 @@ export class AddonModBookProvider { return []; } - return CoreTextUtils.instance.parseJSON(contents[0].content, []); + return CoreTextUtils.parseJSON(contents[0].content, []); } /** @@ -320,7 +320,7 @@ export class AddonModBookProvider { * @return Promise resolved when the data is invalidated. */ async invalidateBookData(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getBookDataCacheKey(courseId)); } @@ -334,15 +334,15 @@ export class AddonModBookProvider { * @return Promise resolved when the data is invalidated. */ invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const promises: Promise[] = []; promises.push(this.invalidateBookData(courseId, siteId)); - promises.push(CoreFilepool.instance.invalidateFilesByComponent(siteId, AddonModBookProvider.COMPONENT, moduleId)); - promises.push(CoreCourse.instance.invalidateModule(moduleId, siteId)); + promises.push(CoreFilepool.invalidateFilesByComponent(siteId, AddonModBookProvider.COMPONENT, moduleId)); + promises.push(CoreCourse.invalidateModule(moduleId, siteId)); - return CoreUtils.instance.allPromises(promises); + return CoreUtils.allPromises(promises); } /** @@ -362,7 +362,7 @@ export class AddonModBookProvider { * @return Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise. */ async isPluginEnabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.canDownloadFiles(); } @@ -382,7 +382,7 @@ export class AddonModBookProvider { chapterid: chapterId, }; - await CoreCourseLogHelper.instance.logSingle( + await CoreCourseLogHelper.logSingle( 'mod_book_view_book', params, AddonModBookProvider.COMPONENT, @@ -396,7 +396,7 @@ export class AddonModBookProvider { } -export class AddonModBook extends makeSingleton(AddonModBookProvider) {} +export const AddonModBook = makeSingleton(AddonModBookProvider); /** * A book chapter inside the toc list. diff --git a/src/addons/mod/book/services/handlers/index-link.ts b/src/addons/mod/book/services/handlers/index-link.ts index cb1d39657..eb07cba7e 100644 --- a/src/addons/mod/book/services/handlers/index-link.ts +++ b/src/addons/mod/book/services/handlers/index-link.ts @@ -47,9 +47,9 @@ export class AddonModBookIndexLinkHandlerService extends CoreContentLinksModuleI * @return Whether the handler is enabled for the URL and site. */ isEnabled(siteId: string): Promise { - return AddonModBook.instance.isPluginEnabled(siteId); + return AddonModBook.isPluginEnabled(siteId); } } -export class AddonModBookIndexLinkHandler extends makeSingleton(AddonModBookIndexLinkHandlerService) {} +export const AddonModBookIndexLinkHandler = makeSingleton(AddonModBookIndexLinkHandlerService); diff --git a/src/addons/mod/book/services/handlers/list-link.ts b/src/addons/mod/book/services/handlers/list-link.ts index 96903dc74..b6bd0d7ee 100644 --- a/src/addons/mod/book/services/handlers/list-link.ts +++ b/src/addons/mod/book/services/handlers/list-link.ts @@ -36,9 +36,9 @@ export class AddonModBookListLinkHandlerService extends CoreContentLinksModuleLi * @return Whether the handler is enabled for the URL and site. */ isEnabled(): Promise { - return AddonModBook.instance.isPluginEnabled(); + return AddonModBook.isPluginEnabled(); } } -export class AddonModBookListLinkHandler extends makeSingleton(AddonModBookListLinkHandlerService) {} +export const AddonModBookListLinkHandler = makeSingleton(AddonModBookListLinkHandlerService); diff --git a/src/addons/mod/book/services/handlers/module.ts b/src/addons/mod/book/services/handlers/module.ts index 224fb766f..4ce95616e 100644 --- a/src/addons/mod/book/services/handlers/module.ts +++ b/src/addons/mod/book/services/handlers/module.ts @@ -51,7 +51,7 @@ export class AddonModBookModuleHandlerService implements CoreCourseModuleHandler * @return Whether or not the handler is enabled on a site level. */ isEnabled(): Promise { - return AddonModBook.instance.isPluginEnabled(); + return AddonModBook.isPluginEnabled(); } /** @@ -64,7 +64,7 @@ export class AddonModBookModuleHandlerService implements CoreCourseModuleHandler */ getData(module: CoreCourseAnyModuleData): CoreCourseModuleHandlerData { return { - icon: CoreCourse.instance.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), + icon: CoreCourse.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), title: module.name, class: 'addon-mod_book-handler', showDownloadButton: true, @@ -74,7 +74,7 @@ export class AddonModBookModuleHandlerService implements CoreCourseModuleHandler Object.assign(options.params, { module }); const routeParams = '/' + courseId + '/' + module.id; - CoreNavigator.instance.navigateToSitePath(AddonModBookModuleHandlerService.PAGE_NAME + routeParams, options); + CoreNavigator.navigateToSitePath(AddonModBookModuleHandlerService.PAGE_NAME + routeParams, options); }, }; } @@ -91,4 +91,4 @@ export class AddonModBookModuleHandlerService implements CoreCourseModuleHandler } } -export class AddonModBookModuleHandler extends makeSingleton(AddonModBookModuleHandlerService) {} +export const AddonModBookModuleHandler = makeSingleton(AddonModBookModuleHandlerService); diff --git a/src/addons/mod/book/services/handlers/prefetch.ts b/src/addons/mod/book/services/handlers/prefetch.ts index bc8475fe5..6dc9c26cf 100644 --- a/src/addons/mod/book/services/handlers/prefetch.ts +++ b/src/addons/mod/book/services/handlers/prefetch.ts @@ -44,7 +44,7 @@ export class AddonModBookPrefetchHandlerService extends CoreCourseResourcePrefet promises.push(super.downloadOrPrefetch(module, courseId, prefetch)); // Ignore errors since this WS isn't available in some Moodle versions. - promises.push(CoreUtils.instance.ignoreErrors(AddonModBook.instance.getBook(courseId, module.id))); + promises.push(CoreUtils.ignoreErrors(AddonModBook.getBook(courseId, module.id))); await Promise.all(promises); } @@ -56,7 +56,7 @@ export class AddonModBookPrefetchHandlerService extends CoreCourseResourcePrefet * @return Promise resolved with list of intro files. */ async getIntroFiles(module: CoreCourseAnyModuleData, courseId: number): Promise { - const book = await CoreUtils.instance.ignoreErrors(AddonModBook.instance.getBook(courseId, module.id)); + const book = await CoreUtils.ignoreErrors(AddonModBook.getBook(courseId, module.id)); return this.getIntroFilesFromInstance(module, book); } @@ -69,7 +69,7 @@ export class AddonModBookPrefetchHandlerService extends CoreCourseResourcePrefet * @return Promise resolved when the data is invalidated. */ async invalidateContent(moduleId: number, courseId: number): Promise { - await AddonModBook.instance.invalidateContent(moduleId, courseId); + await AddonModBook.invalidateContent(moduleId, courseId); } /** @@ -78,9 +78,9 @@ export class AddonModBookPrefetchHandlerService extends CoreCourseResourcePrefet * @return A boolean, or a promise resolved with a boolean, indicating if the handler is enabled. */ isEnabled(): Promise { - return AddonModBook.instance.isPluginEnabled(); + return AddonModBook.isPluginEnabled(); } } -export class AddonModBookPrefetchHandler extends makeSingleton(AddonModBookPrefetchHandlerService) {} +export const AddonModBookPrefetchHandler = makeSingleton(AddonModBookPrefetchHandlerService); diff --git a/src/addons/mod/book/services/handlers/tag-area.ts b/src/addons/mod/book/services/handlers/tag-area.ts index e416707ee..dea35c442 100644 --- a/src/addons/mod/book/services/handlers/tag-area.ts +++ b/src/addons/mod/book/services/handlers/tag-area.ts @@ -36,7 +36,7 @@ export class AddonModBookTagAreaHandlerService implements CoreTagAreaHandler { * @return Whether or not the handler is enabled on a site level. */ isEnabled(): Promise { - return AddonModBook.instance.isPluginEnabled(); + return AddonModBook.isPluginEnabled(); } /** @@ -46,15 +46,15 @@ export class AddonModBookTagAreaHandlerService implements CoreTagAreaHandler { * @return Area items (or promise resolved with the items). */ async parseContent(content: string): Promise { - const items = CoreTagHelper.instance.parseFeedContent(content); + const items = CoreTagHelper.parseFeedContent(content); // Find module ids of the returned books, they are needed by the link delegate. await Promise.all(items.map((item) => { - const params = item.url ? CoreUrlUtils.instance.extractUrlParams(item.url) : {}; + const params = item.url ? CoreUrlUtils.extractUrlParams(item.url) : {}; if (params.b && !params.id) { const bookId = parseInt(params.b, 10); - return CoreCourse.instance.getModuleBasicInfoByInstance(bookId, 'book').then((module) => { + return CoreCourse.getModuleBasicInfoByInstance(bookId, 'book').then((module) => { item.url += '&id=' + module.id; return; @@ -76,4 +76,4 @@ export class AddonModBookTagAreaHandlerService implements CoreTagAreaHandler { } -export class AddonModBookTagAreaHandler extends makeSingleton(AddonModBookTagAreaHandlerService) {} +export const AddonModBookTagAreaHandler = makeSingleton(AddonModBookTagAreaHandlerService); diff --git a/src/addons/mod/forum/components/discussion-options-menu/discussion-options-menu.ts b/src/addons/mod/forum/components/discussion-options-menu/discussion-options-menu.ts index 10969ab5d..415b18862 100644 --- a/src/addons/mod/forum/components/discussion-options-menu/discussion-options-menu.ts +++ b/src/addons/mod/forum/components/discussion-options-menu/discussion-options-menu.ts @@ -38,7 +38,7 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { * Component being initialized. */ async ngOnInit(): Promise { - if (!AddonModForum.instance.isSetPinStateAvailableForSite()) { + if (!AddonModForum.isSetPinStateAvailableForSite()) { this.canPin = false; return; @@ -46,7 +46,7 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { // Use the canAddDiscussion WS to check if the user can pin discussions. try { - const response = await AddonModForum.instance.canAddDiscussionToAll(this.forumId, { cmId: this.cmId }); + const response = await AddonModForum.canAddDiscussionToAll(this.forumId, { cmId: this.cmId }); this.canPin = !!response.canpindiscussions; } catch (error) { @@ -60,10 +60,10 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { * @param locked True to lock the discussion, false to unlock. */ async setLockState(locked: boolean): Promise { - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - const response = await AddonModForum.instance.setLockState(this.forumId, this.discussion.discussion, locked); + const response = await AddonModForum.setLockState(this.forumId, this.discussion.discussion, locked); const data = { forumId: this.forumId, discussionId: this.discussion.discussion, @@ -71,12 +71,12 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { locked: response.locked, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.instance.getCurrentSiteId()); - PopoverController.instance.dismiss({ action: 'lock', value: locked }); - CoreDomUtils.instance.showToast('addon.mod_forum.lockupdated', true); + CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + PopoverController.dismiss({ action: 'lock', value: locked }); + CoreDomUtils.showToast('addon.mod_forum.lockupdated', true); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); - PopoverController.instance.dismiss(); + CoreDomUtils.showErrorModal(error); + PopoverController.dismiss(); } finally { modal.dismiss(); } @@ -88,10 +88,10 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { * @param pinned True to pin the discussion, false to unpin it. */ async setPinState(pinned: boolean): Promise { - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - await AddonModForum.instance.setPinState(this.discussion.discussion, pinned); + await AddonModForum.setPinState(this.discussion.discussion, pinned); const data = { forumId: this.forumId, @@ -100,12 +100,12 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { pinned: pinned, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.instance.getCurrentSiteId()); - PopoverController.instance.dismiss({ action: 'pin', value: pinned }); - CoreDomUtils.instance.showToast('addon.mod_forum.pinupdated', true); + CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + PopoverController.dismiss({ action: 'pin', value: pinned }); + CoreDomUtils.showToast('addon.mod_forum.pinupdated', true); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); - PopoverController.instance.dismiss(); + CoreDomUtils.showErrorModal(error); + PopoverController.dismiss(); } finally { modal.dismiss(); } @@ -117,10 +117,10 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { * @param starred True to star the discussion, false to unstar it. */ async toggleFavouriteState(starred: boolean): Promise { - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - await AddonModForum.instance.toggleFavouriteState(this.discussion.discussion, starred); + await AddonModForum.toggleFavouriteState(this.discussion.discussion, starred); const data = { forumId: this.forumId, @@ -129,12 +129,12 @@ export class AddonModForumDiscussionOptionsMenuComponent implements OnInit { starred: starred, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.instance.getCurrentSiteId()); - PopoverController.instance.dismiss({ action: 'star', value: starred }); - CoreDomUtils.instance.showToast('addon.mod_forum.favouriteupdated', true); + CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); + PopoverController.dismiss({ action: 'star', value: starred }); + CoreDomUtils.showToast('addon.mod_forum.favouriteupdated', true); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); - PopoverController.instance.dismiss(); + CoreDomUtils.showErrorModal(error); + PopoverController.dismiss(); } finally { modal.dismiss(); } diff --git a/src/addons/mod/forum/components/edit-post/edit-post.ts b/src/addons/mod/forum/components/edit-post/edit-post.ts index a0e340629..230333110 100644 --- a/src/addons/mod/forum/components/edit-post/edit-post.ts +++ b/src/addons/mod/forum/components/edit-post/edit-post.ts @@ -55,7 +55,7 @@ export class AddonModForumEditPostComponent implements OnInit { }; // Delete the local files from the tmp folder if any. - CoreFileUploader.instance.clearTmpFiles(this.replyData.files as CoreFileEntry[]); + CoreFileUploader.clearTmpFiles(this.replyData.files as CoreFileEntry[]); // Update rich text editor. this.messageControl.setValue(this.replyData.message); @@ -93,12 +93,12 @@ export class AddonModForumEditPostComponent implements OnInit { } if (data) { - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, false, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, false, CoreSites.getCurrentSiteId()); } else { - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); } - ModalController.instance.dismiss(data); + ModalController.dismiss(data); } /** @@ -128,16 +128,16 @@ export class AddonModForumEditPostComponent implements OnInit { * @return Resolved if we can leave it, rejected if not. */ private async confirmDismiss(): Promise { - if (this.forceLeave || !AddonModForumHelper.instance.hasPostDataChanged(this.replyData, this.originalData)) { + if (this.forceLeave || !AddonModForumHelper.hasPostDataChanged(this.replyData, this.originalData)) { return true; } try { // Show confirmation if some data has been modified. - await CoreDomUtils.instance.showConfirm(Translate.instant('core.confirmcanceledit')); + await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); // Delete the local files from the tmp folder. - CoreFileUploader.instance.clearTmpFiles(this.replyData.files as CoreFileEntry[]); + CoreFileUploader.clearTmpFiles(this.replyData.files as CoreFileEntry[]); return true; } catch (error) { diff --git a/src/addons/mod/forum/components/index/index.ts b/src/addons/mod/forum/components/index/index.ts index 9e215fdec..3fca535d3 100644 --- a/src/addons/mod/forum/components/index/index.ts +++ b/src/addons/mod/forum/components/index/index.ts @@ -110,9 +110,9 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom * Component being initialized. */ async ngOnInit(): Promise { - this.addDiscussionText = Translate.instance.instant('addon.mod_forum.addanewdiscussion'); - this.sortingAvailable = AddonModForum.instance.isDiscussionListSortingAvailable(); - this.sortOrders = AddonModForum.instance.getAvailableSortOrders(); + this.addDiscussionText = Translate.instant('addon.mod_forum.addanewdiscussion'); + this.sortingAvailable = AddonModForum.isDiscussionListSortingAvailable(); + this.sortOrders = AddonModForum.getAvailableSortOrders(); await super.ngOnInit(); @@ -132,7 +132,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom ); this.changeDiscObserver = CoreEvents.on(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data => { if ((this.forum && this.forum.id === data.forumId) || data.cmId === this.module!.id) { - AddonModForum.instance.invalidateDiscussionsList(this.forum!.id).finally(() => { + AddonModForum.invalidateDiscussionsList(this.forum!.id).finally(() => { if (data.discussionId) { // Discussion changed, search it in the list of discussions. const discussion = this.discussions.items.find( @@ -155,7 +155,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom } if (typeof data.deleted != 'undefined' && data.deleted) { - if (data.post?.parentid == 0 && CoreScreen.instance.isTablet && !this.discussions.empty) { + if (data.post?.parentid == 0 && CoreScreen.isTablet && !this.discussions.empty) { // Discussion deleted, clear details page. this.discussions.select(this.discussions[0]); } @@ -176,11 +176,11 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom return; } - CoreUtils.instance.ignoreErrors( + CoreUtils.ignoreErrors( AddonModForum.instance .logView(this.forum.id, this.forum.name) .then(async () => { - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); return; }), @@ -228,7 +228,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom ]); } catch (error) { if (refresh) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_forum.errorgetforum', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_forum.errorgetforum', true); this.fetchMoreDiscussionsFailed = true; // Set to prevent infinite calls with infinite-loading. } else { @@ -245,11 +245,11 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom return; } - const forum = await AddonModForum.instance.getForum(this.courseId, this.module.id); + const forum = await AddonModForum.getForum(this.courseId, this.module.id); this.forum = forum; this.description = forum.intro || this.description; - this.availabilityMessage = AddonModForumHelper.instance.getAvailabilityMessage(forum); + this.availabilityMessage = AddonModForumHelper.getAvailabilityMessage(forum); this.descriptionNote = Translate.instant('addon.mod_forum.numdiscussions', { numdiscussions: forum.numdiscussions, }); @@ -280,9 +280,9 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom // Sync successful, send event. CoreEvents.trigger(AddonModForumSyncProvider.MANUAL_SYNCED, { forumId: forum.id, - userId: CoreSites.instance.getCurrentSiteUserId(), + userId: CoreSites.getCurrentSiteUserId(), source: 'index', - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } } @@ -307,7 +307,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom // Disallow adding discussions if cut-off date is reached and the user has not the // capability to override it. // Just in case the forum was fetched from WS when the cut-off date was not reached but it is now. - const cutoffDateReached = AddonModForumHelper.instance.isCutoffDateReached(this.forum!) + const cutoffDateReached = AddonModForumHelper.isCutoffDateReached(this.forum!) && !accessInfo.cancanoverridecutoff; this.canAddDiscussion = !!this.forum?.cancreatediscussions && !cutoffDateReached; @@ -315,7 +315,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom }), ); - if (AddonModForum.instance.isSetPinStateAvailableForSite()) { + if (AddonModForum.isSetPinStateAvailableForSite()) { // Use the canAddDiscussion WS to check if the user can pin discussions. promises.push( AddonModForum.instance @@ -345,7 +345,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom */ protected async fetchOfflineDiscussions(): Promise { const forum = this.forum!; - let offlineDiscussions = await AddonModForumOffline.instance.getNewDiscussions(forum.id); + let offlineDiscussions = await AddonModForumOffline.getNewDiscussions(forum.id); this.hasOffline = !!offlineDiscussions.length; if (!this.hasOffline) { @@ -355,7 +355,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom } if (this.usesGroups) { - offlineDiscussions = await AddonModForum.instance.formatDiscussionsGroups(forum.cmid, offlineDiscussions); + offlineDiscussions = await AddonModForum.formatDiscussionsGroups(forum.cmid, offlineDiscussions); } // Fill user data for Offline discussions (should be already cached). @@ -366,7 +366,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom } try { - const user = await CoreUser.instance.getProfile(discussion.userid, this.courseId, true); + const user = await CoreUser.getProfile(discussion.userid, this.courseId, true); discussion.userfullname = user.fullname; discussion.userpictureurl = user.profileimageurl; @@ -397,7 +397,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom this.page = 0; } - const response = await AddonModForum.instance.getDiscussions(forum.id, { + const response = await AddonModForum.getDiscussions(forum.id, { cmId: forum.cmid, sortOrder: this.selectedSortOrder!.value, page: this.page, @@ -405,7 +405,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom let discussions = response.discussions; if (this.usesGroups) { - discussions = await AddonModForum.instance.formatDiscussionsGroups(forum.cmid, discussions); + discussions = await AddonModForum.formatDiscussionsGroups(forum.cmid, discussions); } // Hide author for first post and type single. @@ -437,7 +437,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom this.page++; // Check if there are replies for discussions stored in offline. - const hasOffline = await AddonModForumOffline.instance.hasForumReplies(forum.id); + const hasOffline = await AddonModForumOffline.hasForumReplies(forum.id); this.hasOffline = this.hasOffline || hasOffline; @@ -445,7 +445,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom // Only update new fetched discussions. const promises = discussions.map(async (discussion) => { // Get offline discussions. - const replies = await AddonModForumOffline.instance.getDiscussionReplies(discussion.discussion); + const replies = await AddonModForumOffline.getDiscussionReplies(discussion.discussion); discussion.numreplies = Number(discussion.numreplies) + replies.length; }); @@ -464,7 +464,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom try { await this.fetchDiscussions(false); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_forum.errorgetforum', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_forum.errorgetforum', true); this.fetchMoreDiscussionsFailed = true; } finally { @@ -483,8 +483,8 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom return null; } - const value = await CoreUtils.instance.ignoreErrors( - CoreUser.instance.getUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER), + const value = await CoreUtils.ignoreErrors( + CoreUser.getUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER), ); return value ? parseInt(value, 10) : null; @@ -503,16 +503,16 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom protected async invalidateContent(): Promise { const promises: Promise[] = []; - promises.push(AddonModForum.instance.invalidateForumData(this.courseId!)); + promises.push(AddonModForum.invalidateForumData(this.courseId!)); if (this.forum) { - promises.push(AddonModForum.instance.invalidateDiscussionsList(this.forum.id)); - promises.push(CoreGroups.instance.invalidateActivityGroupMode(this.forum.cmid)); - promises.push(AddonModForum.instance.invalidateAccessInformation(this.forum.id)); + promises.push(AddonModForum.invalidateDiscussionsList(this.forum.id)); + promises.push(CoreGroups.invalidateActivityGroupMode(this.forum.cmid)); + promises.push(AddonModForum.invalidateAccessInformation(this.forum.id)); } if (this.sortingAvailable) { - promises.push(CoreUser.instance.invalidateUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER)); + promises.push(CoreUser.invalidateUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER)); } await Promise.all(promises); @@ -524,7 +524,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom * @return Promise resolved when done. */ protected sync(): Promise { - return AddonModForumPrefetchHandler.instance.sync(this.module!, this.courseId!); + return AddonModForumPrefetchHandler.sync(this.module!, this.courseId!); } /** @@ -547,7 +547,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom return !!this.forum && (!('source' in syncEventData) || syncEventData.source != 'index') && syncEventData.forumId == this.forum.id - && syncEventData.userId == CoreSites.instance.getCurrentSiteUserId(); + && syncEventData.userId == CoreSites.getCurrentSiteUserId(); } /** @@ -563,7 +563,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom if ((this.forum && this.forum.id === data.forumId) || data.cmId === this.module?.id) { this.showLoadingAndRefresh(false).finally(() => { // If it's a new discussion in tablet mode, try to open it. - if (isNewDiscussion && CoreScreen.instance.isTablet) { + if (isNewDiscussion && CoreScreen.isTablet) { const newDiscussionData = data as AddonModForumNewDiscussionData; const discussion = this.discussions.items.find(disc => { if (this.discussions.isOfflineDiscussion(disc)) { @@ -584,7 +584,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom }); // Check completion since it could be configured to complete once the user adds a new discussion or replies. - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); } } @@ -605,7 +605,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom return; } - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: AddonModForumSortOrderSelectorComponent, componentProps: { sortOrders: this.sortOrders, @@ -626,10 +626,10 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom this.page = 0; try { - await CoreUser.instance.setUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER, result.data.value.toFixed(0)); + await CoreUser.setUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER, result.data.value.toFixed(0)); await this.showLoadingAndFetch(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error updating preference.'); + CoreDomUtils.showErrorModalDefault(error, 'Error updating preference.'); } } } @@ -641,7 +641,7 @@ export class AddonModForumIndexComponent extends CoreCourseModuleMainActivityCom * @param discussion Discussion. */ async showOptionsMenu(event: Event, discussion: AddonModForumDiscussion): Promise { - const popover = await PopoverController.instance.create({ + const popover = await PopoverController.create({ component: AddonModForumDiscussionOptionsMenuComponent, componentProps: { discussion, diff --git a/src/addons/mod/forum/components/post-options-menu/post-options-menu.ts b/src/addons/mod/forum/components/post-options-menu/post-options-menu.ts index 74443bcf8..4b5ed2c4d 100644 --- a/src/addons/mod/forum/components/post-options-menu/post-options-menu.ts +++ b/src/addons/mod/forum/components/post-options-menu/post-options-menu.ts @@ -48,17 +48,17 @@ export class AddonModForumPostOptionsMenuComponent implements OnInit, OnDestroy * Component being initialized. */ async ngOnInit(): Promise { - this.isOnline = CoreApp.instance.isOnline(); + this.isOnline = CoreApp.isOnline(); - this.onlineObserver = Network.instance.onChange().subscribe(() => { + this.onlineObserver = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { - this.isOnline = CoreApp.instance.isOnline(); + NgZone.run(() => { + this.isOnline = CoreApp.isOnline(); }); }); if (this.post.id > 0) { - const site = CoreSites.instance.getCurrentSite()!; + const site = CoreSites.getCurrentSite()!; this.url = site.createSiteUrl('/mod/forum/discuss.php', { d: this.post.discussionid.toString() }, 'p' + this.post.id); this.offlinePost = false; } else { @@ -73,12 +73,12 @@ export class AddonModForumPostOptionsMenuComponent implements OnInit, OnDestroy if (this.forumId) { try { this.post = - await AddonModForum.instance.getDiscussionPost(this.forumId, this.post.discussionid, this.post.id, { + await AddonModForum.getDiscussionPost(this.forumId, this.post.discussionid, this.post.id, { cmId: this.cmId, readingStrategy: CoreSitesReadingStrategy.OnlyNetwork, }); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting discussion post.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting discussion post.'); } } else { this.loaded = true; @@ -87,8 +87,8 @@ export class AddonModForumPostOptionsMenuComponent implements OnInit, OnDestroy } } - this.canDelete = !!this.post.capabilities.delete && AddonModForum.instance.isDeletePostAvailable(); - this.canEdit = !!this.post.capabilities.edit && AddonModForum.instance.isUpdatePostAvailable(); + this.canDelete = !!this.post.capabilities.delete && AddonModForum.isDeletePostAvailable(); + this.canEdit = !!this.post.capabilities.edit && AddonModForum.isUpdatePostAvailable(); this.wordCount = (this.post.haswordcount && this.post.wordcount) || null; this.loaded = true; } @@ -104,7 +104,7 @@ export class AddonModForumPostOptionsMenuComponent implements OnInit, OnDestroy * Close the popover. */ dismiss(): void { - PopoverController.instance.dismiss(); + PopoverController.dismiss(); } /** @@ -112,9 +112,9 @@ export class AddonModForumPostOptionsMenuComponent implements OnInit, OnDestroy */ deletePost(): void { if (!this.offlinePost) { - PopoverController.instance.dismiss({ action: 'delete' }); + PopoverController.dismiss({ action: 'delete' }); } else { - PopoverController.instance.dismiss({ action: 'deleteoffline' }); + PopoverController.dismiss({ action: 'deleteoffline' }); } } @@ -123,9 +123,9 @@ export class AddonModForumPostOptionsMenuComponent implements OnInit, OnDestroy */ editPost(): void { if (!this.offlinePost) { - PopoverController.instance.dismiss({ action: 'edit' }); + PopoverController.dismiss({ action: 'edit' }); } else { - PopoverController.instance.dismiss({ action: 'editoffline' }); + PopoverController.dismiss({ action: 'editoffline' }); } } diff --git a/src/addons/mod/forum/components/post/post.ts b/src/addons/mod/forum/components/post/post.ts index 9fd345a13..fa853d497 100644 --- a/src/addons/mod/forum/components/post/post.ts +++ b/src/addons/mod/forum/components/post/post.ts @@ -108,7 +108,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges * Component being initialized. */ ngOnInit(): void { - this.tagsEnabled = CoreTag.instance.areTagsAvailableInSite(); + this.tagsEnabled = CoreTag.areTagsAvailableInSite(); this.uniqueId = this.post.id > 0 ? 'reply' + this.post.id : 'edit' + this.post.parentid; const reTranslated = Translate.instant('addon.mod_forum.re'); @@ -118,8 +118,8 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges this.defaultReplySubject = this.post.replysubject || ((this.post.subject.startsWith('Re: ') || this.post.subject.startsWith(reTranslated)) ? this.post.subject : `${reTranslated} ${this.post.subject}`); - this.optionsMenuEnabled = this.post.id < 0 || (AddonModForum.instance.isGetDiscussionPostAvailable() && - (AddonModForum.instance.isDeletePostAvailable() || AddonModForum.instance.isUpdatePostAvailable())); + this.optionsMenuEnabled = this.post.id < 0 || (AddonModForum.isGetDiscussionPostAvailable() && + (AddonModForum.isDeletePostAvailable() || AddonModForum.isUpdatePostAvailable())); } /** @@ -128,7 +128,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges ngOnChanges(changes: {[name: string]: SimpleChange}): void { if (changes.leavingPage && this.leavingPage) { // Download all courses is enabled now, initialize it. - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); } } @@ -137,12 +137,12 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges */ async deletePost(): Promise { try { - await CoreDomUtils.instance.showDeleteConfirm('addon.mod_forum.deletesure'); + await CoreDomUtils.showDeleteConfirm('addon.mod_forum.deletesure'); - const modal = await CoreDomUtils.instance.showModalLoading('core.deleting', true); + const modal = await CoreDomUtils.showModalLoading('core.deleting', true); try { - const response = await AddonModForum.instance.deletePost(this.post.id); + const response = await AddonModForum.deletePost(this.post.id); const data = { forumId: this.forum.id, @@ -155,12 +155,12 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges CoreEvents.trigger( AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); - CoreDomUtils.instance.showToast('addon.mod_forum.deletedpost', true); + CoreDomUtils.showToast('addon.mod_forum.deletedpost', true); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { modal.dismiss(); } @@ -188,7 +188,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges isPrivate?: boolean, ): void { // Delete the local files from the tmp folder if any. - CoreFileUploader.instance.clearTmpFiles(this.replyData.files); + CoreFileUploader.clearTmpFiles(this.replyData.files); this.replyData.replyingTo = replyingTo || 0; this.replyData.isEditing = !!isEditing; @@ -216,7 +216,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges * @param event Click Event. */ async showOptionsMenu(event: Event): Promise { - const popover = await PopoverController.instance.create({ + const popover = await PopoverController.create({ component: AddonModForumPostOptionsMenuComponent, componentProps: { post: this.post, @@ -252,7 +252,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges * Shows a form modal to edit an online post. */ async editPost(): Promise { - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: AddonModForumEditPostComponent, componentProps: { post: this.post, @@ -273,16 +273,16 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges } // Add some HTML to the message if needed. - const message = CoreTextUtils.instance.formatHtmlLines(data.message); + const message = CoreTextUtils.formatHtmlLines(data.message); const files = data.files; const options: AddonModForumUpdateDiscussionPostWSOptionsObject = {}; - const sendingModal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const sendingModal = await CoreDomUtils.showModalLoading('core.sending', true); try { // Upload attachments first if any. if (files.length) { - const attachment = await AddonModForumHelper.instance.uploadOrStoreReplyFiles( + const attachment = await AddonModForumHelper.uploadOrStoreReplyFiles( this.forum.id, this.post.id, files, @@ -293,11 +293,11 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges } // Try to send it to server. - const sent = await AddonModForum.instance.updatePost(this.post.id, data.subject, message, options); + const sent = await AddonModForum.updatePost(this.post.id, data.subject, message, options); if (sent && this.forum.id) { // Data sent to server, delete stored files (if any). - AddonModForumHelper.instance.deleteReplyStoredFiles(this.forum.id, this.post.id); + AddonModForumHelper.deleteReplyStoredFiles(this.forum.id, this.post.id); this.onPostChange.emit(); this.post.subject = data.subject; @@ -305,7 +305,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges this.post.attachments = data.files; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_forum.couldnotupdate', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_forum.couldnotupdate', true); } finally { sendingModal.dismiss(); } @@ -323,7 +323,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges if (this.content) { setTimeout(() => { - CoreDomUtils.instance.scrollToElementBySelector( + CoreDomUtils.scrollToElementBySelector( this.elementRef.nativeElement, this.content, '#addon-forum-reply-edit-form-' + this.uniqueId, @@ -355,7 +355,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges if (this.content) { setTimeout(() => { - CoreDomUtils.instance.scrollToElementBySelector( + CoreDomUtils.scrollToElementBySelector( this.elementRef.nativeElement, this.content, '#addon-forum-reply-edit-form-' + this.uniqueId, @@ -373,8 +373,8 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges try { await this.confirmDiscard(); - this.syncId = AddonModForumSync.instance.getDiscussionSyncId(this.discussionId); - CoreSync.instance.blockOperation(AddonModForumProvider.COMPONENT, this.syncId); + this.syncId = AddonModForumSync.getDiscussionSyncId(this.discussionId); + CoreSync.blockOperation(AddonModForumProvider.COMPONENT, this.syncId); this.setReplyFormData( this.post.parentid, @@ -403,13 +403,13 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges */ async reply(): Promise { if (!this.replyData.subject) { - CoreDomUtils.instance.showErrorModal('addon.mod_forum.erroremptysubject', true); + CoreDomUtils.showErrorModal('addon.mod_forum.erroremptysubject', true); return; } if (!this.replyData.message) { - CoreDomUtils.instance.showErrorModal('addon.mod_forum.erroremptymessage', true); + CoreDomUtils.showErrorModal('addon.mod_forum.erroremptymessage', true); return; } @@ -420,10 +420,10 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges const replyingTo = this.replyData.replyingTo; const files = this.replyData.files || []; const options: AddonModForumReplyOptions = {}; - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); // Add some HTML to the message if needed. - message = CoreTextUtils.instance.formatHtmlLines(message); + message = CoreTextUtils.formatHtmlLines(message); // Set private option if checked. if (this.replyData.isprivatereply) { @@ -435,7 +435,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges if (files.length) { try { - attachments = await AddonModForumHelper.instance.uploadOrStoreReplyFiles(this.forum.id, replyingTo, files, false); + attachments = await AddonModForumHelper.uploadOrStoreReplyFiles(this.forum.id, replyingTo, files, false); } catch (error) { // Cannot upload them in online, save them in offline. @@ -445,7 +445,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges } saveOffline = true; - attachments = await AddonModForumHelper.instance.uploadOrStoreReplyFiles(this.forum.id, replyingTo, files, true); + attachments = await AddonModForumHelper.uploadOrStoreReplyFiles(this.forum.id, replyingTo, files, true); } } @@ -457,7 +457,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges let sent; if (saveOffline) { // Save post in offline. - await AddonModForumOffline.instance.replyPost( + await AddonModForumOffline.replyPost( replyingTo, this.discussionId, this.forum.id, @@ -473,7 +473,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges } else { // Try to send it to server. // Don't allow offline if there are attachments since they were uploaded fine. - sent = await AddonModForum.instance.replyPost( + sent = await AddonModForum.replyPost( replyingTo, this.discussionId, this.forum.id, @@ -489,7 +489,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges if (sent && this.forum.id) { // Data sent to server, delete stored files (if any). - AddonModForumHelper.instance.deleteReplyStoredFiles(this.forum.id, replyingTo); + AddonModForumHelper.deleteReplyStoredFiles(this.forum.id, replyingTo); } // Reset data. @@ -497,13 +497,13 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges this.onPostChange.emit(); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, sent, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, sent, CoreSites.getCurrentSiteId()); if (this.syncId) { - CoreSync.instance.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); + CoreSync.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_forum.couldnotadd', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_forum.couldnotadd', true); } finally { modal.dismiss(); } @@ -519,10 +519,10 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges // Reset data. this.setReplyFormData(); - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); if (this.syncId) { - CoreSync.instance.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); + CoreSync.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); } } catch (error) { // Cancelled. @@ -534,19 +534,19 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges */ async discardOfflineReply(): Promise { try { - await CoreDomUtils.instance.showDeleteConfirm(); + await CoreDomUtils.showDeleteConfirm(); const promises: Promise[] = []; - promises.push(AddonModForumOffline.instance.deleteReply(this.post.parentid!)); + promises.push(AddonModForumOffline.deleteReply(this.post.parentid!)); if (this.forum.id) { - promises.push(AddonModForumHelper.instance.deleteReplyStoredFiles(this.forum.id, this.post.parentid!).catch(() => { + promises.push(AddonModForumHelper.deleteReplyStoredFiles(this.forum.id, this.post.parentid!).catch(() => { // Ignore errors, maybe there are no files. })); } - await CoreUtils.instance.ignoreErrors(Promise.all(promises)); + await CoreUtils.ignoreErrors(Promise.all(promises)); // Reset data. this.setReplyFormData(); @@ -554,7 +554,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges this.onPostChange.emit(); if (this.syncId) { - CoreSync.instance.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); + CoreSync.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); } } catch (error) { // Cancelled. @@ -565,7 +565,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges * Function called when rating is updated online. */ ratingUpdated(): void { - AddonModForum.instance.invalidateDiscussionPosts(this.discussionId, this.forum.id); + AddonModForum.invalidateDiscussionPosts(this.discussionId, this.forum.id); } /** @@ -580,7 +580,7 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges */ ngOnDestroy(): void { if (this.syncId) { - CoreSync.instance.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); + CoreSync.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); } } @@ -590,9 +590,9 @@ export class AddonModForumPostComponent implements OnInit, OnDestroy, OnChanges * @return Promise resolved if the user confirms or data was not changed and rejected otherwise. */ protected confirmDiscard(): Promise { - if (AddonModForumHelper.instance.hasPostDataChanged(this.replyData, this.originalData)) { + if (AddonModForumHelper.hasPostDataChanged(this.replyData, this.originalData)) { // Show confirmation if some data has been modified. - return CoreDomUtils.instance.showConfirm(Translate.instant('core.confirmloss')); + return CoreDomUtils.showConfirm(Translate.instant('core.confirmloss')); } else { return Promise.resolve(); } diff --git a/src/addons/mod/forum/components/sort-order-selector/sort-order-selector.ts b/src/addons/mod/forum/components/sort-order-selector/sort-order-selector.ts index 6240be65b..6de83877c 100644 --- a/src/addons/mod/forum/components/sort-order-selector/sort-order-selector.ts +++ b/src/addons/mod/forum/components/sort-order-selector/sort-order-selector.ts @@ -32,7 +32,7 @@ export class AddonModForumSortOrderSelectorComponent { * Close the modal. */ closeModal(): void { - ModalController.instance.dismiss(); + ModalController.dismiss(); } /** @@ -41,7 +41,7 @@ export class AddonModForumSortOrderSelectorComponent { * @param sortOrder Selected sort order. */ selectSortOrder(sortOrder: AddonModForumSortOrder): void { - ModalController.instance.dismiss(sortOrder); + ModalController.dismiss(sortOrder); } } diff --git a/src/addons/mod/forum/forum-lazy.module.ts b/src/addons/mod/forum/forum-lazy.module.ts index a4b888420..5d7301643 100644 --- a/src/addons/mod/forum/forum-lazy.module.ts +++ b/src/addons/mod/forum/forum-lazy.module.ts @@ -57,8 +57,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; @NgModule({ diff --git a/src/addons/mod/forum/forum.module.ts b/src/addons/mod/forum/forum.module.ts index a3c602250..d5ca65ae1 100644 --- a/src/addons/mod/forum/forum.module.ts +++ b/src/addons/mod/forum/forum.module.ts @@ -60,7 +60,7 @@ const mainMenuRoutes: Routes = [ loadChildren: () => import('./pages/discussion/discussion.module').then(m => m.AddonForumDiscussionPageModule), }, ], - () => CoreScreen.instance.isMobile, + () => CoreScreen.isMobile, ), ]; @@ -76,7 +76,7 @@ const courseContentsRoutes: Routes = conditionalRoutes( loadChildren: () => import('./pages/discussion/discussion.module').then(m => m.AddonForumDiscussionPageModule), }, ], - () => CoreScreen.instance.isTablet, + () => CoreScreen.isTablet, ); @NgModule({ @@ -95,15 +95,15 @@ const courseContentsRoutes: Routes = conditionalRoutes( provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreCourseModuleDelegate.instance.registerHandler(AddonModForumModuleHandler.instance); - CoreCourseModulePrefetchDelegate.instance.registerHandler(AddonModForumPrefetchHandler.instance); - CoreCronDelegate.instance.register(AddonModForumSyncCronHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModForumDiscussionLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModForumIndexLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModForumListLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModForumPostLinkHandler.instance); - CoreTagAreaDelegate.instance.registerHandler(AddonModForumTagAreaHandler.instance); - CorePushNotificationsDelegate.instance.registerClickHandler(AddonModForumPushClickHandler.instance); + CoreCourseModuleDelegate.registerHandler(AddonModForumModuleHandler.instance); + CoreCourseModulePrefetchDelegate.registerHandler(AddonModForumPrefetchHandler.instance); + CoreCronDelegate.register(AddonModForumSyncCronHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModForumDiscussionLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModForumIndexLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModForumListLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModForumPostLinkHandler.instance); + CoreTagAreaDelegate.registerHandler(AddonModForumTagAreaHandler.instance); + CorePushNotificationsDelegate.registerClickHandler(AddonModForumPushClickHandler.instance); }, }, ], diff --git a/src/addons/mod/forum/pages/discussion/discussion.page.ts b/src/addons/mod/forum/pages/discussion/discussion.page.ts index 3f04001d3..6b10eb4df 100644 --- a/src/addons/mod/forum/pages/discussion/discussion.page.ts +++ b/src/addons/mod/forum/pages/discussion/discussion.page.ts @@ -113,26 +113,26 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes ) {} get isMobile(): boolean { - return CoreScreen.instance.isMobile; + return CoreScreen.isMobile; } ngOnInit(): void { - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.cmId = CoreNavigator.instance.getRouteNumberParam('cmId')!; - this.forumId = CoreNavigator.instance.getRouteNumberParam('forumId')!; - this.discussion = CoreNavigator.instance.getRouteParam('discussion')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.cmId = CoreNavigator.getRouteNumberParam('cmId')!; + this.forumId = CoreNavigator.getRouteNumberParam('forumId')!; + this.discussion = CoreNavigator.getRouteParam('discussion')!; this.discussionId = this.discussion ? this.discussion.discussion - : CoreNavigator.instance.getRouteNumberParam('discussionId')!; - this.trackPosts = CoreNavigator.instance.getRouteBooleanParam('trackPosts')!; - this.postId = CoreNavigator.instance.getRouteNumberParam('postId')!; - this.parent = CoreNavigator.instance.getRouteNumberParam('parent')!; + : CoreNavigator.getRouteNumberParam('discussionId')!; + this.trackPosts = CoreNavigator.getRouteBooleanParam('trackPosts')!; + this.postId = CoreNavigator.getRouteNumberParam('postId')!; + this.parent = CoreNavigator.getRouteNumberParam('parent')!; - this.isOnline = CoreApp.instance.isOnline(); - this.onlineObserver = Network.instance.onChange().subscribe(() => { + this.isOnline = CoreApp.isOnline(); + this.onlineObserver = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { - this.isOnline = CoreApp.instance.isOnline(); + NgZone.run(() => { + this.isOnline = CoreApp.isOnline(); }); }); @@ -155,7 +155,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes if (scrollTo) { // Scroll to the post. setTimeout(() => { - CoreDomUtils.instance.scrollToElementBySelector( + CoreDomUtils.scrollToElementBySelector( this.elementRef.nativeElement, this.content, '#addon-mod_forum-post-' + scrollTo, @@ -181,33 +181,33 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes // Refresh data if this discussion is synchronized automatically. this.syncObserver = CoreEvents.on(AddonModForumSyncProvider.AUTO_SYNCED, data => { if (data.forumId == this.forumId && this.discussionId == data.discussionId - && data.userId == CoreSites.instance.getCurrentSiteUserId()) { + && data.userId == CoreSites.getCurrentSiteUserId()) { // Refresh the data. this.discussionLoaded = false; this.refreshPosts(); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); // Refresh data if this forum discussion is synchronized from discussions list. this.syncManualObserver = CoreEvents.on(AddonModForumSyncProvider.MANUAL_SYNCED, data => { if (data.source != 'discussion' && data.forumId == this.forumId && - data.userId == CoreSites.instance.getCurrentSiteUserId()) { + data.userId == CoreSites.getCurrentSiteUserId()) { // Refresh the data. this.discussionLoaded = false; this.refreshPosts(); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); // Invalidate discussion list if it was not read. if (this.discussion.numunread > 0) { - AddonModForum.instance.invalidateDiscussionsList(this.forumId); + AddonModForum.invalidateDiscussionsList(this.forumId); } // @todo Listen for offline ratings saved and synced. this.changeDiscObserver = CoreEvents.on(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data => { if ((this.forumId && this.forumId === data.forumId) || data.cmId === this.cmId) { - AddonModForum.instance.invalidateDiscussionsList(this.forumId).finally(() => { + AddonModForum.invalidateDiscussionsList(this.forumId).finally(() => { if (typeof data.locked != 'undefined') { this.discussion.locked = data.locked; } @@ -221,9 +221,9 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes if (typeof data.deleted != 'undefined' && data.deleted) { if (!data.post?.parentid) { if (this.splitView?.outletActivated) { - CoreNavigator.instance.navigate('../'); + CoreNavigator.navigate('../'); } else { - CoreNavigator.instance.back(); + CoreNavigator.back(); } } else { this.discussionLoaded = false; @@ -241,13 +241,13 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes * @return Resolved if we can leave it, rejected if not. */ async canLeave(): Promise { - if (AddonModForumHelper.instance.hasPostDataChanged(this.replyData, this.originalData)) { + if (AddonModForumHelper.hasPostDataChanged(this.replyData, this.originalData)) { // Show confirmation if some data has been modified. - await CoreDomUtils.instance.showConfirm(Translate.instant('core.confirmcanceledit')); + await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); } // Delete the local files from the tmp folder. - CoreFileUploader.instance.clearTmpFiles(this.replyData.files); + CoreFileUploader.clearTmpFiles(this.replyData.files); this.leavingPage = true; @@ -280,12 +280,12 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes */ protected async getUserSort(): Promise { try { - const value = await CoreSites.instance.getCurrentSite()!.getLocalSiteConfig('AddonModForumDiscussionSort'); + const value = await CoreSites.getCurrentSite()!.getLocalSiteConfig('AddonModForumDiscussionSort'); return value; } catch (error) { try { - const value = await CoreUser.instance.getUserPreference('forum_displaymode'); + const value = await CoreUser.getUserPreference('forum_displaymode'); switch (Number(value)) { case 1: @@ -314,11 +314,11 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes */ protected fetchForum(): Promise { if (this.courseId && this.cmId) { - return AddonModForum.instance.getForum(this.courseId, this.cmId); + return AddonModForum.getForum(this.courseId, this.cmId); } if (this.courseId && this.forumId) { - return AddonModForum.instance.getForumById(this.courseId, this.forumId); + return AddonModForum.getForumById(this.courseId, this.forumId); } throw new Error('Cannot get the forum'); @@ -340,11 +340,11 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes try { if (sync) { // Try to synchronize the forum. - await CoreUtils.instance.ignoreErrors(this.syncDiscussion(!!showErrors)); + await CoreUtils.ignoreErrors(this.syncDiscussion(!!showErrors)); } - const response = await AddonModForum.instance.getDiscussionPosts(this.discussionId, { cmId: this.cmId }); - const replies = await AddonModForumOffline.instance.getDiscussionReplies(this.discussionId); + const response = await AddonModForum.getDiscussionPosts(this.discussionId, { cmId: this.cmId }); + const replies = await AddonModForumOffline.getDiscussionReplies(this.discussionId); const ratingInfo = response.ratinginfo; onlinePosts = response.posts; this.courseId = response.courseid || this.courseId; @@ -387,23 +387,23 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes await Promise.all(convertPromises); // Convert back to array. - onlinePosts = CoreUtils.instance.objectToArray(onlinePostsMap); + onlinePosts = CoreUtils.objectToArray(onlinePostsMap); let posts = offlineReplies.concat(onlinePosts); - this.startingPost = AddonModForum.instance.extractStartingPost(posts); + this.startingPost = AddonModForum.extractStartingPost(posts); // If sort type is nested, normal sorting is disabled and nested posts will be displayed. if (this.sort == 'nested') { // Sort first by creation date to make format tree work. - AddonModForum.instance.sortDiscussionPosts(posts, 'ASC'); + AddonModForum.sortDiscussionPosts(posts, 'ASC'); const rootId = this.startingPost ? this.startingPost.id : (this.discussion ? this.discussion.id : 0); - posts = CoreUtils.instance.formatTree(posts, 'parentid', 'id', rootId); + posts = CoreUtils.formatTree(posts, 'parentid', 'id', rootId); } else { // Set default reply subject. const direction = this.sort == 'flat-newest' ? 'DESC' : 'ASC'; - AddonModForum.instance.sortDiscussionPosts(posts, direction); + AddonModForum.sortDiscussionPosts(posts, direction); } try { @@ -418,7 +418,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes this.cmId = forum.cmid; this.courseId = forum.course; this.forum = forum; - this.availabilityMessage = AddonModForumHelper.instance.getAvailabilityMessage(forum); + this.availabilityMessage = AddonModForumHelper.getAvailabilityMessage(forum); const promises: Promise[] = []; @@ -430,7 +430,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes // Disallow replying if cut-off date is reached and the user has not the capability to override it. // Just in case the posts were fetched from WS when the cut-off date was not reached but it is now. - if (AddonModForumHelper.instance.isCutoffDateReached(forum) && !accessInfo.cancanoverridecutoff) { + if (AddonModForumHelper.isCutoffDateReached(forum) && !accessInfo.cancanoverridecutoff) { posts.forEach((post) => { post.capabilities.reply = false; }); @@ -474,10 +474,10 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes : {}, ); - if (AddonModForum.instance.isSetPinStateAvailableForSite()) { + if (AddonModForum.isSetPinStateAvailableForSite()) { // Use the canAddDiscussion WS to check if the user can pin discussions. try { - const response = await AddonModForum.instance.canAddDiscussionToAll(this.forumId, { cmId: this.cmId }); + const response = await AddonModForum.canAddDiscussionToAll(this.forumId, { cmId: this.cmId }); this.canPin = !!response.canpindiscussions; } catch (error) { @@ -489,7 +489,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes // @todo fetch hasOfflineRatings. } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { this.discussionLoaded = true; this.refreshIcon = 'refresh'; @@ -497,14 +497,14 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes if (forceMarkAsRead || (hasUnreadPosts && this.trackPosts)) { // // Add log in Moodle and mark unread posts as readed. - AddonModForum.instance.logDiscussionView(this.discussionId, this.forumId || -1, this.forum.name).catch(() => { + AddonModForum.logDiscussionView(this.discussionId, this.forumId || -1, this.forum.name).catch(() => { // Ignore errors. }).finally(() => { // Trigger mark read posts. CoreEvents.trigger(AddonModForumProvider.MARK_READ_EVENT, { courseId: this.courseId, moduleId: this.cmId, - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); }); } } @@ -525,7 +525,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes } try { - const discussion = await AddonModForumHelper.instance.getDiscussionById(forumId, cmId, discussionId); + const discussion = await AddonModForumHelper.getDiscussionById(forumId, cmId, discussionId); this.discussion = discussion; this.discussionId = this.discussion.discussion; @@ -548,16 +548,16 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes .syncDiscussionReplies(this.discussionId) .then((result) => { if (result.warnings && result.warnings.length) { - CoreDomUtils.instance.showErrorModal(result.warnings[0]); + CoreDomUtils.showErrorModal(result.warnings[0]); } if (result && result.updated) { // Sync successful, send event. CoreEvents.trigger(AddonModForumSyncProvider.MANUAL_SYNCED, { forumId: this.forumId, - userId: CoreSites.instance.getCurrentSiteUserId(), + userId: CoreSites.getCurrentSiteUserId(), source: 'discussion', - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } return; @@ -569,7 +569,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes .syncRatings(this.cmId, this.discussionId) .then((result) => { if (result.warnings && result.warnings.length) { - CoreDomUtils.instance.showErrorModal(result.warnings[0]); + CoreDomUtils.showErrorModal(result.warnings[0]); } return; @@ -580,7 +580,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes await Promise.all(promises); } catch (error) { if (showErrors) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errorsync', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errorsync', true); } throw new Error('Failed syncing discussion'); @@ -617,13 +617,13 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes this.syncIcon = 'spinner'; const promises = [ - AddonModForum.instance.invalidateForumData(this.courseId), - AddonModForum.instance.invalidateDiscussionPosts(this.discussionId, this.forumId), - AddonModForum.instance.invalidateAccessInformation(this.forumId), - AddonModForum.instance.invalidateCanAddDiscussion(this.forumId), + AddonModForum.invalidateForumData(this.courseId), + AddonModForum.invalidateDiscussionPosts(this.discussionId, this.forumId), + AddonModForum.invalidateAccessInformation(this.forumId), + AddonModForum.invalidateCanAddDiscussion(this.forumId), ]; - return CoreUtils.instance.allPromises(promises).catch(() => { + return CoreUtils.allPromises(promises).catch(() => { // Ignore errors. }).then(() => this.fetchPosts(sync, showErrors)); } @@ -637,7 +637,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes changeSort(type: SortType): Promise { this.discussionLoaded = false; this.sort = type; - CoreSites.instance.getCurrentSite()!.setLocalSiteConfig('AddonModForumDiscussionSort', this.sort); + CoreSites.getCurrentSite()!.setLocalSiteConfig('AddonModForumDiscussionSort', this.sort); this.content.scrollToTop(); return this.fetchPosts(); @@ -649,10 +649,10 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes * @param locked True to lock the discussion, false to unlock. */ async setLockState(locked: boolean): Promise { - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - const response = await AddonModForum.instance.setLockState(this.forumId, this.discussionId, locked); + const response = await AddonModForum.setLockState(this.forumId, this.discussionId, locked); this.discussion.locked = response.locked; const data = { @@ -661,11 +661,11 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes cmId: this.cmId, locked: this.discussion.locked, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.instance.getCurrentSiteId()); + CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); - CoreDomUtils.instance.showToast('addon.mod_forum.lockupdated', true); + CoreDomUtils.showToast('addon.mod_forum.lockupdated', true); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { modal.dismiss(); } @@ -677,10 +677,10 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes * @param pinned True to pin the discussion, false to unpin it. */ async setPinState(pinned: boolean): Promise { - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - await AddonModForum.instance.setPinState(this.discussionId, pinned); + await AddonModForum.setPinState(this.discussionId, pinned); this.discussion.pinned = pinned; @@ -690,11 +690,11 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes cmId: this.cmId, pinned: this.discussion.pinned, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.instance.getCurrentSiteId()); + CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); - CoreDomUtils.instance.showToast('addon.mod_forum.pinupdated', true); + CoreDomUtils.showToast('addon.mod_forum.pinupdated', true); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { modal.dismiss(); } @@ -706,10 +706,10 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes * @param starred True to star the discussion, false to unstar it. */ async toggleFavouriteState(starred: boolean): Promise { - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - await AddonModForum.instance.toggleFavouriteState(this.discussionId, starred); + await AddonModForum.toggleFavouriteState(this.discussionId, starred); this.discussion.starred = starred; @@ -719,11 +719,11 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes cmId: this.cmId, starred: this.discussion.starred, }; - CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.instance.getCurrentSiteId()); + CoreEvents.trigger(AddonModForumProvider.CHANGE_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); - CoreDomUtils.instance.showToast('addon.mod_forum.favouriteupdated', true); + CoreDomUtils.showToast('addon.mod_forum.favouriteupdated', true); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { modal.dismiss(); } @@ -739,7 +739,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes discussionId: this.discussionId, cmId: this.cmId, }; - CoreEvents.trigger(AddonModForumProvider.REPLY_DISCUSSION_EVENT, data, CoreSites.instance.getCurrentSiteId()); + CoreEvents.trigger(AddonModForumProvider.REPLY_DISCUSSION_EVENT, data, CoreSites.getCurrentSiteId()); this.discussionLoaded = false; this.refreshPosts().finally(() => { diff --git a/src/addons/mod/forum/pages/index/index.ts b/src/addons/mod/forum/pages/index/index.ts index d4c0737e8..c36a76073 100644 --- a/src/addons/mod/forum/pages/index/index.ts +++ b/src/addons/mod/forum/pages/index/index.ts @@ -32,8 +32,8 @@ export class AddonModForumIndexPage implements OnInit { * @inheritdoc */ ngOnInit(): void { - this.module = CoreNavigator.instance.getRouteParam('module')!; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; + this.module = CoreNavigator.getRouteParam('module')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; this.title = this.module?.name; } diff --git a/src/addons/mod/forum/pages/new-discussion/new-discussion.page.ts b/src/addons/mod/forum/pages/new-discussion/new-discussion.page.ts index e813bb990..5fa1376bb 100644 --- a/src/addons/mod/forum/pages/new-discussion/new-discussion.page.ts +++ b/src/addons/mod/forum/pages/new-discussion/new-discussion.page.ts @@ -102,10 +102,10 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea * Component being initialized. */ ngOnInit(): void { - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.cmId = CoreNavigator.instance.getRouteNumberParam('cmId')!; - this.forumId = CoreNavigator.instance.getRouteNumberParam('forumId')!; - this.timeCreated = CoreNavigator.instance.getRouteNumberParam('timeCreated')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.cmId = CoreNavigator.getRouteNumberParam('cmId')!; + this.forumId = CoreNavigator.getRouteNumberParam('forumId')!; + this.timeCreated = CoreNavigator.getRouteNumberParam('timeCreated')!; this.fetchDiscussionData().finally(() => { this.groupsLoaded = true; @@ -123,11 +123,11 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea // Refresh data if this discussion is synchronized automatically. this.syncObserver = CoreEvents.on(AddonModForumSyncProvider.AUTO_SYNCED, data => { - if (data.forumId == this.forumId && data.userId == CoreSites.instance.getCurrentSiteUserId()) { - CoreDomUtils.instance.showAlertTranslated('core.notice', 'core.contenteditingsynced'); + if (data.forumId == this.forumId && data.userId == CoreSites.getCurrentSiteUserId()) { + CoreDomUtils.showAlertTranslated('core.notice', 'core.contenteditingsynced'); this.returnToDiscussions(); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } /** @@ -138,7 +138,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea */ protected async fetchDiscussionData(refresh?: boolean): Promise { try { - const mode = await CoreGroups.instance.getActivityGroupMode(this.cmId); + const mode = await CoreGroups.getActivityGroupMode(this.cmId); const promises: Promise[] = []; if (mode === CoreGroupsProvider.SEPARATEGROUPS || mode === CoreGroupsProvider.VISIBLEGROUPS) { @@ -183,7 +183,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea // Use the canAddDiscussion WS to check if the user can add attachments and pin discussions. promises.push( - CoreUtils.instance.ignoreErrors( + CoreUtils.ignoreErrors( AddonModForum.instance .canAddDiscussionToAll(this.forumId, { cmId: this.cmId }) .then((response) => { @@ -197,7 +197,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea } // Get forum. - promises.push(AddonModForum.instance.getForum(this.courseId, this.cmId).then((forum) => this.forum = forum)); + promises.push(AddonModForum.getForum(this.courseId, this.cmId).then((forum) => this.forum = forum)); // Get access information. promises.push( @@ -210,12 +210,12 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea // If editing a discussion, get offline data. if (this.timeCreated && !refresh) { - this.syncId = AddonModForumSync.instance.getForumSyncId(this.forumId); + this.syncId = AddonModForumSync.getForumSyncId(this.forumId); - await AddonModForumSync.instance.waitForSync(this.syncId).then(() => { + await AddonModForumSync.waitForSync(this.syncId).then(() => { // Do not block if the scope is already destroyed. if (!this.isDestroyed) { - CoreSync.instance.blockOperation(AddonModForumProvider.COMPONENT, this.syncId); + CoreSync.blockOperation(AddonModForumProvider.COMPONENT, this.syncId); } // eslint-disable-next-line promise/no-nesting @@ -239,7 +239,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea // Treat offline attachments if any. if (typeof discussion.options.attachmentsid === 'object' && discussion.options.attachmentsid.offline) { - const files = await AddonModForumHelper.instance.getNewDiscussionStoredFiles( + const files = await AddonModForumHelper.getNewDiscussionStoredFiles( this.forumId, this.timeCreated, ); @@ -274,7 +274,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea this.showForm = true; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_forum.errorgetgroups', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_forum.errorgetgroups', true); this.showForm = false; } @@ -291,7 +291,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea // We first check if the user can post to all the groups. try { - response = await AddonModForum.instance.canAddDiscussionToAll(this.forumId, { cmId: this.cmId }); + response = await AddonModForum.canAddDiscussionToAll(this.forumId, { cmId: this.cmId }); } catch (error) { // The call failed, let's assume he can't. response = { @@ -358,7 +358,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea * @return Promise resolved with the list of groups. */ protected addAllParticipantsOption(groups: CoreGroup[], check: boolean): Promise { - if (!AddonModForum.instance.isAllParticipantsFixed()) { + if (!AddonModForum.isAllParticipantsFixed()) { // All participants has a bug, don't add it. return Promise.resolve(groups); } @@ -367,7 +367,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea if (check) { // We need to check if the user can add a discussion to all participants. - promise = AddonModForum.instance.canAddDiscussionToAll(this.forumId, { cmId: this.cmId }).then((response) => { + promise = AddonModForum.canAddDiscussionToAll(this.forumId, { cmId: this.cmId }).then((response) => { this.canPin = !!response.canpindiscussions; this.canCreateAttachments = !!response.cancreateattachment; @@ -400,9 +400,9 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea */ refreshGroups(refresher?: IonRefresher): void { const promises = [ - CoreGroups.instance.invalidateActivityGroupMode(this.cmId), - CoreGroups.instance.invalidateActivityAllowedGroups(this.cmId), - AddonModForum.instance.invalidateCanAddDiscussion(this.forumId), + CoreGroups.invalidateActivityGroupMode(this.cmId), + CoreGroups.invalidateActivityAllowedGroups(this.cmId), + AddonModForum.invalidateCanAddDiscussion(this.forumId), ]; Promise.all(promises).finally(() => { @@ -422,7 +422,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea this.forceLeave = true; // Delete the local files from the tmp folder. - CoreFileUploader.instance.clearTmpFiles(this.newDiscussion.files); + CoreFileUploader.clearTmpFiles(this.newDiscussion.files); CoreEvents.trigger( AddonModForumProvider.NEW_DISCUSSION_EVENT, @@ -432,7 +432,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea discussionIds: discussionIds, discTimecreated: discTimecreated, }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); if (this.splitView?.outletActivated) { @@ -443,9 +443,9 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea this.newDiscussion.files = []; this.newDiscussion.postToAllGroups = false; this.messageEditor.clearText(); - this.originalData = CoreUtils.instance.clone(this.newDiscussion); + this.originalData = CoreUtils.clone(this.newDiscussion); } else { - CoreNavigator.instance.back(); + CoreNavigator.back(); } } @@ -473,20 +473,20 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea }; if (!subject) { - CoreDomUtils.instance.showErrorModal('addon.mod_forum.erroremptysubject', true); + CoreDomUtils.showErrorModal('addon.mod_forum.erroremptysubject', true); return; } if (!message) { - CoreDomUtils.instance.showErrorModal('addon.mod_forum.erroremptymessage', true); + CoreDomUtils.showErrorModal('addon.mod_forum.erroremptymessage', true); return; } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); // Add some HTML to the message if needed. - message = CoreTextUtils.instance.formatHtmlLines(message); + message = CoreTextUtils.formatHtmlLines(message); if (pin) { options.discussionpinned = true; @@ -495,7 +495,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea const groupIds = this.newDiscussion.postToAllGroups ? this.groupIds : [this.newDiscussion.groupId]; try { - const discussionIds = await AddonModForumHelper.instance.addNewDiscussion( + const discussionIds = await AddonModForumHelper.addNewDiscussion( this.forumId, forumName, this.courseId, @@ -509,25 +509,25 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea if (discussionIds) { // Data sent to server, delete stored files (if any). - AddonModForumHelper.instance.deleteNewDiscussionStoredFiles(this.forumId, discTimecreated); + AddonModForumHelper.deleteNewDiscussionStoredFiles(this.forumId, discTimecreated); CoreEvents.trigger(CoreEvents.ACTIVITY_DATA_SENT, { module: 'forum' }); } if (discussionIds && discussionIds.length < groupIds.length) { // Some discussions could not be created. - CoreDomUtils.instance.showErrorModalDefault(null, 'addon.mod_forum.errorposttoallgroups', true); + CoreDomUtils.showErrorModalDefault(null, 'addon.mod_forum.errorposttoallgroups', true); } - CoreDomUtils.instance.triggerFormSubmittedEvent( + CoreDomUtils.triggerFormSubmittedEvent( this.formElement, !!discussionIds, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); this.returnToDiscussions(discussionIds, discTimecreated); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_forum.cannotcreatediscussion', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_forum.cannotcreatediscussion', true); } finally { modal.dismiss(); } @@ -538,20 +538,20 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea */ async discard(): Promise { try { - await CoreDomUtils.instance.showConfirm(Translate.instant('core.areyousure')); + await CoreDomUtils.showConfirm(Translate.instant('core.areyousure')); const promises: Promise[] = []; - promises.push(AddonModForumOffline.instance.deleteNewDiscussion(this.forumId, this.timeCreated)); + promises.push(AddonModForumOffline.deleteNewDiscussion(this.forumId, this.timeCreated)); promises.push( - CoreUtils.instance.ignoreErrors( - AddonModForumHelper.instance.deleteNewDiscussionStoredFiles(this.forumId, this.timeCreated), + CoreUtils.ignoreErrors( + AddonModForumHelper.deleteNewDiscussionStoredFiles(this.forumId, this.timeCreated), ), ); await Promise.all(promises); - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); this.returnToDiscussions(); } catch (error) { @@ -576,16 +576,16 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea return true; } - if (AddonModForumHelper.instance.hasPostDataChanged(this.newDiscussion, this.originalData)) { + if (AddonModForumHelper.hasPostDataChanged(this.newDiscussion, this.originalData)) { // Show confirmation if some data has been modified. - await CoreDomUtils.instance.showConfirm(Translate.instant('core.confirmcanceledit')); + await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); } // Delete the local files from the tmp folder. - CoreFileUploader.instance.clearTmpFiles(this.newDiscussion.files); + CoreFileUploader.clearTmpFiles(this.newDiscussion.files); if (this.formElement) { - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); } return true; @@ -604,7 +604,7 @@ export class AddonModForumNewDiscussionPage implements OnInit, OnDestroy, CanLea */ ngOnDestroy(): void { if (this.syncId) { - CoreSync.instance.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); + CoreSync.unblockOperation(AddonModForumProvider.COMPONENT, this.syncId); } this.isDestroyed = true; } diff --git a/src/addons/mod/forum/services/forum.ts b/src/addons/mod/forum/services/forum.ts index d3eabeaaf..87dd1bd02 100644 --- a/src/addons/mod/forum/services/forum.ts +++ b/src/addons/mod/forum/services/forum.ts @@ -195,14 +195,14 @@ export class AddonModForumProvider { groupId?: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModForumAddDiscussionWSParams = { forumid: forumId, subject: subject, message: message, // eslint-disable-next-line max-len - options: CoreUtils.instance.objectToArrayOfObjects( + options: CoreUtils.objectToArrayOfObjects( options || {}, 'name', 'value', @@ -243,10 +243,10 @@ export class AddonModForumProvider { cacheKey: this.getCanAddDiscussionCacheKey(forumId, groupId), component: AddonModForumProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const result = await site.read('mod_forum_can_add_discussion', params, preSets); if (!result) { @@ -288,7 +288,7 @@ export class AddonModForumProvider { * @since 3.8 */ async deletePost(postId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModForumDeletePostWSParams = { postid: postId, }; @@ -314,7 +314,7 @@ export class AddonModForumProvider { * @return True if fixed, false otherwise. */ isAllParticipantsFixed(): boolean { - return !!CoreSites.instance.getCurrentSite()?.isVersionGreaterEqualThan(['3.1.5', '3.2.2']); + return !!CoreSites.getCurrentSite()?.isVersionGreaterEqualThan(['3.1.5', '3.2.2']); } /** @@ -324,7 +324,7 @@ export class AddonModForumProvider { * @since 3.8 */ isGetDiscussionPostAvailable(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('mod_forum_get_discussion_post'); + return CoreSites.wsAvailableInCurrentSite('mod_forum_get_discussion_post'); } /** @@ -337,7 +337,7 @@ export class AddonModForumProvider { isGetDiscussionPostsAvailable(site?: CoreSite): boolean { return site ? site.wsAvailable('mod_forum_get_discussion_posts') - : CoreSites.instance.wsAvailableInCurrentSite('mod_forum_get_discussion_posts'); + : CoreSites.wsAvailableInCurrentSite('mod_forum_get_discussion_posts'); } /** @@ -347,7 +347,7 @@ export class AddonModForumProvider { * @since 3.8 */ isDeletePostAvailable(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('mod_forum_delete_post'); + return CoreSites.wsAvailableInCurrentSite('mod_forum_delete_post'); } /** @@ -357,7 +357,7 @@ export class AddonModForumProvider { * @since 3.8 */ isUpdatePostAvailable(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('mod_forum_update_discussion_post'); + return CoreSites.wsAvailableInCurrentSite('mod_forum_update_discussion_post'); } /** @@ -373,9 +373,9 @@ export class AddonModForumProvider { cmId: number, discussions: AddonModForumDiscussion[] | AddonModForumOfflineDiscussion[], ): Promise { - discussions = CoreUtils.instance.clone(discussions); + discussions = CoreUtils.clone(discussions); - return CoreGroups.instance.getActivityAllowedGroups(cmId).then((result) => { + return CoreGroups.getActivityAllowedGroups(cmId).then((result) => { const strAllParts = Translate.instant('core.allparticipants'); const strAllGroups = Translate.instant('core.allgroups'); @@ -412,7 +412,7 @@ export class AddonModForumProvider { * @return Promise resolved when the forums are retrieved. */ async getCourseForums(courseId: number, options: CoreSitesCommonWSOptions = {}): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModForumGetForumsByCoursesWSParams = { courseids: [courseId], @@ -421,7 +421,7 @@ export class AddonModForumProvider { cacheKey: this.getForumDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModForumProvider.COMPONENT, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; return site.read('mod_forum_get_forums_by_courses', params, preSets); @@ -442,7 +442,7 @@ export class AddonModForumProvider { postId: number, options: CoreCourseCommonModWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModForumGetDiscussionPostWSParams = { postid: postId, }; @@ -451,7 +451,7 @@ export class AddonModForumProvider { updateFrequency: CoreSite.FREQUENCY_USUALLY, component: AddonModForumProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read( @@ -518,7 +518,7 @@ export class AddonModForumProvider { forumId: number, options: CoreCourseCommonModWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); if (!site.wsAvailable('mod_forum_get_forum_access_information')) { // Access information not available for 3.6 or older sites. @@ -532,7 +532,7 @@ export class AddonModForumProvider { cacheKey: this.getAccessInformationCacheKey(forumId), component: AddonModForumProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read( @@ -602,10 +602,10 @@ export class AddonModForumProvider { cacheKey: this.getDiscussionPostsCacheKey(discussionId), component: AddonModForumProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const isGetDiscussionPostsAvailable = this.isGetDiscussionPostsAvailable(site); const response = isGetDiscussionPostsAvailable @@ -663,7 +663,7 @@ export class AddonModForumProvider { * @return True if discussion lists can be sorted. */ isDiscussionListSortingAvailable(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.isVersionGreaterEqualThan('3.7'); } @@ -726,7 +726,7 @@ export class AddonModForumProvider { options.sortOrder = options.sortOrder || AddonModForumProvider.SORTORDER_LASTPOST_DESC; options.page = options.page || 0; - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); let method = 'mod_forum_get_forum_discussions_paginated'; const params: AddonModForumGetForumDiscussionsPaginatedWSParams | AddonModForumGetForumDiscussionsWSParams = { forumid: forumId, @@ -751,7 +751,7 @@ export class AddonModForumProvider { cacheKey: this.getDiscussionsListCacheKey(forumId, options.sortOrder), component: AddonModForumProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; let response: AddonModForumGetForumDiscussionsPaginatedWSResponse | AddonModForumGetForumDiscussionsWSResponse; @@ -765,7 +765,7 @@ export class AddonModForumProvider { } catch (error) { // Try to get the data from cache stored with the old WS method. if ( - CoreApp.instance.isOnline() || + CoreApp.isOnline() || method !== 'mod_forum_get_forum_discussions' || options.sortOrder !== AddonModForumProvider.SORTORDER_LASTPOST_DESC ) { @@ -779,7 +779,7 @@ export class AddonModForumProvider { sortby: 'timemodified', sortdirection: 'DESC', }; - Object.assign(preSets, CoreSites.instance.getReadingStrategyPreSets(CoreSitesReadingStrategy.PreferCache)); + Object.assign(preSets, CoreSites.getReadingStrategyPreSets(CoreSitesReadingStrategy.PreferCache)); response = await site.read( 'mod_forum_get_forum_discussions_paginated', @@ -861,7 +861,7 @@ export class AddonModForumProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCanAddDiscussion(forumId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getCommonCanAddDiscussionCacheKey(forumId)); } @@ -901,16 +901,16 @@ export class AddonModForumProvider { promises.push(this.invalidateDiscussionPosts(discussion.discussion, forum.id)); }); - return CoreUtils.instance.allPromises(promises); + return CoreUtils.allPromises(promises); }), ); }); if (this.isDiscussionListSortingAvailable()) { - promises.push(CoreUser.instance.invalidateUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER)); + promises.push(CoreUser.invalidateUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER)); } - return CoreUtils.instance.allPromises(promises); + return CoreUtils.allPromises(promises); } /** @@ -921,7 +921,7 @@ export class AddonModForumProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAccessInformation(forumId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAccessInformationCacheKey(forumId)); } @@ -935,14 +935,14 @@ export class AddonModForumProvider { * @return Promise resolved when the data is invalidated. */ async invalidateDiscussionPosts(discussionId: number, forumId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const promises = [site.invalidateWsCacheForKey(this.getDiscussionPostsCacheKey(discussionId))]; if (forumId) { promises.push(site.invalidateWsCacheForKeyStartingWith(this.getForumDiscussionDataCacheKey(forumId, discussionId))); } - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); } /** @@ -953,9 +953,9 @@ export class AddonModForumProvider { * @return Promise resolved when the data is invalidated. */ async invalidateDiscussionsList(forumId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - await CoreUtils.instance.allPromises( + await CoreUtils.allPromises( this.getAvailableSortOrders() .map(sortOrder => site.invalidateWsCacheForKey(this.getDiscussionsListCacheKey(forumId, sortOrder.value))), ); @@ -968,9 +968,9 @@ export class AddonModForumProvider { * @return Promise resolved when the files are invalidated. */ async invalidateFiles(moduleId: number): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); - await CoreFilepool.instance.invalidateFilesByComponent(siteId, AddonModForumProvider.COMPONENT, moduleId); + await CoreFilepool.invalidateFilesByComponent(siteId, AddonModForumProvider.COMPONENT, moduleId); } /** @@ -980,7 +980,7 @@ export class AddonModForumProvider { * @return Promise resolved when the data is invalidated. */ async invalidateForumData(courseId: number): Promise { - const site = CoreSites.instance.getCurrentSite(); + const site = CoreSites.getCurrentSite(); await site?.invalidateWsCacheForKey(this.getForumDataCacheKey(courseId)); } @@ -998,7 +998,7 @@ export class AddonModForumProvider { forumid: id, }; - return CoreCourseLogHelper.instance.logSingle( + return CoreCourseLogHelper.logSingle( 'mod_forum_view_forum', params, AddonModForumProvider.COMPONENT, @@ -1024,7 +1024,7 @@ export class AddonModForumProvider { discussionid: id, }; - return CoreCourseLogHelper.instance.logSingle( + return CoreCourseLogHelper.logSingle( 'mod_forum_view_forum_discussion', params, AddonModForumProvider.COMPONENT, @@ -1063,7 +1063,7 @@ export class AddonModForumProvider { siteId?: string, allowOffline?: boolean, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Convenience function to store a message to be synchronized later. const storeOffline = async (): Promise => { @@ -1072,7 +1072,7 @@ export class AddonModForumProvider { throw new Error(Translate.instant('core.networkerrormsg')); } - await AddonModForumOffline.instance.replyPost( + await AddonModForumOffline.replyPost( postId, discussionId, forumId, @@ -1087,14 +1087,14 @@ export class AddonModForumProvider { return false; }; - if (!CoreApp.instance.isOnline() && allowOffline) { + if (!CoreApp.isOnline() && allowOffline) { // App is offline, store the action. return storeOffline(); } // If there's already a reply to be sent to the server, discard it first. try { - await AddonModForumOffline.instance.deleteReply(postId, siteId); + await AddonModForumOffline.deleteReply(postId, siteId); await this.replyPostOnline( postId, subject, @@ -1105,7 +1105,7 @@ export class AddonModForumProvider { return true; } catch (error) { - if (allowOffline && !CoreUtils.instance.isWebServiceError(error)) { + if (allowOffline && !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server, store in offline. return storeOffline(); } else { @@ -1132,13 +1132,13 @@ export class AddonModForumProvider { options?: AddonModForumAddDiscussionPostWSOptionsObject, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModForumAddDiscussionPostWSParams = { postid: postId, subject: subject, message: message, - options: CoreUtils.instance.objectToArrayOfObjects< + options: CoreUtils.objectToArrayOfObjects< AddonModForumAddDiscussionPostWSOptionsArray[0], AddonModForumAddDiscussionPostWSOptionsObject >( @@ -1173,7 +1173,7 @@ export class AddonModForumProvider { locked: boolean, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModForumSetLockStateWSParams = { forumid: forumId, discussionid: discussionId, @@ -1191,7 +1191,7 @@ export class AddonModForumProvider { * @since 3.7 */ isSetPinStateAvailableForSite(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('mod_forum_set_pin_state'); + return CoreSites.wsAvailableInCurrentSite('mod_forum_set_pin_state'); } /** @@ -1204,7 +1204,7 @@ export class AddonModForumProvider { * @since 3.7 */ async setPinState(discussionId: number, pinned: boolean, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModForumSetPinStateWSParams = { discussionid: discussionId, targetstate: pinned ? 1 : 0, @@ -1223,7 +1223,7 @@ export class AddonModForumProvider { * @since 3.7 */ async toggleFavouriteState(discussionId: number, starred: boolean, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModForumToggleFavouriteStateWSParams = { discussionid: discussionId, targetstate: starred, @@ -1269,7 +1269,7 @@ export class AddonModForumProvider { } }); - CoreUser.instance.storeUsers(CoreUtils.instance.objectToArray(users)); + CoreUser.storeUsers(CoreUtils.objectToArray(users)); } /** @@ -1289,13 +1289,13 @@ export class AddonModForumProvider { options?: AddonModForumUpdateDiscussionPostWSOptionsObject, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModForumUpdateDiscussionPostWSParams = { postid: postId, subject: subject, message: message, - options: CoreUtils.instance.objectToArrayOfObjects< + options: CoreUtils.objectToArrayOfObjects< AddonModForumUpdateDiscussionPostWSOptionsArray[0], AddonModForumUpdateDiscussionPostWSOptionsObject >( @@ -1320,7 +1320,7 @@ export class AddonModForumProvider { protected translateWSPost(post: AddonModForumWSPost): AddonModForumPost { (post as unknown as AddonModForumPost).tags = (post.tags || []).map((tag) => { const viewUrl = (tag.urls && tag.urls.view) || ''; - const params = CoreUrlUtils.instance.extractUrlParams(viewUrl); + const params = CoreUrlUtils.extractUrlParams(viewUrl); return { id: tag.tagid, @@ -1339,7 +1339,7 @@ export class AddonModForumProvider { } -export class AddonModForum extends makeSingleton(AddonModForumProvider) {} +export const AddonModForum = makeSingleton(AddonModForumProvider); /** * Params of mod_forum_get_forums_by_courses WS. diff --git a/src/addons/mod/forum/services/handlers/discussion-link.ts b/src/addons/mod/forum/services/handlers/discussion-link.ts index bc4dc5d2a..245d7c558 100644 --- a/src/addons/mod/forum/services/handlers/discussion-link.ts +++ b/src/addons/mod/forum/services/handlers/discussion-link.ts @@ -69,7 +69,7 @@ export class AddonModForumDiscussionLinkHandlerService extends CoreContentLinksH pageParams.parent = parseInt(params.parent); } - CoreNavigator.instance.navigateToSitePath( + CoreNavigator.navigateToSitePath( `${AddonModForumModuleHandlerService.PAGE_NAME}/discussion/${discussionId}`, { siteId, params: pageParams }, ); @@ -93,4 +93,4 @@ export class AddonModForumDiscussionLinkHandlerService extends CoreContentLinksH } -export class AddonModForumDiscussionLinkHandler extends makeSingleton(AddonModForumDiscussionLinkHandlerService) {} +export const AddonModForumDiscussionLinkHandler = makeSingleton(AddonModForumDiscussionLinkHandlerService); diff --git a/src/addons/mod/forum/services/handlers/index-link.ts b/src/addons/mod/forum/services/handlers/index-link.ts index b15d728bb..bf21b8313 100644 --- a/src/addons/mod/forum/services/handlers/index-link.ts +++ b/src/addons/mod/forum/services/handlers/index-link.ts @@ -30,4 +30,4 @@ export class AddonModForumIndexLinkHandlerService extends CoreContentLinksModule } -export class AddonModForumIndexLinkHandler extends makeSingleton(AddonModForumIndexLinkHandlerService) {} +export const AddonModForumIndexLinkHandler = makeSingleton(AddonModForumIndexLinkHandlerService); diff --git a/src/addons/mod/forum/services/handlers/list-link.ts b/src/addons/mod/forum/services/handlers/list-link.ts index 6338c88e0..ff75a9cc6 100644 --- a/src/addons/mod/forum/services/handlers/list-link.ts +++ b/src/addons/mod/forum/services/handlers/list-link.ts @@ -30,4 +30,4 @@ export class AddonModForumListLinkHandlerService extends CoreContentLinksModuleL } -export class AddonModForumListLinkHandler extends makeSingleton(AddonModForumListLinkHandlerService) {} +export const AddonModForumListLinkHandler = makeSingleton(AddonModForumListLinkHandlerService); diff --git a/src/addons/mod/forum/services/handlers/module.ts b/src/addons/mod/forum/services/handlers/module.ts index 8df24e921..de1116bde 100644 --- a/src/addons/mod/forum/services/handlers/module.ts +++ b/src/addons/mod/forum/services/handlers/module.ts @@ -69,7 +69,7 @@ export class AddonModForumModuleHandlerService implements CoreCourseModuleHandle */ getData(module: CoreCourseAnyModuleData, courseId: number): CoreCourseModuleHandlerData { const data: CoreCourseModuleHandlerData = { - icon: CoreCourse.instance.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), + icon: CoreCourse.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), title: module.name, class: 'addon-mod_forum-handler', showDownloadButton: true, @@ -78,7 +78,7 @@ export class AddonModForumModuleHandlerService implements CoreCourseModuleHandle options.params = options.params || {}; Object.assign(options.params, { module }); - CoreNavigator.instance.navigateToSitePath( + CoreNavigator.navigateToSitePath( `${AddonModForumModuleHandlerService.PAGE_NAME}/${courseId}/${module.id}`, options, ); @@ -88,7 +88,7 @@ export class AddonModForumModuleHandlerService implements CoreCourseModuleHandle if ('afterlink' in module && !!module.afterlink) { data.extraBadgeColor = ''; const match = />(\d+)[^<]+/.exec(module.afterlink); - data.extraBadge = match ? Translate.instance.instant('addon.mod_forum.unreadpostsnumber', { $a : match[1] }) : ''; + data.extraBadge = match ? Translate.instant('addon.mod_forum.unreadpostsnumber', { $a : match[1] }) : ''; } else { this.updateExtraBadge(data, courseId, module.id); } @@ -102,7 +102,7 @@ export class AddonModForumModuleHandlerService implements CoreCourseModuleHandle this.updateExtraBadge(data, eventData.courseId, eventData.moduleId, eventData.siteId); }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); data.onDestroy = () => event.off(); @@ -139,24 +139,24 @@ export class AddonModForumModuleHandlerService implements CoreCourseModuleHandle * @param siteId Site ID. If not defined, current site. */ async updateExtraBadge(data: CoreCourseModuleHandlerData, courseId: number, moduleId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!siteId) { return; } - data.extraBadge = Translate.instance.instant('core.loading'); + data.extraBadge = Translate.instant('core.loading'); data.extraBadgeColor = 'light'; - await CoreUtils.instance.ignoreErrors(AddonModForum.instance.invalidateForumData(courseId)); + await CoreUtils.ignoreErrors(AddonModForum.invalidateForumData(courseId)); try { // Handle unread posts. - const forum = await AddonModForum.instance.getForum(courseId, moduleId, { siteId }); + const forum = await AddonModForum.getForum(courseId, moduleId, { siteId }); data.extraBadgeColor = ''; data.extraBadge = forum.unreadpostscount - ? Translate.instance.instant( + ? Translate.instant( 'addon.mod_forum.unreadpostsnumber', { $a : forum.unreadpostscount }, ) @@ -170,4 +170,4 @@ export class AddonModForumModuleHandlerService implements CoreCourseModuleHandle } -export class AddonModForumModuleHandler extends makeSingleton(AddonModForumModuleHandlerService) {} +export const AddonModForumModuleHandler = makeSingleton(AddonModForumModuleHandlerService); diff --git a/src/addons/mod/forum/services/handlers/post-link.ts b/src/addons/mod/forum/services/handlers/post-link.ts index 4a4e9bf61..7aa3042f3 100644 --- a/src/addons/mod/forum/services/handlers/post-link.ts +++ b/src/addons/mod/forum/services/handlers/post-link.ts @@ -49,13 +49,13 @@ export class AddonModForumPostLinkHandlerService extends CoreContentLinksHandler ): CoreContentLinksAction[] | Promise { return [{ action: async (siteId): Promise => { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); const forumId = parseInt(params.forum, 10); try { - const module = await CoreCourse.instance.getModuleBasicInfoByInstance(forumId, 'forum', siteId); + const module = await CoreCourse.getModuleBasicInfoByInstance(forumId, 'forum', siteId); - await CoreNavigator.instance.navigateToSitePath( + await CoreNavigator.navigateToSitePath( `${AddonModForumModuleHandlerService.PAGE_NAME}/${module.course}/${module.id}/new/0`, { siteId, params: { forumId: module.instance } }, ); @@ -83,4 +83,4 @@ export class AddonModForumPostLinkHandlerService extends CoreContentLinksHandler } -export class AddonModForumPostLinkHandler extends makeSingleton(AddonModForumPostLinkHandlerService) {} +export const AddonModForumPostLinkHandler = makeSingleton(AddonModForumPostLinkHandlerService); diff --git a/src/addons/mod/forum/services/handlers/prefetch.ts b/src/addons/mod/forum/services/handlers/prefetch.ts index 858856133..0688a5747 100644 --- a/src/addons/mod/forum/services/handlers/prefetch.ts +++ b/src/addons/mod/forum/services/handlers/prefetch.ts @@ -46,7 +46,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe */ async getFiles(module: CoreCourseAnyModuleData, courseId: number): Promise { try { - const forum = await AddonModForum.instance.getForum(courseId, module.id); + const forum = await AddonModForum.getForum(courseId, module.id); const files = this.getIntroFilesFromInstance(module, forum); @@ -71,7 +71,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe */ protected getPostsFiles(posts: AddonModForumPost[]): CoreWSExternalFile[] { let files: CoreWSExternalFile[] = []; - const getInlineFiles = CoreSites.instance.getCurrentSite()?.isVersionGreaterEqualThan('3.2'); + const getInlineFiles = CoreSites.getCurrentSite()?.isVersionGreaterEqualThan('3.2'); posts.forEach((post) => { if (post.attachments && post.attachments.length) { @@ -80,7 +80,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe if (getInlineFiles && post.messageinlinefiles && post.messageinlinefiles.length) { files = files.concat(post.messageinlinefiles); } else if (post.message && !getInlineFiles) { - files = files.concat(CoreFilepool.instance.extractDownloadableFilesFromHtmlAsFakeFileObjects(post.message)); + files = files.concat(CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(post.message)); } }); @@ -98,7 +98,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe forum: AddonModForumData, options: CoreCourseCommonModWSOptions = {}, ): Promise { - const promises = AddonModForum.instance.getAvailableSortOrders().map((sortOrder) => { + const promises = AddonModForum.getAvailableSortOrders().map((sortOrder) => { // Get discussions in first 2 pages. const discussionsOptions = { sortOrder: sortOrder.value, @@ -106,7 +106,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe ...options, // Include all options. }; - return AddonModForum.instance.getDiscussionsInPages(forum.id, discussionsOptions).then((response) => { + return AddonModForum.getDiscussionsInPages(forum.id, discussionsOptions).then((response) => { if (response.error) { throw new Error('Failed getting discussions'); } @@ -114,7 +114,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe const promises: Promise<{ posts: AddonModForumPost[] }>[] = []; response.discussions.forEach((discussion) => { - promises.push(AddonModForum.instance.getDiscussionPosts(discussion.discussion, options)); + promises.push(AddonModForum.getDiscussionPosts(discussion.discussion, options)); }); return Promise.all(promises); @@ -149,7 +149,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe * @return Promise resolved when the data is invalidated. */ invalidateContent(moduleId: number, courseId: number): Promise { - return AddonModForum.instance.invalidateContent(moduleId, courseId); + return AddonModForum.invalidateContent(moduleId, courseId); } /** @@ -164,8 +164,8 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe // Invalidate forum data to recalculate unread message count badge. const promises: Promise[] = []; - promises.push(AddonModForum.instance.invalidateForumData(courseId)); - promises.push(CoreCourse.instance.invalidateModule(module.id)); + promises.push(AddonModForum.invalidateForumData(courseId)); + promises.push(CoreCourse.invalidateModule(module.id)); await Promise.all(promises); } @@ -208,7 +208,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe }; // Get the forum data. - const forum = await AddonModForum.instance.getForum(courseId, module.id, commonOptions); + const forum = await AddonModForum.getForum(courseId, module.id, commonOptions); const promises: Promise[] = []; // Prefetch the posts. @@ -216,23 +216,23 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe const promises: Promise[] = []; const files = this.getIntroFilesFromInstance(module, forum).concat(this.getPostsFiles(posts)); - promises.push(CoreFilepool.instance.addFilesToQueue(siteId, files, this.component, module.id)); + promises.push(CoreFilepool.addFilesToQueue(siteId, files, this.component, module.id)); // Prefetch groups data. promises.push(this.prefetchGroupsInfo(forum, courseId, !!forum.cancreatediscussions, siteId)); // Prefetch avatars. - promises.push(CoreUser.instance.prefetchUserAvatars(posts, 'userpictureurl', siteId)); + promises.push(CoreUser.prefetchUserAvatars(posts, 'userpictureurl', siteId)); return Promise.all(promises); })); // Prefetch access information. - promises.push(AddonModForum.instance.getAccessInformation(forum.id, modOptions)); + promises.push(AddonModForum.getAccessInformation(forum.id, modOptions)); // Prefetch sort order preference. - if (AddonModForum.instance.isDiscussionListSortingAvailable()) { - promises.push(CoreUser.instance.getUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER, siteId)); + if (AddonModForum.isDiscussionListSortingAvailable()) { + promises.push(CoreUser.getUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER, siteId)); } await Promise.all(promises); @@ -260,28 +260,28 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe // Check group mode. try { - const mode = await CoreGroups.instance.getActivityGroupMode(forum.cmid, siteId); + const mode = await CoreGroups.getActivityGroupMode(forum.cmid, siteId); if (mode !== CoreGroupsProvider.SEPARATEGROUPS && mode !== CoreGroupsProvider.VISIBLEGROUPS) { // Activity doesn't use groups. Prefetch canAddDiscussionToAll to determine if user can pin/attach. - await CoreUtils.instance.ignoreErrors(AddonModForum.instance.canAddDiscussionToAll(forum.id, options)); + await CoreUtils.ignoreErrors(AddonModForum.canAddDiscussionToAll(forum.id, options)); return; } // Activity uses groups, prefetch allowed groups. - const result = await CoreGroups.instance.getActivityAllowedGroups(forum.cmid, undefined, siteId); + const result = await CoreGroups.getActivityAllowedGroups(forum.cmid, undefined, siteId); if (mode === CoreGroupsProvider.SEPARATEGROUPS) { // Groups are already filtered by WS. Prefetch canAddDiscussionToAll to determine if user can pin/attach. - await CoreUtils.instance.ignoreErrors(AddonModForum.instance.canAddDiscussionToAll(forum.id, options)); + await CoreUtils.ignoreErrors(AddonModForum.canAddDiscussionToAll(forum.id, options)); return; } if (canCreateDiscussions) { // Prefetch data to check the visible groups when creating discussions. - const response = await CoreUtils.instance.ignoreErrors( - AddonModForum.instance.canAddDiscussionToAll(forum.id, options), + const response = await CoreUtils.ignoreErrors( + AddonModForum.canAddDiscussionToAll(forum.id, options), { status: false }, ); @@ -293,8 +293,8 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe // The user can't post to all groups, let's check which groups he can post to. await Promise.all( result.groups.map( - async (group) => CoreUtils.instance.ignoreErrors( - AddonModForum.instance.canAddDiscussion(forum.id, group.id, options), + async (group) => CoreUtils.ignoreErrors( + AddonModForum.canAddDiscussion(forum.id, group.id, options), ), ), ); @@ -322,9 +322,9 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe ): Promise { const promises: Promise[] = []; - promises.push(AddonModForumSync.instance.syncForumDiscussions(module.instance!, undefined, siteId)); - promises.push(AddonModForumSync.instance.syncForumReplies(module.instance!, undefined, siteId)); - promises.push(AddonModForumSync.instance.syncRatings(module.id, undefined, true, siteId)); + promises.push(AddonModForumSync.syncForumDiscussions(module.instance!, undefined, siteId)); + promises.push(AddonModForumSync.syncForumReplies(module.instance!, undefined, siteId)); + promises.push(AddonModForumSync.syncRatings(module.id, undefined, true, siteId)); const results = await Promise.all(promises); @@ -342,7 +342,7 @@ export class AddonModForumPrefetchHandlerService extends CoreCourseActivityPrefe } -export class AddonModForumPrefetchHandler extends makeSingleton(AddonModForumPrefetchHandlerService) {} +export const AddonModForumPrefetchHandler = makeSingleton(AddonModForumPrefetchHandlerService); /** * Data returned by a forum sync. diff --git a/src/addons/mod/forum/services/handlers/push-click.ts b/src/addons/mod/forum/services/handlers/push-click.ts index 05e3f1dfc..c9f2efa8f 100644 --- a/src/addons/mod/forum/services/handlers/push-click.ts +++ b/src/addons/mod/forum/services/handlers/push-click.ts @@ -42,7 +42,7 @@ export class AddonModForumPushClickHandlerService implements CorePushNotificatio * @return Whether the notification click is handled by this handler */ async handles(notification: NotificationData): Promise { - return CoreUtils.instance.isTrueOrOne(notification.notif) + return CoreUtils.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'mod_forum' && notification.name == 'posts'; } @@ -54,7 +54,7 @@ export class AddonModForumPushClickHandlerService implements CorePushNotificatio * @return Promise resolved when done. */ async handleClick(notification: NotificationData): Promise { - const contextUrlParams = CoreUrlUtils.instance.extractUrlParams(notification.contexturl); + const contextUrlParams = CoreUrlUtils.extractUrlParams(notification.contexturl); const data = notification.customdata || {}; const courseId = Number(notification.courseid); const discussionId = Number(contextUrlParams.d || data.discussionid); @@ -67,11 +67,11 @@ export class AddonModForumPushClickHandlerService implements CorePushNotificatio pageParams.postId = Number(data.postid || contextUrlParams.urlHash.replace('p', '')); } - await CoreUtils.instance.ignoreErrors( - AddonModForum.instance.invalidateDiscussionPosts(pageParams.discussionId, undefined, notification.site), + await CoreUtils.ignoreErrors( + AddonModForum.invalidateDiscussionPosts(pageParams.discussionId, undefined, notification.site), ); - await CoreNavigator.instance.navigateToSitePath( + await CoreNavigator.navigateToSitePath( `${AddonModForumModuleHandlerService.PAGE_NAME}/${courseId}/${cmId}/${discussionId}`, { siteId: notification.site, params: pageParams }, ); @@ -79,7 +79,7 @@ export class AddonModForumPushClickHandlerService implements CorePushNotificatio } -export class AddonModForumPushClickHandler extends makeSingleton(AddonModForumPushClickHandlerService) {} +export const AddonModForumPushClickHandler = makeSingleton(AddonModForumPushClickHandlerService); type NotificationData = CorePushNotificationsNotificationBasicData & { courseid: number; diff --git a/src/addons/mod/forum/services/handlers/sync-cron.ts b/src/addons/mod/forum/services/handlers/sync-cron.ts index 86f6aff10..2544f3bd1 100644 --- a/src/addons/mod/forum/services/handlers/sync-cron.ts +++ b/src/addons/mod/forum/services/handlers/sync-cron.ts @@ -34,7 +34,7 @@ export class AddonModForumSyncCronHandlerService implements CoreCronHandler { * @return Promise resolved when done, rejected if failure. */ execute(siteId?: string, force?: boolean): Promise { - return AddonModForumSync.instance.syncAllForums(siteId, force); + return AddonModForumSync.syncAllForums(siteId, force); } /** @@ -43,9 +43,9 @@ export class AddonModForumSyncCronHandlerService implements CoreCronHandler { * @return Time between consecutive executions (in ms). */ getInterval(): number { - return AddonModForumSync.instance.syncInterval; + return AddonModForumSync.syncInterval; } } -export class AddonModForumSyncCronHandler extends makeSingleton(AddonModForumSyncCronHandlerService) {} +export const AddonModForumSyncCronHandler = makeSingleton(AddonModForumSyncCronHandlerService); diff --git a/src/addons/mod/forum/services/handlers/tag-area.ts b/src/addons/mod/forum/services/handlers/tag-area.ts index f93819405..3c5fb3e31 100644 --- a/src/addons/mod/forum/services/handlers/tag-area.ts +++ b/src/addons/mod/forum/services/handlers/tag-area.ts @@ -44,7 +44,7 @@ export class AddonModForumTagAreaHandlerService implements CoreTagAreaHandler { * @return Area items (or promise resolved with the items). */ parseContent(content: string): CoreTagFeedElement[] { - return CoreTagHelper.instance.parseFeedContent(content); + return CoreTagHelper.parseFeedContent(content); } /** @@ -59,4 +59,4 @@ export class AddonModForumTagAreaHandlerService implements CoreTagAreaHandler { } -export class AddonModForumTagAreaHandler extends makeSingleton(AddonModForumTagAreaHandlerService) {} +export const AddonModForumTagAreaHandler = makeSingleton(AddonModForumTagAreaHandlerService); diff --git a/src/addons/mod/forum/services/helper.ts b/src/addons/mod/forum/services/helper.ts index 25266f75b..f80b1f2d6 100644 --- a/src/addons/mod/forum/services/helper.ts +++ b/src/addons/mod/forum/services/helper.ts @@ -65,7 +65,7 @@ export class AddonModForumHelperProvider { timeCreated?: number, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); groupIds = (groupIds && groupIds.length > 0) ? groupIds : [0]; let saveOffline = false; @@ -81,7 +81,7 @@ export class AddonModForumHelperProvider { options.attachmentsid = offlineAttachments; } - await AddonModForumOffline.instance.addNewDiscussion( + await AddonModForumOffline.addNewDiscussion( forumId, name, courseId, @@ -116,10 +116,10 @@ export class AddonModForumHelperProvider { // If we are editing an offline discussion, discard previous first. if (timeCreated) { - await AddonModForumOffline.instance.deleteNewDiscussion(forumId, timeCreated, siteId); + await AddonModForumOffline.deleteNewDiscussion(forumId, timeCreated, siteId); } - if (saveOffline || !CoreApp.instance.isOnline()) { + if (saveOffline || !CoreApp.isOnline()) { await storeOffline(); return null; @@ -128,14 +128,14 @@ export class AddonModForumHelperProvider { const errors: Error[] = []; const discussionIds: number[] = []; const promises = groupIds.map(async (groupId, index) => { - const groupOptions = CoreUtils.instance.clone(options); + const groupOptions = CoreUtils.clone(options); if (groupOptions && attachmentsIds[index]) { groupOptions.attachmentsid = attachmentsIds[index]; } try { - const discussionId = await AddonModForum.instance.addNewDiscussionOnline( + const discussionId = await AddonModForum.addNewDiscussionOnline( forumId, subject, message, @@ -155,7 +155,7 @@ export class AddonModForumHelperProvider { if (errors.length == groupIds.length) { // All requests have failed. for (let i = 0; i < errors.length; i++) { - if (CoreUtils.instance.isWebServiceError(errors[i]) || (attachments && attachments.length > 0)) { + if (CoreUtils.isWebServiceError(errors[i]) || (attachments && attachments.length > 0)) { // The WebService has thrown an error or offline not supported, reject. throw errors[i]; } @@ -219,7 +219,7 @@ export class AddonModForumHelperProvider { // Get user data. promises.push( - CoreUtils.instance.ignoreErrors( + CoreUtils.ignoreErrors( CoreUser.instance .getProfile(offlineReply.userid, offlineReply.courseid, true) .then(user => { @@ -247,10 +247,10 @@ export class AddonModForumHelperProvider { * @return Promise resolved when deleted. */ async deleteNewDiscussionStoredFiles(forumId: number, timecreated: number, siteId?: string): Promise { - const folderPath = await AddonModForumOffline.instance.getNewDiscussionFolder(forumId, timecreated, siteId); + const folderPath = await AddonModForumOffline.getNewDiscussionFolder(forumId, timecreated, siteId); // Ignore any errors, CoreFileProvider.removeDir fails if folder doesn't exist. - await CoreUtils.instance.ignoreErrors(CoreFile.instance.removeDir(folderPath)); + await CoreUtils.ignoreErrors(CoreFile.removeDir(folderPath)); } /** @@ -263,10 +263,10 @@ export class AddonModForumHelperProvider { * @return Promise resolved when deleted. */ async deleteReplyStoredFiles(forumId: number, postId: number, siteId?: string, userId?: number): Promise { - const folderPath = await AddonModForumOffline.instance.getReplyFolder(forumId, postId, siteId, userId); + const folderPath = await AddonModForumOffline.getReplyFolder(forumId, postId, siteId, userId); // Ignore any errors, CoreFileProvider.removeDir fails if folder doesn't exist. - await CoreUtils.instance.ignoreErrors(CoreFile.instance.removeDir(folderPath)); + await CoreUtils.ignoreErrors(CoreFile.removeDir(folderPath)); } /** @@ -277,19 +277,19 @@ export class AddonModForumHelperProvider { */ getAvailabilityMessage(forum: AddonModForumData): string | null { if (this.isCutoffDateReached(forum)) { - return Translate.instance.instant('addon.mod_forum.cutoffdatereached'); + return Translate.instant('addon.mod_forum.cutoffdatereached'); } if (this.isDueDateReached(forum)) { - const dueDate = CoreTimeUtils.instance.userDate(forum.duedate * 1000); + const dueDate = CoreTimeUtils.userDate(forum.duedate * 1000); - return Translate.instance.instant('addon.mod_forum.thisforumisdue', { $a: dueDate }); + return Translate.instant('addon.mod_forum.thisforumisdue', { $a: dueDate }); } if ((forum.duedate ?? 0) > 0) { - const dueDate = CoreTimeUtils.instance.userDate(forum.duedate! * 1000); + const dueDate = CoreTimeUtils.userDate(forum.duedate! * 1000); - return Translate.instance.instant('addon.mod_forum.thisforumhasduedate', { $a: dueDate }); + return Translate.instant('addon.mod_forum.thisforumhasduedate', { $a: dueDate }); } return null; @@ -307,10 +307,10 @@ export class AddonModForumHelperProvider { * @return Promise resolved with the discussion data. */ getDiscussionById(forumId: number, cmId: number, discussionId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const findDiscussion = async (page: number): Promise => { - const response = await AddonModForum.instance.getDiscussions(forumId, { + const response = await AddonModForum.getDiscussions(forumId, { cmId, page, siteId, @@ -344,9 +344,9 @@ export class AddonModForumHelperProvider { * @return Promise resolved with the files. */ async getNewDiscussionStoredFiles(forumId: number, timecreated: number, siteId?: string): Promise { - const folderPath = await AddonModForumOffline.instance.getNewDiscussionFolder(forumId, timecreated, siteId); + const folderPath = await AddonModForumOffline.getNewDiscussionFolder(forumId, timecreated, siteId); - return CoreFileUploader.instance.getStoredFiles(folderPath); + return CoreFileUploader.getStoredFiles(folderPath); } /** @@ -359,9 +359,9 @@ export class AddonModForumHelperProvider { * @return Promise resolved with the files. */ async getReplyStoredFiles(forumId: number, postId: number, siteId?: string, userId?: number): Promise { - const folderPath = await AddonModForumOffline.instance.getReplyFolder(forumId, postId, siteId, userId); + const folderPath = await AddonModForumOffline.getReplyFolder(forumId, postId, siteId, userId); - return CoreFileUploader.instance.getStoredFiles(folderPath); + return CoreFileUploader.getStoredFiles(folderPath); } /** @@ -385,7 +385,7 @@ export class AddonModForumHelperProvider { return true; } - return CoreFileUploader.instance.areFileListDifferent(post.files, original.files); + return CoreFileUploader.areFileListDifferent(post.files, original.files); } /** @@ -428,9 +428,9 @@ export class AddonModForumHelperProvider { siteId?: string, ): Promise { // Get the folder where to store the files. - const folderPath = await AddonModForumOffline.instance.getNewDiscussionFolder(forumId, timecreated, siteId); + const folderPath = await AddonModForumOffline.getNewDiscussionFolder(forumId, timecreated, siteId); - return CoreFileUploader.instance.storeFilesToUpload(folderPath, files); + return CoreFileUploader.storeFilesToUpload(folderPath, files); } /** @@ -446,9 +446,9 @@ export class AddonModForumHelperProvider { */ async storeReplyFiles(forumId: number, postId: number, files: any[], siteId?: string, userId?: number): Promise { // Get the folder where to store the files. - const folderPath = await AddonModForumOffline.instance.getReplyFolder(forumId, postId, siteId, userId); + const folderPath = await AddonModForumOffline.getReplyFolder(forumId, postId, siteId, userId); - await CoreFileUploader.instance.storeFilesToUpload(folderPath, files); + await CoreFileUploader.storeFilesToUpload(folderPath, files); } /** @@ -485,7 +485,7 @@ export class AddonModForumHelperProvider { if (offline) { return this.storeNewDiscussionFiles(forumId, timecreated, files, siteId); } else { - return CoreFileUploader.instance.uploadOrReuploadFiles(files, AddonModForumProvider.COMPONENT, forumId, siteId); + return CoreFileUploader.uploadOrReuploadFiles(files, AddonModForumProvider.COMPONENT, forumId, siteId); } } @@ -511,10 +511,10 @@ export class AddonModForumHelperProvider { if (offline) { return this.storeReplyFiles(forumId, postId, files, siteId, userId); } else { - return CoreFileUploader.instance.uploadOrReuploadFiles(files, AddonModForumProvider.COMPONENT, forumId, siteId); + return CoreFileUploader.uploadOrReuploadFiles(files, AddonModForumProvider.COMPONENT, forumId, siteId); } } } -export class AddonModForumHelper extends makeSingleton(AddonModForumHelperProvider) {} +export const AddonModForumHelper = makeSingleton(AddonModForumHelperProvider); diff --git a/src/addons/mod/forum/services/offline.ts b/src/addons/mod/forum/services/offline.ts index 8ece6b1b2..bb28c0287 100644 --- a/src/addons/mod/forum/services/offline.ts +++ b/src/addons/mod/forum/services/offline.ts @@ -42,7 +42,7 @@ export class AddonModForumOfflineProvider { * @return Promise resolved if stored, rejected if failure. */ async deleteNewDiscussion(forumId: number, timeCreated: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions = { forumid: forumId, userid: userId || site.getUserId(), @@ -67,7 +67,7 @@ export class AddonModForumOfflineProvider { siteId?: string, userId?: number, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions = { forumid: forumId, userid: userId || site.getUserId(), @@ -86,7 +86,7 @@ export class AddonModForumOfflineProvider { * @return Promise resolved with discussions. */ async getAllNewDiscussions(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const records = await site.getDb().getRecords(DISCUSSIONS_TABLE); return this.parseRecordsOptions(records); @@ -121,7 +121,7 @@ export class AddonModForumOfflineProvider { * @return Promise resolved with the object to be synced. */ async getNewDiscussions(forumId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions = { forumid: forumId, userid: userId || site.getUserId(), @@ -159,7 +159,7 @@ export class AddonModForumOfflineProvider { siteId?: string, userId?: number, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data: AddonModForumOfflineDiscussionDBRecord = { forumid: forumId, name: name, @@ -184,7 +184,7 @@ export class AddonModForumOfflineProvider { * @return Promise resolved if stored, rejected if failure. */ async deleteReply(postId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions = { postid: postId, userid: userId || site.getUserId(), @@ -200,7 +200,7 @@ export class AddonModForumOfflineProvider { * @return Promise resolved with replies. */ async getAllReplies(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const records = await site.getDb().getRecords(REPLIES_TABLE); return this.parseRecordsOptions(records); @@ -235,7 +235,7 @@ export class AddonModForumOfflineProvider { * @return Promise resolved with replies. */ async getForumReplies(forumId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions = { forumid: forumId, userid: userId || site.getUserId(), @@ -275,7 +275,7 @@ export class AddonModForumOfflineProvider { * @return Promise resolved with discussions. */ async getDiscussionReplies(discussionId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions = { discussionid: discussionId, userid: userId || site.getUserId(), @@ -313,7 +313,7 @@ export class AddonModForumOfflineProvider { siteId?: string, userId?: number, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data: AddonModForumOfflineReplyDBRecord = { postid: postId, discussionid: discussionId, @@ -338,10 +338,10 @@ export class AddonModForumOfflineProvider { * @return Promise resolved with the path. */ async getForumFolder(forumId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); - const siteFolderPath = CoreFile.instance.getSiteFolder(site.getId()); + const site = await CoreSites.getSite(siteId); + const siteFolderPath = CoreFile.getSiteFolder(site.getId()); - return CoreTextUtils.instance.concatenatePaths(siteFolderPath, 'offlineforum/' + forumId); + return CoreTextUtils.concatenatePaths(siteFolderPath, 'offlineforum/' + forumId); } /** @@ -355,7 +355,7 @@ export class AddonModForumOfflineProvider { async getNewDiscussionFolder(forumId: number, timeCreated: number, siteId?: string): Promise { const folderPath = await this.getForumFolder(forumId, siteId); - return CoreTextUtils.instance.concatenatePaths(folderPath, 'newdisc_' + timeCreated); + return CoreTextUtils.concatenatePaths(folderPath, 'newdisc_' + timeCreated); } /** @@ -369,10 +369,10 @@ export class AddonModForumOfflineProvider { */ async getReplyFolder(forumId: number, postId: number, siteId?: string, userId?: number): Promise { const folderPath = await this.getForumFolder(forumId, siteId); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); - return CoreTextUtils.instance.concatenatePaths(folderPath, 'reply_' + postId + '_' + userId); + return CoreTextUtils.concatenatePaths(folderPath, 'reply_' + postId + '_' + userId); } /** @@ -398,14 +398,14 @@ export class AddonModForumOfflineProvider { R extends { options: string }, O extends Record = Record >(record: R): Omit & { options: O } { - record.options = CoreTextUtils.instance.parseJSON(record.options); + record.options = CoreTextUtils.parseJSON(record.options); return record as unknown as Omit & { options: O }; } } -export class AddonModForumOffline extends makeSingleton(AddonModForumOfflineProvider) {} +export const AddonModForumOffline = makeSingleton(AddonModForumOfflineProvider); export type AddonModForumDiscussionOptions = { attachmentsid?: number | CoreFileUploaderStoreFilesResult; diff --git a/src/addons/mod/forum/services/sync.ts b/src/addons/mod/forum/services/sync.ts index 1f99f2ec2..863360c3f 100644 --- a/src/addons/mod/forum/services/sync.ts +++ b/src/addons/mod/forum/services/sync.ts @@ -66,7 +66,7 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const syncId = this.getForumSyncId(forumId, userId); @@ -202,8 +202,8 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider { - userId = userId || CoreSites.instance.getCurrentSiteUserId(); - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + userId = userId || CoreSites.getCurrentSiteUserId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const syncId = this.getForumSyncId(forumId, userId); @@ -213,7 +213,7 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider => { - await CoreUtils.instance.ignoreErrors( - CoreCourseLogHelper.instance.syncActivity(AddonModForumProvider.COMPONENT, forumId, siteId), + await CoreUtils.ignoreErrors( + CoreCourseLogHelper.syncActivity(AddonModForumProvider.COMPONENT, forumId, siteId), ); // Get offline responses to be sent. - const discussions = await CoreUtils.instance.ignoreErrors( - AddonModForumOffline.instance.getNewDiscussions(forumId, siteId, userId), + const discussions = await CoreUtils.ignoreErrors( + AddonModForumOffline.getNewDiscussions(forumId, siteId, userId), [] as AddonModForumOfflineDiscussion[], ); - if (discussions.length !== 0 && !CoreApp.instance.isOnline()) { + if (discussions.length !== 0 && !CoreApp.isOnline()) { throw new Error('cannot sync in offline'); } @@ -247,7 +247,7 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider CoreGroups.instance.getActivityAllowedGroups(forum.cmid)) + .then(forum => CoreGroups.getActivityAllowedGroups(forum.cmid)) .then(result => result.groups.map((group) => group.id)) : [discussion.groupid]; @@ -257,10 +257,10 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider { // Get offline forum replies to be sent. - const replies = await CoreUtils.instance.ignoreErrors( - AddonModForumOffline.instance.getForumReplies(forumId, siteId, userId), + const replies = await CoreUtils.ignoreErrors( + AddonModForumOffline.getForumReplies(forumId, siteId, userId), [] as AddonModForumOfflineReply[], ); if (!replies.length) { // Nothing to sync. return { warnings: [], updated: false }; - } else if (!CoreApp.instance.isOnline()) { + } else if (!CoreApp.isOnline()) { // Cannot sync in offline. return Promise.reject(null); } @@ -391,7 +391,7 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const syncId = this.getDiscussionSyncId(discussionId, userId); @@ -411,8 +411,8 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider { - userId = userId || CoreSites.instance.getCurrentSiteUserId(); - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + userId = userId || CoreSites.getCurrentSiteUserId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const syncId = this.getDiscussionSyncId(discussionId, userId); @@ -422,7 +422,7 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider { - const replies = await CoreUtils.instance.ignoreErrors( - AddonModForumOffline.instance.getDiscussionReplies(discussionId, siteId, userId), + const replies = await CoreUtils.ignoreErrors( + AddonModForumOffline.getDiscussionReplies(discussionId, siteId, userId), [] as AddonModForumOfflineReply[], ); - if (replies.length !== 0 && !CoreApp.instance.isOnline()) { + if (replies.length !== 0 && !CoreApp.isOnline()) { throw new Error('Cannot sync in offline'); } @@ -457,7 +457,7 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider[] = []; if (forumId) { - invalidationPromises.push(AddonModForum.instance.invalidateDiscussionsList(forumId, siteId)); + invalidationPromises.push(AddonModForum.invalidateDiscussionsList(forumId, siteId)); } - invalidationPromises.push(AddonModForum.instance.invalidateDiscussionPosts(discussionId, forumId, siteId)); + invalidationPromises.push(AddonModForum.invalidateDiscussionPosts(discussionId, forumId, siteId)); - await CoreUtils.instance.ignoreErrors(CoreUtils.instance.allPromises(invalidationPromises)); + await CoreUtils.ignoreErrors(CoreUtils.allPromises(invalidationPromises)); // Sync finished, set sync time. - await CoreUtils.instance.ignoreErrors(this.setSyncTime(syncId, siteId)); + await CoreUtils.ignoreErrors(this.setSyncTime(syncId, siteId)); // All done, return the warnings. return result; @@ -522,9 +522,9 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider { await Promise.all([ - AddonModForumOffline.instance.deleteNewDiscussion(forumId, timecreated, siteId, userId), - CoreUtils.instance.ignoreErrors( - AddonModForumHelper.instance.deleteNewDiscussionStoredFiles(forumId, timecreated, siteId), + AddonModForumOffline.deleteNewDiscussion(forumId, timecreated, siteId, userId), + CoreUtils.ignoreErrors( + AddonModForumHelper.deleteNewDiscussionStoredFiles(forumId, timecreated, siteId), ), ]); } @@ -540,8 +540,8 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider { await Promise.all([ - AddonModForumOffline.instance.deleteReply(postId, siteId, userId), - CoreUtils.instance.ignoreErrors(AddonModForumHelper.instance.deleteReplyStoredFiles(forumId, postId, siteId, userId)), + AddonModForumOffline.deleteReply(postId, siteId, userId), + CoreUtils.ignoreErrors(AddonModForumHelper.deleteReplyStoredFiles(forumId, postId, siteId, userId)), ]); } @@ -575,12 +575,12 @@ export class AddonModForumSyncProvider extends CoreSyncBaseProvider[] = []; - if (AddonModLesson.instance.isLessonOffline(this.lesson)) { + if (AddonModLesson.isLessonOffline(this.lesson)) { // Handle status. this.setStatusListener(); @@ -171,7 +171,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo } if (this.accessInfo.preventaccessreasons.length) { - let preventReason = AddonModLesson.instance.getPreventAccessReason(this.accessInfo, false); + let preventReason = AddonModLesson.getPreventAccessReason(this.accessInfo, false); const askPassword = preventReason?.reason == 'passwordprotectedlesson'; if (askPassword) { @@ -179,12 +179,12 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo // The lesson requires a password. Check if there is one in memory or DB. const password = this.password ? this.password : - await AddonModLesson.instance.getStoredPassword(this.lesson.id); + await AddonModLesson.getStoredPassword(this.lesson.id); await this.validatePassword(password); // Now that we have the password, get the access reason again ignoring the password. - preventReason = AddonModLesson.instance.getPreventAccessReason(this.accessInfo, true); + preventReason = AddonModLesson.getPreventAccessReason(this.accessInfo, true); if (preventReason) { this.preventReasons = [preventReason]; } @@ -231,21 +231,21 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo const options = { cmId: this.module!.id }; // Check if there is offline data. - promises.push(AddonModLessonSync.instance.hasDataToSync(this.lesson.id, this.accessInfo.attemptscount).then((hasData) => { + promises.push(AddonModLessonSync.hasDataToSync(this.lesson.id, this.accessInfo.attemptscount).then((hasData) => { this.hasOffline = hasData; return; })); // Check if there is a retake finished in a synchronization. - promises.push(AddonModLessonSync.instance.getRetakeFinishedInSync(this.lesson.id).then((retake) => { + promises.push(AddonModLessonSync.getRetakeFinishedInSync(this.lesson.id).then((retake) => { if (retake && retake.retake == this.accessInfo!.attemptscount - 1) { // The retake finished is still the last retake. Allow reviewing it. this.retakeToReview = retake; } else { this.retakeToReview = undefined; if (retake) { - AddonModLessonSync.instance.deleteRetakeFinishedInSync(this.lesson!.id); + AddonModLessonSync.deleteRetakeFinishedInSync(this.lesson!.id); } } @@ -253,15 +253,15 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo })); // Check if the ser has a finished retake in offline. - promises.push(AddonModLessonOffline.instance.hasFinishedRetake(this.lesson.id).then((finished) => { + promises.push(AddonModLessonOffline.hasFinishedRetake(this.lesson.id).then((finished) => { this.finishedOffline = finished; return; })); // Update the list of content pages viewed and question attempts. - promises.push(AddonModLesson.instance.getContentPagesViewedOnline(this.lesson.id, this.accessInfo.attemptscount, options)); - promises.push(AddonModLesson.instance.getQuestionsAttemptsOnline(this.lesson.id, this.accessInfo.attemptscount, options)); + promises.push(AddonModLesson.getContentPagesViewedOnline(this.lesson.id, this.accessInfo.attemptscount, options)); + promises.push(AddonModLesson.getQuestionsAttemptsOnline(this.lesson.id, this.accessInfo.attemptscount, options)); await Promise.all(promises); } @@ -277,9 +277,9 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo } try { - this.groupInfo = await CoreGroups.instance.getActivityGroupInfo(this.module.id); + this.groupInfo = await CoreGroups.getActivityGroupInfo(this.module.id); - await this.setGroup(CoreGroups.instance.validateGroupId(this.group, this.groupInfo)); + await this.setGroup(CoreGroups.validateGroupId(this.group, this.groupInfo)); } finally { this.reportLoaded = true; } @@ -294,7 +294,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo protected hasSyncSucceed(result: AddonModLessonSyncResult): boolean { if (result.updated || this.dataSent) { // Check completion status if something was sent. - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); } this.dataSent = false; @@ -340,18 +340,18 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo protected async invalidateContent(): Promise { const promises: Promise[] = []; - promises.push(AddonModLesson.instance.invalidateLessonData(this.courseId!)); + promises.push(AddonModLesson.invalidateLessonData(this.courseId!)); if (this.lesson) { - promises.push(AddonModLesson.instance.invalidateAccessInformation(this.lesson.id)); - promises.push(AddonModLesson.instance.invalidatePages(this.lesson.id)); - promises.push(AddonModLesson.instance.invalidateLessonWithPassword(this.lesson.id)); - promises.push(AddonModLesson.instance.invalidateTimers(this.lesson.id)); - promises.push(AddonModLesson.instance.invalidateContentPagesViewed(this.lesson.id)); - promises.push(AddonModLesson.instance.invalidateQuestionsAttempts(this.lesson.id)); - promises.push(AddonModLesson.instance.invalidateRetakesOverview(this.lesson.id)); + promises.push(AddonModLesson.invalidateAccessInformation(this.lesson.id)); + promises.push(AddonModLesson.invalidatePages(this.lesson.id)); + promises.push(AddonModLesson.invalidateLessonWithPassword(this.lesson.id)); + promises.push(AddonModLesson.invalidateTimers(this.lesson.id)); + promises.push(AddonModLesson.invalidateContentPagesViewed(this.lesson.id)); + promises.push(AddonModLesson.invalidateQuestionsAttempts(this.lesson.id)); + promises.push(AddonModLesson.invalidateRetakesOverview(this.lesson.id)); if (this.module) { - promises.push(CoreGroups.instance.invalidateActivityGroupInfo(this.module.id)); + promises.push(CoreGroups.invalidateActivityGroupInfo(this.module.id)); } } @@ -373,11 +373,11 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo */ protected lessonReady(): void { this.askPassword = false; - this.leftDuringTimed = this.hasOffline || AddonModLesson.instance.leftDuringTimed(this.accessInfo); + this.leftDuringTimed = this.hasOffline || AddonModLesson.leftDuringTimed(this.accessInfo); if (this.password) { // Store the password in DB. - AddonModLesson.instance.storePassword(this.lesson!.id, this.password); + AddonModLesson.storePassword(this.lesson!.id, this.password); } } @@ -391,11 +391,11 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo return; } - await CoreUtils.instance.ignoreErrors( - AddonModLesson.instance.logViewLesson(this.lesson.id, this.password, this.lesson.name), + await CoreUtils.ignoreErrors( + AddonModLesson.logViewLesson(this.lesson.id, this.password, this.lesson.name), ); - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); } /** @@ -414,7 +414,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo if (this.hasOffline) { if (continueLast) { - pageId = await AddonModLesson.instance.getLastPageSeen(this.lesson.id, this.accessInfo.attemptscount, { + pageId = await AddonModLesson.getLastPageSeen(this.lesson.id, this.accessInfo.attemptscount, { cmId: this.module!.id, }); } else { @@ -424,7 +424,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo pageId = continueLast ? this.accessInfo.lastpageseen : this.accessInfo.firstpageid; } - await CoreNavigator.instance.navigate(`../player/${this.courseId}/${this.lesson.id}`, { + await CoreNavigator.navigate(`../player/${this.courseId}/${this.lesson.id}`, { params: { pageId: pageId, password: this.password, @@ -458,7 +458,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo if (!this.groupInfo) { this.fetchReportData().catch((error) => { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting report.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting report.'); }); } } @@ -472,7 +472,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo return; } - CoreNavigator.instance.navigate(`../player/${this.courseId}/${this.lesson.id}`, { + CoreNavigator.navigate(`../player/${this.courseId}/${this.lesson.id}`, { params: { pageId: this.retakeToReview.pageid, password: this.password, @@ -503,7 +503,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo } // Get the overview of retakes for the group. - const data = await AddonModLesson.instance.getRetakesOverview(this.lesson.id, { + const data = await AddonModLesson.getRetakesOverview(this.lesson.id, { groupId, cmId: this.lesson.coursemodule, }); @@ -519,35 +519,35 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo // Format times and grades. if (formattedData.avetime != null && formattedData.numofattempts) { formattedData.avetime = Math.floor(formattedData.avetime / formattedData.numofattempts); - this.avetimeReadable = CoreTimeUtils.instance.formatTime(formattedData.avetime); + this.avetimeReadable = CoreTimeUtils.formatTime(formattedData.avetime); } if (formattedData.hightime != null) { - this.hightimeReadable = CoreTimeUtils.instance.formatTime(formattedData.hightime); + this.hightimeReadable = CoreTimeUtils.formatTime(formattedData.hightime); } if (formattedData.lowtime != null) { - this.lowtimeReadable = CoreTimeUtils.instance.formatTime(formattedData.lowtime); + this.lowtimeReadable = CoreTimeUtils.formatTime(formattedData.lowtime); } if (formattedData.lessonscored) { if (formattedData.numofattempts && formattedData.avescore != null) { - formattedData.avescore = CoreTextUtils.instance.roundToDecimals(formattedData.avescore, 2); + formattedData.avescore = CoreTextUtils.roundToDecimals(formattedData.avescore, 2); } if (formattedData.highscore != null) { - formattedData.highscore = CoreTextUtils.instance.roundToDecimals(formattedData.highscore, 2); + formattedData.highscore = CoreTextUtils.roundToDecimals(formattedData.highscore, 2); } if (formattedData.lowscore != null) { - formattedData.lowscore = CoreTextUtils.instance.roundToDecimals(formattedData.lowscore, 2); + formattedData.lowscore = CoreTextUtils.roundToDecimals(formattedData.lowscore, 2); } } if (formattedData.students) { // Get the user data for each student returned. - await CoreUtils.instance.allPromises(formattedData.students.map(async (student) => { - student.bestgrade = CoreTextUtils.instance.roundToDecimals(student.bestgrade, 2); + await CoreUtils.allPromises(formattedData.students.map(async (student) => { + student.bestgrade = CoreTextUtils.roundToDecimals(student.bestgrade, 2); - const user = await CoreUtils.instance.ignoreErrors(CoreUser.instance.getProfile(student.id, this.courseId, true)); + const user = await CoreUtils.ignoreErrors(CoreUser.getProfile(student.id, this.courseId, true)); if (user) { student.profileimageurl = user.profileimageurl; } @@ -579,7 +579,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo return; } - if (!AddonModLesson.instance.isLessonOffline(this.lesson) || this.currentStatus == CoreConstants.DOWNLOADED) { + if (!AddonModLesson.isLessonOffline(this.lesson) || this.currentStatus == CoreConstants.DOWNLOADED) { // Not downloadable or already downloaded, open it. this.playLesson(continueLast); @@ -590,7 +590,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo this.showSpinner = true; try { - await AddonModLessonPrefetchHandler.instance.prefetch(this.module!, this.courseId, true); + await AddonModLessonPrefetchHandler.prefetch(this.module!, this.courseId, true); // Success downloading, open lesson. this.playLesson(continueLast); @@ -599,7 +599,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo // Error downloading but there is something offline, allow continuing it. this.playLesson(continueLast); } else { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); } } finally { this.showSpinner = false; @@ -618,7 +618,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo const password = passwordEl?.value; if (!password) { - CoreDomUtils.instance.showErrorModal('addon.mod_lesson.emptypassword', true); + CoreDomUtils.showErrorModal('addon.mod_lesson.emptypassword', true); return; } @@ -634,19 +634,19 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo this.lessonReady(); // Now that we have the password, get the access reason again ignoring the password. - const preventReason = AddonModLesson.instance.getPreventAccessReason(this.accessInfo!, true); + const preventReason = AddonModLesson.getPreventAccessReason(this.accessInfo!, true); this.preventReasons = preventReason ? [preventReason] : []; // Log view now that we have the password. this.logView(); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { this.loaded = true; this.refreshIcon = CoreConstants.ICON_REFRESH; this.syncIcon = CoreConstants.ICON_SYNC; - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, true, this.siteId); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, true, this.siteId); } } @@ -656,11 +656,11 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo * @return Promise resolved when done. */ protected async sync(): Promise { - const result = await AddonModLessonSync.instance.syncLesson(this.lesson!.id, true); + const result = await AddonModLessonSync.syncLesson(this.lesson!.id, true); if (!result.updated && this.dataSent && this.isPrefetched()) { // The user sent data to server, but not in the sync process. Check if we need to fetch data. - await CoreUtils.instance.ignoreErrors(AddonModLessonSync.instance.prefetchAfterUpdate( + await CoreUtils.ignoreErrors(AddonModLessonSync.prefetchAfterUpdate( AddonModLessonPrefetchHandler.instance, this.module!, this.courseId!, @@ -678,7 +678,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo */ protected async validatePassword(password: string): Promise { try { - this.lesson = await AddonModLesson.instance.getLessonWithPassword(this.lesson!.id, { password, cmId: this.module!.id }); + this.lesson = await AddonModLesson.getLessonWithPassword(this.lesson!.id, { password, cmId: this.module!.id }); this.password = password; } catch (error) { @@ -695,7 +695,7 @@ export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityCo * @return Promise resolved when done. */ async openRetake(userId: number): Promise { - await CoreNavigator.instance.navigate(`../user-retake/${this.courseId}/${this.lesson!.id}`, { + await CoreNavigator.navigate(`../user-retake/${this.courseId}/${this.lesson!.id}`, { params: { userId, }, diff --git a/src/addons/mod/lesson/components/menu-modal/menu-modal.ts b/src/addons/mod/lesson/components/menu-modal/menu-modal.ts index 0b14d58e1..73b257e79 100644 --- a/src/addons/mod/lesson/components/menu-modal/menu-modal.ts +++ b/src/addons/mod/lesson/components/menu-modal/menu-modal.ts @@ -39,7 +39,7 @@ export class AddonModLessonMenuModalPage { * Close modal. */ closeModal(): void { - ModalController.instance.dismiss(); + ModalController.dismiss(); } /** diff --git a/src/addons/mod/lesson/components/password-modal/password-modal.ts b/src/addons/mod/lesson/components/password-modal/password-modal.ts index f92c513db..9e77b63ec 100644 --- a/src/addons/mod/lesson/components/password-modal/password-modal.ts +++ b/src/addons/mod/lesson/components/password-modal/password-modal.ts @@ -41,18 +41,18 @@ export class AddonModLessonPasswordModalComponent { e.preventDefault(); e.stopPropagation(); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, false, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, false, CoreSites.getCurrentSiteId()); - ModalController.instance.dismiss(password.value); + ModalController.dismiss(password.value); } /** * Close modal. */ closeModal(): void { - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); - ModalController.instance.dismiss(); + ModalController.dismiss(); } } diff --git a/src/addons/mod/lesson/lesson.module.ts b/src/addons/mod/lesson/lesson.module.ts index 0d53428a7..ac90cef84 100644 --- a/src/addons/mod/lesson/lesson.module.ts +++ b/src/addons/mod/lesson/lesson.module.ts @@ -56,14 +56,14 @@ const routes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreCourseModuleDelegate.instance.registerHandler(AddonModLessonModuleHandler.instance); - CoreCourseModulePrefetchDelegate.instance.registerHandler(AddonModLessonPrefetchHandler.instance); - CoreCronDelegate.instance.register(AddonModLessonSyncCronHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModLessonGradeLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModLessonIndexLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModLessonListLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModLessonReportLinkHandler.instance); - CorePushNotificationsDelegate.instance.registerClickHandler(AddonModLessonPushClickHandler.instance); + CoreCourseModuleDelegate.registerHandler(AddonModLessonModuleHandler.instance); + CoreCourseModulePrefetchDelegate.registerHandler(AddonModLessonPrefetchHandler.instance); + CoreCronDelegate.register(AddonModLessonSyncCronHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModLessonGradeLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModLessonIndexLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModLessonListLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModLessonReportLinkHandler.instance); + CorePushNotificationsDelegate.registerClickHandler(AddonModLessonPushClickHandler.instance); }, }, ], diff --git a/src/addons/mod/lesson/pages/index/index.ts b/src/addons/mod/lesson/pages/index/index.ts index 976f7c627..983bdda98 100644 --- a/src/addons/mod/lesson/pages/index/index.ts +++ b/src/addons/mod/lesson/pages/index/index.ts @@ -40,10 +40,10 @@ export class AddonModLessonIndexPage implements OnInit { * Component being initialized. */ ngOnInit(): void { - this.module = CoreNavigator.instance.getRouteParam('module'); - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId'); - this.group = CoreNavigator.instance.getRouteNumberParam('group'); - this.action = CoreNavigator.instance.getRouteParam('action'); + this.module = CoreNavigator.getRouteParam('module'); + this.courseId = CoreNavigator.getRouteNumberParam('courseId'); + this.group = CoreNavigator.getRouteNumberParam('group'); + this.action = CoreNavigator.getRouteParam('action'); this.title = this.module?.name; } diff --git a/src/addons/mod/lesson/pages/player/player.ts b/src/addons/mod/lesson/pages/player/player.ts index 3626b2d11..592b2dc54 100644 --- a/src/addons/mod/lesson/pages/player/player.ts +++ b/src/addons/mod/lesson/pages/player/player.ts @@ -118,22 +118,22 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { * Component being initialized. */ async ngOnInit(): Promise { - this.lessonId = CoreNavigator.instance.getRouteNumberParam('lessonId')!; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.password = CoreNavigator.instance.getRouteParam('password'); - this.review = !!CoreNavigator.instance.getRouteBooleanParam('review'); - this.currentPage = CoreNavigator.instance.getRouteNumberParam('pageId'); - this.retakeToReview = CoreNavigator.instance.getRouteNumberParam('retake'); + this.lessonId = CoreNavigator.getRouteNumberParam('lessonId')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.password = CoreNavigator.getRouteParam('password'); + this.review = !!CoreNavigator.getRouteBooleanParam('review'); + this.currentPage = CoreNavigator.getRouteNumberParam('pageId'); + this.retakeToReview = CoreNavigator.getRouteNumberParam('retake'); // Block the lesson so it cannot be synced. - CoreSync.instance.blockOperation(this.component, this.lessonId); + CoreSync.blockOperation(this.component, this.lessonId); try { // Fetch the Lesson data. const success = await this.fetchLessonData(); if (success) { // Review data loaded or new retake started, remove any retake being finished in sync. - AddonModLessonSync.instance.deleteRetakeFinishedInSync(this.lessonId); + AddonModLessonSync.deleteRetakeFinishedInSync(this.lessonId); } } finally { this.loaded = true; @@ -145,7 +145,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { */ ngOnDestroy(): void { // Unblock the lesson so it can be synced. - CoreSync.instance.unblockOperation(this.component, this.lessonId); + CoreSync.unblockOperation(this.component, this.lessonId); } /** @@ -160,12 +160,12 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { if (this.question && !this.eolData && !this.processData && this.originalData) { // Question shown. Check if there is any change. - if (!CoreUtils.instance.basicLeftCompare(this.questionForm.getRawValue(), this.originalData, 3)) { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.confirmcanceledit')); + if (!CoreUtils.basicLeftCompare(this.questionForm.getRawValue(), this.originalData, 3)) { + await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); } } - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); return true; } @@ -175,7 +175,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { */ ionViewWillLeave(): void { if (this.menuShown) { - ModalController.instance.dismiss(); + ModalController.dismiss(); } } @@ -199,12 +199,12 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { try { return await func(); } catch (error) { - if (this.offline || this.review || !AddonModLesson.instance.isLessonOffline(this.lesson!)) { + if (this.offline || this.review || !AddonModLesson.isLessonOffline(this.lesson!)) { // Already offline or not allowed. throw error; } - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // WebService returned an error, cannot perform the action. throw error; } @@ -213,7 +213,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { this.offline = true; // Get the possible jumps now. - this.jumps = await AddonModLesson.instance.getPagesPossibleJumps(this.lesson!.id, { + this.jumps = await AddonModLesson.getPagesPossibleJumps(this.lesson!.id, { cmId: this.lesson!.coursemodule, readingStrategy: CoreSitesReadingStrategy.PreferCache, }); @@ -246,7 +246,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { try { await this.loadPage(pageId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading page'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading page'); } finally { this.loaded = true; } @@ -260,15 +260,15 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { protected async fetchLessonData(): Promise { try { // Wait for any ongoing sync to finish. We won't sync a lesson while it's being played. - await AddonModLessonSync.instance.waitForSync(this.lessonId); + await AddonModLessonSync.waitForSync(this.lessonId); - this.lesson = await AddonModLesson.instance.getLessonById(this.courseId, this.lessonId); + this.lesson = await AddonModLesson.getLessonById(this.courseId, this.lessonId); this.title = this.lesson.name; // Temporary title. // If lesson has offline data already, use offline mode. - this.offline = await AddonModLessonOffline.instance.hasOfflineData(this.lessonId); + this.offline = await AddonModLessonOffline.hasOfflineData(this.lessonId); - if (!this.offline && !CoreApp.instance.isOnline() && AddonModLesson.instance.isLessonOffline(this.lesson) && + if (!this.offline && !CoreApp.isOnline() && AddonModLesson.isLessonOffline(this.lesson) && !this.review) { // Lesson doesn't have offline data, but it allows offline and the device is offline. Use offline mode. this.offline = true; @@ -279,7 +279,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { readingStrategy: this.offline ? CoreSitesReadingStrategy.PreferCache : CoreSitesReadingStrategy.OnlyNetwork, }; this.accessInfo = await this.callFunction( - AddonModLesson.instance.getAccessInformation.bind(AddonModLesson.instance, this.lesson.id, options), + AddonModLesson.getAccessInformation.bind(AddonModLesson.instance, this.lesson.id, options), options, ); @@ -290,7 +290,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { if (this.accessInfo.preventaccessreasons.length) { // If it's a password protected lesson and we have the password, allow playing it. - const preventReason = AddonModLesson.instance.getPreventAccessReason(this.accessInfo, !!this.password, this.review); + const preventReason = AddonModLesson.getPreventAccessReason(this.accessInfo, !!this.password, this.review); if (preventReason) { // Lesson cannot be played, show message and go back. throw new CoreError(preventReason.message); @@ -299,7 +299,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { if (this.review && this.retakeToReview != this.accessInfo.attemptscount - 1) { // Reviewing a retake that isn't the last one. Error. - throw new CoreError(Translate.instance.instant('addon.mod_lesson.errorreviewretakenotlast')); + throw new CoreError(Translate.instant('addon.mod_lesson.errorreviewretakenotlast')); } if (this.password) { @@ -310,7 +310,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { readingStrategy: this.offline ? CoreSitesReadingStrategy.PreferCache : CoreSitesReadingStrategy.OnlyNetwork, }; promises.push(this.callFunction( - AddonModLesson.instance.getLessonWithPassword.bind(AddonModLesson.instance, this.lesson.id, options), + AddonModLesson.getLessonWithPassword.bind(AddonModLesson.instance, this.lesson.id, options), options, ).then((lesson) => { this.lesson = lesson; @@ -321,7 +321,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { if (this.offline) { // Offline mode, get the list of possible jumps to allow navigation. - promises.push(AddonModLesson.instance.getPagesPossibleJumps(this.lesson.id, { + promises.push(AddonModLesson.getPagesPossibleJumps(this.lesson.id, { cmId: this.lesson.coursemodule, readingStrategy: CoreSitesReadingStrategy.PreferCache, }).then((jumpList) => { @@ -334,22 +334,22 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { await Promise.all(promises); this.mediaFile = this.lesson.mediafiles?.[0]; - this.lessonWidth = this.lesson.slideshow ? CoreDomUtils.instance.formatPixelsSize(this.lesson.mediawidth!) : ''; - this.lessonHeight = this.lesson.slideshow ? CoreDomUtils.instance.formatPixelsSize(this.lesson.mediaheight!) : ''; + this.lessonWidth = this.lesson.slideshow ? CoreDomUtils.formatPixelsSize(this.lesson.mediawidth!) : ''; + this.lessonHeight = this.lesson.slideshow ? CoreDomUtils.formatPixelsSize(this.lesson.mediaheight!) : ''; await this.launchRetake(this.currentPage); return true; } catch (error) { - if (this.review && this.retakeToReview && CoreUtils.instance.isWebServiceError(error)) { + if (this.review && this.retakeToReview && CoreUtils.isWebServiceError(error)) { // The user cannot review the retake. Unmark the retake as being finished in sync. - await AddonModLessonSync.instance.deleteRetakeFinishedInSync(this.lessonId); + await AddonModLessonSync.deleteRetakeFinishedInSync(this.lessonId); } - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errorgetmodule', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); this.forceLeave = true; - CoreNavigator.instance.back(); + CoreNavigator.back(); return false; } @@ -364,28 +364,28 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { protected async finishRetake(outOfTime?: boolean): Promise { this.messages = []; - if (this.offline && CoreApp.instance.isOnline()) { + if (this.offline && CoreApp.isOnline()) { // Offline mode but the app is online. Try to sync the data. - const result = await CoreUtils.instance.ignoreErrors( - AddonModLessonSync.instance.syncLesson(this.lesson!.id, true, true), + const result = await CoreUtils.ignoreErrors( + AddonModLessonSync.syncLesson(this.lesson!.id, true, true), ); if (result?.warnings?.length) { // Some data was deleted. Check if the retake has changed. - const info = await AddonModLesson.instance.getAccessInformation(this.lesson!.id, { + const info = await AddonModLesson.getAccessInformation(this.lesson!.id, { cmId: this.lesson!.coursemodule, }); if (info.attemptscount != this.accessInfo!.attemptscount) { // The retake has changed. Leave the view and show the error. this.forceLeave = true; - CoreNavigator.instance.back(); + CoreNavigator.back(); throw new CoreError(result.warnings[0]); } // Retake hasn't changed, show the warning and finish the retake in offline. - CoreDomUtils.instance.showErrorModal(result.warnings[0]); + CoreDomUtils.showErrorModal(result.warnings[0]); } this.offline = false; @@ -400,7 +400,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { accessInfo: this.accessInfo, }; const data = await this.callFunction( - AddonModLesson.instance.finishRetake.bind(AddonModLesson.instance, this.lesson, this.courseId, options), + AddonModLesson.finishRetake.bind(AddonModLesson.instance, this.lesson, this.courseId, options), options, ); @@ -413,14 +413,14 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { // Format activity link if present. if (this.eolData.activitylink) { - this.activityLink = AddonModLessonHelper.instance.formatActivityLink( this.eolData.activitylink.value); + this.activityLink = AddonModLessonHelper.formatActivityLink( this.eolData.activitylink.value); } else { this.activityLink = undefined; } // Format review lesson if present. if (this.eolData.reviewlesson) { - const params = CoreUrlUtils.instance.extractUrlParams( this.eolData.reviewlesson.value); + const params = CoreUrlUtils.extractUrlParams( this.eolData.reviewlesson.value); if (!params || !params.pageid) { // No pageid in the URL, the user cannot review (probably didn't answer any question). @@ -442,7 +442,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { // Not a valid page, return to entry view. // This happens, for example, when the user clicks to go to previous page and there is no previous page. this.forceLeave = true; - CoreNavigator.instance.back(); + CoreNavigator.back(); return; } else if (pageId == AddonModLessonProvider.LESSON_EOL) { @@ -469,10 +469,10 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { // Review mode, no need to launch the retake. } else if (!this.offline) { // Not in offline mode, launch the retake. - data = await AddonModLesson.instance.launchRetake(this.lesson!.id, this.password, pageId); + data = await AddonModLesson.launchRetake(this.lesson!.id, this.password, pageId); } else { // Check if there is a finished offline retake. - const finished = await AddonModLessonOffline.instance.hasFinishedRetake(this.lesson!.id); + const finished = await AddonModLessonOffline.hasFinishedRetake(this.lesson!.id); if (finished) { // Always show EOL page. pageId = AddonModLessonProvider.LESSON_EOL; @@ -484,7 +484,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { if (this.lesson!.timelimit && !this.accessInfo!.canmanage) { // Get the last lesson timer. - const timers = await AddonModLesson.instance.getTimers(this.lesson!.id, { + const timers = await AddonModLesson.getTimers(this.lesson!.id, { cmId: this.lesson!.coursemodule, readingStrategy: CoreSitesReadingStrategy.OnlyNetwork, }); @@ -515,13 +515,13 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { }; const pages = await this.callFunction( - AddonModLesson.instance.getPages.bind(AddonModLesson.instance, this.lessonId, options), + AddonModLesson.getPages.bind(AddonModLesson.instance, this.lessonId, options), options, ); this.lessonPages = pages.map((entry) => entry.page); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading menu.'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading menu.'); } finally { this.loadingMenu = false; } @@ -551,7 +551,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { }; const data = await this.callFunction( - AddonModLesson.instance.getPageData.bind(AddonModLesson.instance, this.lesson, pageId, options), + AddonModLesson.getPageData.bind(AddonModLesson.instance, this.lesson, pageId, options), options, ); @@ -562,7 +562,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { this.pageData = data; this.title = data.page!.title; - this.pageContent = AddonModLessonHelper.instance.getPageContentsFromPageData(data); + this.pageContent = AddonModLessonHelper.getPageContentsFromPageData(data); this.loaded = true; this.currentPage = pageId; this.messages = this.messages.concat(data.messages); @@ -570,14 +570,14 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { // Page loaded, hide EOL and feedback data if shown. this.eolData = this.processData = undefined; - if (AddonModLesson.instance.isQuestionPage(data.page!.type)) { + if (AddonModLesson.isQuestionPage(data.page!.type)) { // Create an empty FormGroup without controls, they will be added in getQuestionFromPageData. this.questionForm = this.formBuilder.group({}); this.pageButtons = []; - this.question = AddonModLessonHelper.instance.getQuestionFromPageData(this.questionForm, data); + this.question = AddonModLessonHelper.getQuestionFromPageData(this.questionForm, data); this.originalData = this.questionForm.getRawValue(); // Use getRawValue to include disabled values. } else { - this.pageButtons = AddonModLessonHelper.instance.getPageButtonsFromHtml(data.pagecontent || ''); + this.pageButtons = AddonModLessonHelper.getPageButtonsFromHtml(data.pagecontent || ''); this.question = undefined; this.originalData = undefined; } @@ -615,7 +615,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { try { const result = await this.callFunction( - AddonModLesson.instance.processPage.bind( + AddonModLesson.processPage.bind( AddonModLesson.instance, this.lesson, this.courseId, @@ -627,14 +627,14 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { ); if (formSubmitted) { - CoreDomUtils.instance.triggerFormSubmittedEvent( + CoreDomUtils.triggerFormSubmittedEvent( this.formElement, result.sent, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } - if (!this.offline && !this.review && AddonModLesson.instance.isLessonOffline(this.lesson!)) { + if (!this.offline && !this.review && AddonModLesson.isLessonOffline(this.lesson!)) { // Lesson allows offline and the user changed some data in server. Update cached data. const retake = this.accessInfo!.attemptscount; const options = { @@ -643,10 +643,10 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { }; // Update in background the list of content pages viewed or question attempts. - if (AddonModLesson.instance.isQuestionPage(this.pageData?.page?.type || -1)) { - AddonModLesson.instance.getQuestionsAttemptsOnline(this.lessonId, retake, options); + if (AddonModLesson.isQuestionPage(this.pageData?.page?.type || -1)) { + AddonModLesson.getQuestionsAttemptsOnline(this.lessonId, retake, options); } else { - AddonModLesson.instance.getContentPagesViewedOnline(this.lessonId, retake, options); + AddonModLesson.getContentPagesViewedOnline(this.lessonId, retake, options); } } @@ -656,7 +656,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { } // Not inmediate jump, show the feedback. - result.feedback = AddonModLessonHelper.instance.removeQuestionFromFeedback(result.feedback); + result.feedback = AddonModLessonHelper.removeQuestionFromFeedback(result.feedback); this.messages = result.messages; this.processData = result; this.processDataButtons = []; @@ -689,7 +689,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { }); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error processing page'); + CoreDomUtils.showErrorModalDefault(error, 'Error processing page'); } finally { this.loaded = true; } @@ -708,7 +708,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { try { await this.loadPage(pageId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading page'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading page'); } finally { this.loaded = true; } @@ -726,7 +726,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { this.loaded = false; // Use getRawValue to include disabled values. - const data = AddonModLessonHelper.instance.prepareQuestionData(this.question!, this.questionForm!.getRawValue()); + const data = AddonModLessonHelper.prepareQuestionData(this.question!, this.questionForm!.getRawValue()); this.processPage(data, true).finally(() => { this.loaded = true; @@ -744,7 +744,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { try { await this.finishRetake(true); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error finishing attempt'); + CoreDomUtils.showErrorModalDefault(error, 'Error finishing attempt'); } finally { this.loaded = true; } @@ -758,7 +758,7 @@ export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { async showMenu(): Promise { this.menuShown = true; - const menuModal = await ModalController.instance.create({ + const menuModal = await ModalController.create({ component: AddonModLessonMenuModalPage, componentProps: { pageInstance: this, diff --git a/src/addons/mod/lesson/pages/user-retake/user-retake.ts b/src/addons/mod/lesson/pages/user-retake/user-retake.ts index 31c736f73..771a8e4c9 100644 --- a/src/addons/mod/lesson/pages/user-retake/user-retake.ts +++ b/src/addons/mod/lesson/pages/user-retake/user-retake.ts @@ -64,10 +64,10 @@ export class AddonModLessonUserRetakePage implements OnInit { * Component being initialized. */ ngOnInit(): void { - this.lessonId = CoreNavigator.instance.getRouteNumberParam('lessonId')!; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.userId = CoreNavigator.instance.getRouteNumberParam('userId') || CoreSites.instance.getCurrentSiteUserId(); - this.retakeNumber = CoreNavigator.instance.getRouteNumberParam('retake'); + this.lessonId = CoreNavigator.getRouteNumberParam('lessonId')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.userId = CoreNavigator.getRouteNumberParam('userId') || CoreSites.getCurrentSiteUserId(); + this.retakeNumber = CoreNavigator.getRouteNumberParam('retake'); // Fetch the data. this.fetchData().finally(() => { @@ -87,7 +87,7 @@ export class AddonModLessonUserRetakePage implements OnInit { await this.setRetake(retakeNumber); } catch (error) { this.selectedRetake = this.previousSelectedRetake; - CoreDomUtils.instance.showErrorModal(CoreUtils.instance.addDataNotDownloadedError(error, 'Error getting attempt.')); + CoreDomUtils.showErrorModal(CoreUtils.addDataNotDownloadedError(error, 'Error getting attempt.')); } finally { this.loaded = true; } @@ -111,10 +111,10 @@ export class AddonModLessonUserRetakePage implements OnInit { */ protected async fetchData(): Promise { try { - this.lesson = await AddonModLesson.instance.getLessonById(this.courseId, this.lessonId); + this.lesson = await AddonModLesson.getLessonById(this.courseId, this.lessonId); // Get the retakes overview for all participants. - const data = await AddonModLesson.instance.getRetakesOverview(this.lesson.id, { + const data = await AddonModLesson.getRetakesOverview(this.lesson.id, { cmId: this.lesson.coursemodule, }); @@ -122,22 +122,22 @@ export class AddonModLessonUserRetakePage implements OnInit { const student: StudentData | undefined = data?.students?.find(student => student.id == this.userId); if (!student) { // Student not found. - throw new CoreError(Translate.instance.instant('addon.mod_lesson.cannotfinduser')); + throw new CoreError(Translate.instant('addon.mod_lesson.cannotfinduser')); } if (!student.attempts.length) { // No retakes. - throw new CoreError(Translate.instance.instant('addon.mod_lesson.cannotfindattempt')); + throw new CoreError(Translate.instant('addon.mod_lesson.cannotfindattempt')); } - student.bestgrade = CoreTextUtils.instance.roundToDecimals(student.bestgrade, 2); + student.bestgrade = CoreTextUtils.roundToDecimals(student.bestgrade, 2); student.attempts.forEach((retake) => { if (!this.selectedRetake && this.retakeNumber == retake.try) { // The retake specified as parameter exists. Use it. this.selectedRetake = this.retakeNumber; } - retake.label = AddonModLessonHelper.instance.getRetakeLabel(retake); + retake.label = AddonModLessonHelper.getRetakeLabel(retake); }); if (!this.selectedRetake) { @@ -146,14 +146,14 @@ export class AddonModLessonUserRetakePage implements OnInit { } // Get the profile image of the user. - const user = await CoreUtils.instance.ignoreErrors(CoreUser.instance.getProfile(student.id, this.courseId, true)); + const user = await CoreUtils.ignoreErrors(CoreUser.getProfile(student.id, this.courseId, true)); this.student = student; this.student.profileimageurl = user?.profileimageurl; await this.setRetake(this.selectedRetake); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting data.', true); + CoreDomUtils.showErrorModalDefault(error, 'Error getting data.', true); } } @@ -165,13 +165,13 @@ export class AddonModLessonUserRetakePage implements OnInit { protected async refreshData(): Promise { const promises: Promise[] = []; - promises.push(AddonModLesson.instance.invalidateLessonData(this.courseId)); + promises.push(AddonModLesson.invalidateLessonData(this.courseId)); if (this.lesson) { - promises.push(AddonModLesson.instance.invalidateRetakesOverview(this.lesson.id)); - promises.push(AddonModLesson.instance.invalidateUserRetakesForUser(this.lesson.id, this.userId)); + promises.push(AddonModLesson.invalidateRetakesOverview(this.lesson.id)); + promises.push(AddonModLesson.invalidateUserRetakesForUser(this.lesson.id, this.userId)); } - await CoreUtils.instance.ignoreErrors(Promise.all(promises)); + await CoreUtils.ignoreErrors(Promise.all(promises)); await this.fetchData(); } @@ -185,7 +185,7 @@ export class AddonModLessonUserRetakePage implements OnInit { protected async setRetake(retakeNumber: number): Promise { this.selectedRetake = retakeNumber; - const retakeData = await AddonModLesson.instance.getUserRetake(this.lessonId, retakeNumber, { + const retakeData = await AddonModLesson.getUserRetake(this.lessonId, retakeNumber, { cmId: this.lesson!.coursemodule, userId: this.userId, }); @@ -205,28 +205,28 @@ export class AddonModLessonUserRetakePage implements OnInit { if (formattedData.userstats.gradeinfo) { // Completed. - formattedData.userstats.grade = CoreTextUtils.instance.roundToDecimals(formattedData.userstats.grade, 2); - this.timeTakenReadable = CoreTimeUtils.instance.formatTime(formattedData.userstats.timetotake); + formattedData.userstats.grade = CoreTextUtils.roundToDecimals(formattedData.userstats.grade, 2); + this.timeTakenReadable = CoreTimeUtils.formatTime(formattedData.userstats.timetotake); } // Format pages data. formattedData.answerpages.forEach((page) => { - if (AddonModLesson.instance.answerPageIsContent(page)) { + if (AddonModLesson.answerPageIsContent(page)) { page.isContent = true; if (page.answerdata?.answers) { page.answerdata.answers.forEach((answer) => { // Content pages only have 1 valid field in the answer array. - answer[0] = AddonModLessonHelper.instance.getContentPageAnswerDataFromHtml(answer[0]); + answer[0] = AddonModLessonHelper.getContentPageAnswerDataFromHtml(answer[0]); }); } - } else if (AddonModLesson.instance.answerPageIsQuestion(page)) { + } else if (AddonModLesson.answerPageIsQuestion(page)) { page.isQuestion = true; if (page.answerdata?.answers) { page.answerdata.answers.forEach((answer) => { // Only the first field of the answer array requires to be parsed. - answer[0] = AddonModLessonHelper.instance.getQuestionPageAnswerDataFromHtml(answer[0]); + answer[0] = AddonModLessonHelper.getQuestionPageAnswerDataFromHtml(answer[0]); }); } } diff --git a/src/addons/mod/lesson/services/handlers/grade-link.ts b/src/addons/mod/lesson/services/handlers/grade-link.ts index 49df7a159..4478201e9 100644 --- a/src/addons/mod/lesson/services/handlers/grade-link.ts +++ b/src/addons/mod/lesson/services/handlers/grade-link.ts @@ -53,18 +53,18 @@ export class AddonModLessonGradeLinkHandlerService extends CoreContentLinksModul ): Promise { const moduleId = Number(params.id); - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { - const module = await CoreCourse.instance.getModuleBasicInfo(moduleId, siteId); + const module = await CoreCourse.getModuleBasicInfo(moduleId, siteId); courseId = Number(module.course || courseId || params.courseid || params.cid); // Check if the user can see the user reports in the lesson. - const accessInfo = await AddonModLesson.instance.getAccessInformation(module.instance, { cmId: module.id, siteId }); + const accessInfo = await AddonModLesson.getAccessInformation(module.instance, { cmId: module.id, siteId }); if (accessInfo.canviewreports) { // User can view reports, go to view the report. - CoreNavigator.instance.navigateToSitePath( + CoreNavigator.navigateToSitePath( AddonModLessonModuleHandlerService.PAGE_NAME + `/user-retake/${courseId}/${module.instance}`, { params: { userId: Number(params.userid) }, @@ -73,10 +73,10 @@ export class AddonModLessonGradeLinkHandlerService extends CoreContentLinksModul ); } else { // User cannot view the report, go to lesson index. - CoreCourseHelper.instance.navigateToModule(moduleId, siteId, courseId, module.section); + CoreCourseHelper.navigateToModule(moduleId, siteId, courseId, module.section); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errorgetmodule', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); } finally { modal.dismiss(); } @@ -94,9 +94,9 @@ export class AddonModLessonGradeLinkHandlerService extends CoreContentLinksModul */ // eslint-disable-next-line @typescript-eslint/no-unused-vars async isEnabled(siteId: string, url: string, params: Record, courseId?: number): Promise { - return AddonModLesson.instance.isPluginEnabled(siteId); + return AddonModLesson.isPluginEnabled(siteId); } } -export class AddonModLessonGradeLinkHandler extends makeSingleton(AddonModLessonGradeLinkHandlerService) {} +export const AddonModLessonGradeLinkHandler = makeSingleton(AddonModLessonGradeLinkHandlerService); diff --git a/src/addons/mod/lesson/services/handlers/index-link.ts b/src/addons/mod/lesson/services/handlers/index-link.ts index f49ea7c07..03da03b76 100644 --- a/src/addons/mod/lesson/services/handlers/index-link.ts +++ b/src/addons/mod/lesson/services/handlers/index-link.ts @@ -60,7 +60,7 @@ export class AddonModLessonIndexLinkHandlerService extends CoreContentLinksModul if (params.userpassword) { this.navigateToModuleWithPassword(parseInt(params.id, 10), courseId!, params.userpassword, siteId); } else { - CoreCourseHelper.instance.navigateToModule(parseInt(params.id, 10), siteId, courseId); + CoreCourseHelper.navigateToModule(parseInt(params.id, 10), siteId, courseId); } }, }]; @@ -78,7 +78,7 @@ export class AddonModLessonIndexLinkHandlerService extends CoreContentLinksModul */ // eslint-disable-next-line @typescript-eslint/no-unused-vars isEnabled(siteId: string, url: string, params: Record, courseId?: number): Promise { - return AddonModLesson.instance.isPluginEnabled(siteId); + return AddonModLesson.isPluginEnabled(siteId); } /** @@ -96,21 +96,21 @@ export class AddonModLessonIndexLinkHandlerService extends CoreContentLinksModul password: string, siteId: string, ): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { // Get the module. - const module = await CoreCourse.instance.getModuleBasicInfo(moduleId, siteId); + const module = await CoreCourse.getModuleBasicInfo(moduleId, siteId); courseId = courseId || module.course; // Store the password so it's automatically used. - await CoreUtils.instance.ignoreErrors(AddonModLesson.instance.storePassword(module.instance, password, siteId)); + await CoreUtils.ignoreErrors(AddonModLesson.storePassword(module.instance, password, siteId)); - await CoreCourseHelper.instance.navigateToModule(moduleId, siteId, courseId, module.section); + await CoreCourseHelper.navigateToModule(moduleId, siteId, courseId, module.section); } catch { // Error, go to index page. - await CoreCourseHelper.instance.navigateToModule(moduleId, siteId, courseId); + await CoreCourseHelper.navigateToModule(moduleId, siteId, courseId); } finally { modal.dismiss(); } @@ -118,4 +118,4 @@ export class AddonModLessonIndexLinkHandlerService extends CoreContentLinksModul } -export class AddonModLessonIndexLinkHandler extends makeSingleton(AddonModLessonIndexLinkHandlerService) {} +export const AddonModLessonIndexLinkHandler = makeSingleton(AddonModLessonIndexLinkHandlerService); diff --git a/src/addons/mod/lesson/services/handlers/list-link.ts b/src/addons/mod/lesson/services/handlers/list-link.ts index ac466dfa1..16e69fb25 100644 --- a/src/addons/mod/lesson/services/handlers/list-link.ts +++ b/src/addons/mod/lesson/services/handlers/list-link.ts @@ -37,9 +37,9 @@ export class AddonModLessonListLinkHandlerService extends CoreContentLinksModule */ // eslint-disable-next-line @typescript-eslint/no-unused-vars isEnabled(siteId: string, url: string, params: Record, courseId?: number): Promise { - return AddonModLesson.instance.isPluginEnabled(siteId); + return AddonModLesson.isPluginEnabled(siteId); } } -export class AddonModLessonListLinkHandler extends makeSingleton(AddonModLessonListLinkHandlerService) {} +export const AddonModLessonListLinkHandler = makeSingleton(AddonModLessonListLinkHandlerService); diff --git a/src/addons/mod/lesson/services/handlers/module.ts b/src/addons/mod/lesson/services/handlers/module.ts index e2413c3a8..c094f2170 100644 --- a/src/addons/mod/lesson/services/handlers/module.ts +++ b/src/addons/mod/lesson/services/handlers/module.ts @@ -53,7 +53,7 @@ export class AddonModLessonModuleHandlerService implements CoreCourseModuleHandl * @return Promise resolved with boolean: whether or not the handler is enabled on a site level. */ isEnabled(): Promise { - return AddonModLesson.instance.isPluginEnabled(); + return AddonModLesson.isPluginEnabled(); } /** @@ -72,7 +72,7 @@ export class AddonModLessonModuleHandlerService implements CoreCourseModuleHandl forCoursePage?: boolean, // eslint-disable-line @typescript-eslint/no-unused-vars ): CoreCourseModuleHandlerData { return { - icon: CoreCourse.instance.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), + icon: CoreCourse.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), title: module.name, class: 'addon-mod_lesson-handler', showDownloadButton: true, @@ -82,7 +82,7 @@ export class AddonModLessonModuleHandlerService implements CoreCourseModuleHandl Object.assign(options.params, { module }); const routeParams = '/' + courseId + '/' + module.id; - CoreNavigator.instance.navigateToSitePath(AddonModLessonModuleHandlerService.PAGE_NAME + routeParams, options); + CoreNavigator.navigateToSitePath(AddonModLessonModuleHandlerService.PAGE_NAME + routeParams, options); }, }; } @@ -102,4 +102,4 @@ export class AddonModLessonModuleHandlerService implements CoreCourseModuleHandl } -export class AddonModLessonModuleHandler extends makeSingleton(AddonModLessonModuleHandlerService) {} +export const AddonModLessonModuleHandler = makeSingleton(AddonModLessonModuleHandlerService); diff --git a/src/addons/mod/lesson/services/handlers/prefetch.ts b/src/addons/mod/lesson/services/handlers/prefetch.ts index 6cb182a06..7180e172c 100644 --- a/src/addons/mod/lesson/services/handlers/prefetch.ts +++ b/src/addons/mod/lesson/services/handlers/prefetch.ts @@ -54,7 +54,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref */ protected async askUserPassword(): Promise { // Create and show the modal. - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: AddonModLessonPasswordModalComponent, }); @@ -78,9 +78,9 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref * @return Promise resolved with the size. */ async getDownloadSize(module: CoreCourseAnyModuleData, courseId: number, single?: boolean): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); - let lesson = await AddonModLesson.instance.getLesson(courseId, module.id, { siteId }); + let lesson = await AddonModLesson.getLesson(courseId, module.id, { siteId }); // Get the lesson password if it's needed. const passwordData = await this.getLessonPassword(lesson.id, { @@ -95,10 +95,10 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref let files = lesson.mediafiles || []; files = files.concat(this.getIntroFilesFromInstance(module, lesson)); - const result = await CorePluginFileDelegate.instance.getFilesDownloadSize(files); + const result = await CorePluginFileDelegate.getFilesDownloadSize(files); // Get the pages to calculate the size. - const pages = await AddonModLesson.instance.getPages(lesson.id, { + const pages = await AddonModLesson.getPages(lesson.id, { cmId: module.id, password: passwordData.password, siteId, @@ -123,10 +123,10 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref options: AddonModLessonGetPasswordOptions = {}, ): Promise { - options.siteId = options.siteId || CoreSites.instance.getCurrentSiteId(); + options.siteId = options.siteId || CoreSites.getCurrentSiteId(); // Get access information to check if password is needed. - const accessInfo = await AddonModLesson.instance.getAccessInformation(lessonId, options); + const accessInfo = await AddonModLesson.getAccessInformation(lessonId, options); if (!accessInfo.preventaccessreasons.length) { // Password not needed. @@ -134,7 +134,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref } const passwordNeeded = accessInfo.preventaccessreasons.length == 1 && - AddonModLesson.instance.isPasswordProtected(accessInfo); + AddonModLesson.isPasswordProtected(accessInfo); if (!passwordNeeded) { // Lesson cannot be played, reject. @@ -142,7 +142,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref } // The lesson requires a password. Check if there is one in DB. - let password = await CoreUtils.instance.ignoreErrors(AddonModLesson.instance.getStoredPassword(lessonId)); + let password = await CoreUtils.ignoreErrors(AddonModLesson.getStoredPassword(lessonId)); if (password) { try { @@ -173,9 +173,9 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref async invalidateContent(moduleId: number, courseId: number): Promise { // Only invalidate the data that doesn't ignore cache when prefetching. await Promise.all([ - AddonModLesson.instance.invalidateLessonData(courseId), - CoreCourse.instance.invalidateModule(moduleId), - CoreGroups.instance.invalidateActivityAllowedGroups(moduleId), + AddonModLesson.invalidateLessonData(courseId), + CoreCourse.invalidateModule(moduleId), + CoreGroups.invalidateActivityAllowedGroups(moduleId), ]); } @@ -188,16 +188,16 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref */ async invalidateModule(module: CoreCourseAnyModuleData, courseId: number): Promise { // Invalidate data to determine if module is downloadable. - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); - const lesson = await AddonModLesson.instance.getLesson(courseId, module.id, { + const lesson = await AddonModLesson.getLesson(courseId, module.id, { readingStrategy: CoreSitesReadingStrategy.PreferCache, siteId, }); await Promise.all([ - AddonModLesson.instance.invalidateLessonData(courseId, siteId), - AddonModLesson.instance.invalidateAccessInformation(lesson.id, siteId), + AddonModLesson.invalidateLessonData(courseId, siteId), + AddonModLesson.invalidateAccessInformation(lesson.id, siteId), ]); } @@ -209,19 +209,19 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref * @return Whether the module can be downloaded. The promise should never be rejected. */ async isDownloadable(module: CoreCourseAnyModuleData, courseId: number): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); - const lesson = await AddonModLesson.instance.getLesson(courseId, module.id, { siteId }); - const accessInfo = await AddonModLesson.instance.getAccessInformation(lesson.id, { cmId: module.id, siteId }); + const lesson = await AddonModLesson.getLesson(courseId, module.id, { siteId }); + const accessInfo = await AddonModLesson.getAccessInformation(lesson.id, { cmId: module.id, siteId }); // If it's a student and lesson isn't offline, it isn't downloadable. - if (!accessInfo.canviewreports && !AddonModLesson.instance.isLessonOffline(lesson)) { + if (!accessInfo.canviewreports && !AddonModLesson.isLessonOffline(lesson)) { return false; } // It's downloadable if there are no prevent access reasons or there is just 1 and it's password. return !accessInfo.preventaccessreasons.length || - (accessInfo.preventaccessreasons.length == 1 && AddonModLesson.instance.isPasswordProtected(accessInfo)); + (accessInfo.preventaccessreasons.length == 1 && AddonModLesson.isPasswordProtected(accessInfo)); } /** @@ -230,7 +230,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref * @return Promise resolved with a boolean indicating if the handler is enabled. */ isEnabled(): Promise { - return AddonModLesson.instance.isPluginEnabled(); + return AddonModLesson.isPluginEnabled(); } /** @@ -256,8 +256,8 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref * @return Promise resolved when done. */ protected async prefetchLesson(module: CoreCourseAnyModuleData, courseId?: number, single?: boolean): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); - courseId = courseId || module.course || CoreSites.instance.getCurrentSiteHomeId(); + const siteId = CoreSites.getCurrentSiteId(); + courseId = courseId || module.course || CoreSites.getCurrentSiteHomeId(); const commonOptions = { readingStrategy: CoreSitesReadingStrategy.OnlyNetwork, @@ -268,7 +268,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref ...commonOptions, // Include all common options. }; - let lesson = await AddonModLesson.instance.getLesson(courseId, module.id, commonOptions); + let lesson = await AddonModLesson.getLesson(courseId, module.id, commonOptions); // Get the lesson password if it's needed. const passwordData = await this.getLessonPassword(lesson.id, { @@ -281,7 +281,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref let accessInfo = passwordData.accessInfo; const password = passwordData.password; - if (AddonModLesson.instance.isLessonOffline(lesson) && !AddonModLesson.instance.leftDuringTimed(accessInfo)) { + if (AddonModLesson.isLessonOffline(lesson) && !AddonModLesson.leftDuringTimed(accessInfo)) { // The user didn't left during a timed session. Call launch retake to make sure there is a started retake. accessInfo = await this.launchRetake(lesson.id, password, modOptions, siteId); } @@ -290,9 +290,9 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref // Download intro files and media files. const files = (lesson.mediafiles || []).concat(this.getIntroFilesFromInstance(module, lesson)); - promises.push(CoreFilepool.instance.addFilesToQueue(siteId, files, this.component, module.id)); + promises.push(CoreFilepool.addFilesToQueue(siteId, files, this.component, module.id)); - if (AddonModLesson.instance.isLessonOffline(lesson)) { + if (AddonModLesson.isLessonOffline(lesson)) { promises.push(this.prefetchPlayData(lesson, password, accessInfo.attemptscount, modOptions)); } @@ -319,11 +319,11 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref siteId: string, ): Promise { // The user didn't left during a timed session. Call launch retake to make sure there is a started retake. - await AddonModLesson.instance.launchRetake(lessonId, password, undefined, false, siteId); + await AddonModLesson.launchRetake(lessonId, password, undefined, false, siteId); const results = await Promise.all([ - CoreUtils.instance.ignoreErrors(CoreFilepool.instance.updatePackageDownloadTime(siteId, this.component, module.id)), - AddonModLesson.instance.getAccessInformation(lessonId, modOptions), + CoreUtils.ignoreErrors(CoreFilepool.updatePackageDownloadTime(siteId, this.component, module.id)), + AddonModLesson.getAccessInformation(lessonId, modOptions), ]); return results[1]; @@ -352,11 +352,11 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref await Promise.all([ this.prefetchPagesData(lesson, passwordOptions), // Prefetch user timers to be able to calculate timemodified in offline. - CoreUtils.instance.ignoreErrors(AddonModLesson.instance.getTimers(lesson.id, modOptions)), + CoreUtils.ignoreErrors(AddonModLesson.getTimers(lesson.id, modOptions)), // Prefetch viewed pages in last retake to calculate progress. - AddonModLesson.instance.getContentPagesViewedOnline(lesson.id, retake, modOptions), + AddonModLesson.getContentPagesViewedOnline(lesson.id, retake, modOptions), // Prefetch question attempts in last retake for offline calculations. - AddonModLesson.instance.getQuestionsAttemptsOnline(lesson.id, retake, modOptions), + AddonModLesson.getQuestionsAttemptsOnline(lesson.id, retake, modOptions), ]); } @@ -371,7 +371,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref lesson: AddonModLessonLessonWSData, options: AddonModLessonPasswordOptions, ): Promise { - const pages = await AddonModLesson.instance.getPages(lesson.id, options); + const pages = await AddonModLesson.getPages(lesson.id, options); let hasRandomBranch = false; @@ -388,7 +388,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref } // Get the page data. We don't pass accessInfo because we don't need to calculate the offline data. - const pageData = await AddonModLesson.instance.getPageData(lesson, data.page.id, { + const pageData = await AddonModLesson.getPageData(lesson, data.page.id, { includeContents: true, includeOfflineData: false, ...options, // Include all options. @@ -402,7 +402,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref pageFiles = pageFiles.concat(answer.responsefiles); }); - await CoreFilepool.instance.addFilesToQueue(options.siteId!, pageFiles, this.component, module.id); + await CoreFilepool.addFilesToQueue(options.siteId!, pageFiles, this.component, module.id); }); // Prefetch the list of possible jumps for offline navigation. Do it here because we know hasRandomBranch. @@ -425,11 +425,11 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref modOptions: CoreCourseCommonModWSOptions, ): Promise { try { - await AddonModLesson.instance.getPagesPossibleJumps(lessonId, modOptions); + await AddonModLesson.getPagesPossibleJumps(lessonId, modOptions); } catch (error) { if (hasRandomBranch) { // The WebSevice probably failed because RANDOMBRANCH aren't supported if the user hasn't seen any page. - throw new CoreError(Translate.instance.instant('addon.mod_lesson.errorprefetchrandombranch')); + throw new CoreError(Translate.instant('addon.mod_lesson.errorprefetchrandombranch')); } throw error; @@ -449,10 +449,10 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref lessonId: number, modOptions: CoreCourseCommonModWSOptions, ): Promise { - const groupInfo = await CoreGroups.instance.getActivityGroupInfo(moduleId, false, undefined, modOptions.siteId, true); + const groupInfo = await CoreGroups.getActivityGroupInfo(moduleId, false, undefined, modOptions.siteId, true); await Promise.all(groupInfo.groups?.map(async (group) => { - await AddonModLesson.instance.getRetakesOverview(lessonId, { + await AddonModLesson.getRetakesOverview(lessonId, { groupId: group.id, ...modOptions, // Include all options. }); @@ -473,7 +473,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref modOptions: CoreCourseCommonModWSOptions, ): Promise { // Always get all participants, even if there are no groups. - const data = await AddonModLesson.instance.getRetakesOverview(lessonId, modOptions); + const data = await AddonModLesson.getRetakesOverview(lessonId, modOptions); if (!data || !data.students) { return; } @@ -485,7 +485,7 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref return; } - const attempt = await AddonModLesson.instance.getUserRetake(lessonId, lastRetake.try, { + const attempt = await AddonModLesson.getUserRetake(lessonId, lastRetake.try, { userId: student.id, ...modOptions, // Include all options. }); @@ -502,11 +502,11 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref } answerPage.answerdata?.answers?.forEach((answer) => { - files.push(...CoreFilepool.instance.extractDownloadableFilesFromHtmlAsFakeFileObjects(answer[0])); + files.push(...CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(answer[0])); }); }); - await CoreFilepool.instance.addFilesToQueue(modOptions.siteId!, files, this.component, moduleId); + await CoreFilepool.addFilesToQueue(modOptions.siteId!, files, this.component, moduleId); })); } @@ -526,15 +526,15 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref options: CoreCourseCommonModWSOptions = {}, ): Promise { - options.siteId = options.siteId || CoreSites.instance.getCurrentSiteId(); + options.siteId = options.siteId || CoreSites.getCurrentSiteId(); - const lesson = await AddonModLesson.instance.getLessonWithPassword(lessonId, { + const lesson = await AddonModLesson.getLessonWithPassword(lessonId, { password, ...options, // Include all options. }); // Password is ok, store it and return the data. - await AddonModLesson.instance.storePassword(lesson.id, password, options.siteId); + await AddonModLesson.storePassword(lesson.id, password, options.siteId); return { password, @@ -552,12 +552,12 @@ export class AddonModLessonPrefetchHandlerService extends CoreCourseActivityPref * @return Promise resolved when done. */ sync(module: CoreCourseAnyModuleData, courseId: number, siteId?: string): Promise { - return AddonModLessonSync.instance.syncLesson(module.instance!, false, false, siteId); + return AddonModLessonSync.syncLesson(module.instance!, false, false, siteId); } } -export class AddonModLessonPrefetchHandler extends makeSingleton(AddonModLessonPrefetchHandlerService) {} +export const AddonModLessonPrefetchHandler = makeSingleton(AddonModLessonPrefetchHandlerService); /** * Options to pass to get lesson password. diff --git a/src/addons/mod/lesson/services/handlers/push-click.ts b/src/addons/mod/lesson/services/handlers/push-click.ts index 82aa5f647..f78710b25 100644 --- a/src/addons/mod/lesson/services/handlers/push-click.ts +++ b/src/addons/mod/lesson/services/handlers/push-click.ts @@ -38,10 +38,10 @@ export class AddonModLessonPushClickHandlerService implements CorePushNotificati * @return Whether the notification click is handled by this handler. */ async handles(notification: NotificationData): Promise { - if (CoreUtils.instance.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'mod_lesson' && + if (CoreUtils.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'mod_lesson' && notification.name == 'graded_essay') { - return CoreGrades.instance.isPluginEnabledForCourse(Number(notification.courseid), notification.site); + return CoreGrades.isPluginEnabledForCourse(Number(notification.courseid), notification.site); } return false; @@ -58,12 +58,12 @@ export class AddonModLessonPushClickHandlerService implements CorePushNotificati const courseId = Number(notification.courseid); const moduleId = Number(data.cmid); - return CoreGradesHelper.instance.goToGrades(courseId, undefined, moduleId, notification.site); + return CoreGradesHelper.goToGrades(courseId, undefined, moduleId, notification.site); } } -export class AddonModLessonPushClickHandler extends makeSingleton(AddonModLessonPushClickHandlerService) {} +export const AddonModLessonPushClickHandler = makeSingleton(AddonModLessonPushClickHandlerService); type NotificationData = CorePushNotificationsNotificationBasicData & { courseid: number; diff --git a/src/addons/mod/lesson/services/handlers/report-link.ts b/src/addons/mod/lesson/services/handlers/report-link.ts index eee37ed45..59d545ae3 100644 --- a/src/addons/mod/lesson/services/handlers/report-link.ts +++ b/src/addons/mod/lesson/services/handlers/report-link.ts @@ -81,7 +81,7 @@ export class AddonModLessonReportLinkHandlerService extends CoreContentLinksHand return false; } - return AddonModLesson.instance.isPluginEnabled(siteId); + return AddonModLesson.isPluginEnabled(siteId); } /** @@ -96,11 +96,11 @@ export class AddonModLessonReportLinkHandlerService extends CoreContentLinksHand */ protected async openReportOverview(moduleId: number, courseId?: number, groupId?: number, siteId?: string): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { // Get the module object. - const module = await CoreCourse.instance.getModuleBasicInfo(moduleId, siteId); + const module = await CoreCourse.getModuleBasicInfo(moduleId, siteId); const params = { module: module, @@ -109,9 +109,9 @@ export class AddonModLessonReportLinkHandlerService extends CoreContentLinksHand group: groupId === undefined || isNaN(groupId) ? null : groupId, }; - CoreNavigator.instance.navigateToSitePath(AddonModLessonModuleHandlerService.PAGE_NAME, { params, siteId }); + CoreNavigator.navigateToSitePath(AddonModLessonModuleHandlerService.PAGE_NAME, { params, siteId }); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error processing link.'); + CoreDomUtils.showErrorModalDefault(error, 'Error processing link.'); } finally { modal.dismiss(); } @@ -137,11 +137,11 @@ export class AddonModLessonReportLinkHandlerService extends CoreContentLinksHand courseId?: number, ): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { // Get the module object. - const module = await CoreCourse.instance.getModuleBasicInfo(moduleId, siteId); + const module = await CoreCourse.getModuleBasicInfo(moduleId, siteId); courseId = courseId || module.course; const params = { @@ -149,12 +149,12 @@ export class AddonModLessonReportLinkHandlerService extends CoreContentLinksHand retake: retake || 0, }; - CoreNavigator.instance.navigateToSitePath( + CoreNavigator.navigateToSitePath( AddonModLessonModuleHandlerService.PAGE_NAME + `/user-retake/${courseId}/${module.instance}`, { params, siteId }, ); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error processing link.'); + CoreDomUtils.showErrorModalDefault(error, 'Error processing link.'); } finally { modal.dismiss(); } @@ -162,4 +162,4 @@ export class AddonModLessonReportLinkHandlerService extends CoreContentLinksHand } -export class AddonModLessonReportLinkHandler extends makeSingleton(AddonModLessonReportLinkHandlerService) {} +export const AddonModLessonReportLinkHandler = makeSingleton(AddonModLessonReportLinkHandlerService); diff --git a/src/addons/mod/lesson/services/handlers/sync-cron.ts b/src/addons/mod/lesson/services/handlers/sync-cron.ts index c2dfce3ca..1603ab835 100644 --- a/src/addons/mod/lesson/services/handlers/sync-cron.ts +++ b/src/addons/mod/lesson/services/handlers/sync-cron.ts @@ -35,7 +35,7 @@ export class AddonModLessonSyncCronHandlerService implements CoreCronHandler { * @return Promise resolved when done, rejected if failure. */ execute(siteId?: string, force?: boolean): Promise { - return AddonModLessonSync.instance.syncAllLessons(siteId, force); + return AddonModLessonSync.syncAllLessons(siteId, force); } /** @@ -44,9 +44,9 @@ export class AddonModLessonSyncCronHandlerService implements CoreCronHandler { * @return Time between consecutive executions (in ms). */ getInterval(): number { - return AddonModLessonSync.instance.syncInterval; + return AddonModLessonSync.syncInterval; } } -export class AddonModLessonSyncCronHandler extends makeSingleton(AddonModLessonSyncCronHandlerService) {} +export const AddonModLessonSyncCronHandler = makeSingleton(AddonModLessonSyncCronHandlerService); diff --git a/src/addons/mod/lesson/services/lesson-helper.ts b/src/addons/mod/lesson/services/lesson-helper.ts index 527f34e1d..f7035f99d 100644 --- a/src/addons/mod/lesson/services/lesson-helper.ts +++ b/src/addons/mod/lesson/services/lesson-helper.ts @@ -43,7 +43,7 @@ export class AddonModLessonHelperProvider { * @return Formatted data. */ formatActivityLink(activityLink: string): AddonModLessonActivityLink { - const element = CoreDomUtils.instance.convertToElement(activityLink); + const element = CoreDomUtils.convertToElement(activityLink); const anchor = element.querySelector('a'); if (!anchor) { @@ -73,7 +73,7 @@ export class AddonModLessonHelperProvider { buttonText: '', content: '', }; - const element = CoreDomUtils.instance.convertToElement(html); + const element = CoreDomUtils.convertToElement(html); // Search the input button. const button = element.querySelector('input[type="button"]'); @@ -97,7 +97,7 @@ export class AddonModLessonHelperProvider { */ getPageButtonsFromHtml(html: string): AddonModLessonPageButton[] { const buttons: AddonModLessonPageButton[] = []; - const element = CoreDomUtils.instance.convertToElement(html); + const element = CoreDomUtils.convertToElement(html); // Get the container of the buttons if it exists. let buttonsContainer = element.querySelector('.branchbuttoncontainer'); @@ -149,7 +149,7 @@ export class AddonModLessonHelperProvider { */ getPageContentsFromPageData(data: AddonModLessonGetPageDataWSResponse): string { // Search the page contents inside the whole page HTML. Use data.pagecontent because it's filtered. - const element = CoreDomUtils.instance.convertToElement(data.pagecontent || ''); + const element = CoreDomUtils.convertToElement(data.pagecontent || ''); const contents = element.querySelector('.contents'); if (contents) { @@ -157,7 +157,7 @@ export class AddonModLessonHelperProvider { } // Cannot find contents element. - if (AddonModLesson.instance.isQuestionPage(data.page?.type || -1) || + if (AddonModLesson.isQuestionPage(data.page?.type || -1) || data.page?.qtype == AddonModLessonProvider.LESSON_PAGE_BRANCHTABLE) { // Return page.contents to prevent having duplicated elements (some elements like videos might not work). return data.page?.contents || ''; @@ -175,7 +175,7 @@ export class AddonModLessonHelperProvider { * @return Question data. */ getQuestionFromPageData(questionForm: FormGroup, pageData: AddonModLessonGetPageDataWSResponse): AddonModLessonQuestion { - const element = CoreDomUtils.instance.convertToElement(pageData.pagecontent || ''); + const element = CoreDomUtils.convertToElement(pageData.pagecontent || ''); // Get the container of the question answers if it exists. const fieldContainer = element.querySelector('.fcontainer'); @@ -190,7 +190,7 @@ export class AddonModLessonHelperProvider { const submitButton = element.querySelector('input[type="submit"]'); const question: AddonModLessonQuestion = { template: '', - submitLabel: submitButton ? submitButton.value : Translate.instance.instant('addon.mod_lesson.submit'), + submitLabel: submitButton ? submitButton.value : Translate.instant('addon.mod_lesson.submit'), }; if (!fieldContainer) { @@ -455,7 +455,7 @@ export class AddonModLessonHelperProvider { * @return Object with the data to render the answer. If the answer doesn't require any parsing, return a string with the HTML. */ getQuestionPageAnswerDataFromHtml(html: string): AddonModLessonAnswerData { - const element = CoreDomUtils.instance.convertToElement(html); + const element = CoreDomUtils.convertToElement(html); // Check if it has a checkbox. let input = element.querySelector('input[type="checkbox"][name*="answer"]'); @@ -526,21 +526,21 @@ export class AddonModLessonHelperProvider { if (hasGrade || retake.end) { // Retake finished with or without grade (if the lesson only has content pages, it has no grade). if (hasGrade) { - data.grade = Translate.instance.instant('core.percentagenumber', { $a: retake.grade }); + data.grade = Translate.instant('core.percentagenumber', { $a: retake.grade }); } - data.timestart = CoreTimeUtils.instance.userDate(retake.timestart * 1000); + data.timestart = CoreTimeUtils.userDate(retake.timestart * 1000); if (includeDuration) { - data.duration = CoreTimeUtils.instance.formatTime(retake.timeend - retake.timestart); + data.duration = CoreTimeUtils.formatTime(retake.timeend - retake.timestart); } } else { // The user has not completed the retake. - data.grade = Translate.instance.instant('addon.mod_lesson.notcompleted'); + data.grade = Translate.instant('addon.mod_lesson.notcompleted'); if (retake.timestart) { - data.timestart = CoreTimeUtils.instance.userDate(retake.timestart * 1000); + data.timestart = CoreTimeUtils.userDate(retake.timestart * 1000); } } - return Translate.instance.instant('addon.mod_lesson.retakelabel' + (includeDuration ? 'full' : 'short'), data); + return Translate.instant('addon.mod_lesson.retakelabel' + (includeDuration ? 'full' : 'short'), data); } /** @@ -556,7 +556,7 @@ export class AddonModLessonHelperProvider { // Add some HTML to the answer if needed. if (textarea) { - data[textarea.name] = CoreTextUtils.instance.formatHtmlLines( data[textarea.name]); + data[textarea.name] = CoreTextUtils.formatHtmlLines( data[textarea.name]); } } else if (question.template == 'multichoice' && ( question).multi) { // Only send the options with value set to true. @@ -577,17 +577,17 @@ export class AddonModLessonHelperProvider { * @return Feedback without the question text. */ removeQuestionFromFeedback(html: string): string { - const element = CoreDomUtils.instance.convertToElement(html); + const element = CoreDomUtils.convertToElement(html); // Remove the question text. - CoreDomUtils.instance.removeElement(element, '.generalbox:not(.feedback):not(.correctanswer)'); + CoreDomUtils.removeElement(element, '.generalbox:not(.feedback):not(.correctanswer)'); return element.innerHTML.trim(); } } -export class AddonModLessonHelper extends makeSingleton(AddonModLessonHelperProvider) {} +export const AddonModLessonHelper = makeSingleton(AddonModLessonHelperProvider); /** * Page button data. diff --git a/src/addons/mod/lesson/services/lesson-offline.ts b/src/addons/mod/lesson/services/lesson-offline.ts index b557428f9..41b7f836a 100644 --- a/src/addons/mod/lesson/services/lesson-offline.ts +++ b/src/addons/mod/lesson/services/lesson-offline.ts @@ -44,7 +44,7 @@ export class AddonModLessonOfflineProvider { * @return Promise resolved when done. */ async deleteAttempt(lessonId: number, retake: number, pageId: number, timemodified: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(PAGE_ATTEMPTS_TABLE_NAME, > { lessonid: lessonId, @@ -62,7 +62,7 @@ export class AddonModLessonOfflineProvider { * @return Promise resolved when done. */ async deleteRetake(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(RETAKES_TABLE_NAME, > { lessonid: lessonId }); } @@ -77,7 +77,7 @@ export class AddonModLessonOfflineProvider { * @return Promise resolved when done. */ async deleteRetakeAttemptsForPage(lessonId: number, retake: number, pageId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(PAGE_ATTEMPTS_TABLE_NAME, > { lessonid: lessonId, @@ -106,14 +106,14 @@ export class AddonModLessonOfflineProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Get current stored retake (if any). If not found, it will create a new one. const entry = await this.getRetakeWithFallback(lessonId, courseId, retake, site.id); entry.finished = finished ? 1 : 0; entry.outoftime = outOfTime ? 1 : 0; - entry.timemodified = CoreTimeUtils.instance.timestamp(); + entry.timemodified = CoreTimeUtils.timestamp(); await site.getDb().insertRecord(RETAKES_TABLE_NAME, entry); } @@ -125,7 +125,7 @@ export class AddonModLessonOfflineProvider { * @return Promise resolved when the offline attempts are retrieved. */ async getAllAttempts(siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const attempts = await db.getAllRecords(PAGE_ATTEMPTS_TABLE_NAME); @@ -142,14 +142,14 @@ export class AddonModLessonOfflineProvider { const lessons: Record = {}; const [pageAttempts, retakes] = await Promise.all([ - CoreUtils.instance.ignoreErrors(this.getAllAttempts(siteId)), - CoreUtils.instance.ignoreErrors(this.getAllRetakes(siteId)), + CoreUtils.ignoreErrors(this.getAllAttempts(siteId)), + CoreUtils.ignoreErrors(this.getAllRetakes(siteId)), ]); this.getLessonsFromEntries(lessons, pageAttempts || []); this.getLessonsFromEntries(lessons, retakes || []); - return CoreUtils.instance.objectToArray(lessons); + return CoreUtils.objectToArray(lessons); } /** @@ -159,7 +159,7 @@ export class AddonModLessonOfflineProvider { * @return Promise resolved when the offline retakes are retrieved. */ async getAllRetakes(siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); return db.getAllRecords(RETAKES_TABLE_NAME); } @@ -177,7 +177,7 @@ export class AddonModLessonOfflineProvider { retake: number, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); try { const retakeData = await this.getRetakeWithFallback(lessonId, 0, retake, siteId); @@ -203,7 +203,7 @@ export class AddonModLessonOfflineProvider { * @return Promise resolved with the attempts. */ async getLessonAttempts(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const attempts = await site.getDb().getRecords( PAGE_ATTEMPTS_TABLE_NAME, @@ -269,7 +269,7 @@ export class AddonModLessonOfflineProvider { * @return Promise resolved with the retake. */ async getRetake(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecord(RETAKES_TABLE_NAME, { lessonid: lessonId }); } @@ -283,7 +283,7 @@ export class AddonModLessonOfflineProvider { * @return Promise resolved with the retake attempts. */ async getRetakeAttempts(lessonId: number, retake: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const attempts = await site.getDb().getRecords( PAGE_ATTEMPTS_TABLE_NAME, @@ -311,7 +311,7 @@ export class AddonModLessonOfflineProvider { pageId: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const attempts = await site.getDb().getRecords( PAGE_ATTEMPTS_TABLE_NAME, @@ -340,7 +340,7 @@ export class AddonModLessonOfflineProvider { type: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const attempts = await site.getDb().getRecords( PAGE_ATTEMPTS_TABLE_NAME, @@ -415,8 +415,8 @@ export class AddonModLessonOfflineProvider { */ async hasOfflineData(lessonId: number, siteId?: string): Promise { const [retake, attempts] = await Promise.all([ - CoreUtils.instance.ignoreErrors(this.getRetake(lessonId, siteId)), - CoreUtils.instance.ignoreErrors(this.getLessonAttempts(lessonId, siteId)), + CoreUtils.ignoreErrors(this.getRetake(lessonId, siteId)), + CoreUtils.ignoreErrors(this.getLessonAttempts(lessonId, siteId)), ]); return !!retake || !!attempts?.length; @@ -449,8 +449,8 @@ export class AddonModLessonOfflineProvider { protected parsePageAttempt(attempt: AddonModLessonPageAttemptDBRecord): AddonModLessonPageAttemptRecord { return { ...attempt, - data: attempt.data ? CoreTextUtils.instance.parseJSON(attempt.data) : null, - useranswer: attempt.useranswer ? CoreTextUtils.instance.parseJSON(attempt.useranswer) : null, + data: attempt.data ? CoreTextUtils.parseJSON(attempt.data) : null, + useranswer: attempt.useranswer ? CoreTextUtils.parseJSON(attempt.useranswer) : null, }; } @@ -492,13 +492,13 @@ export class AddonModLessonOfflineProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entry: AddonModLessonPageAttemptDBRecord = { lessonid: lessonId, retake: retake, pageid: page.id, - timemodified: CoreTimeUtils.instance.timestamp(), + timemodified: CoreTimeUtils.timestamp(), courseid: courseId, data: data ? JSON.stringify(data) : null, type: page.type, @@ -533,20 +533,20 @@ export class AddonModLessonOfflineProvider { lastPage: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Get current stored retake (if any). If not found, it will create a new one. const entry = await this.getRetakeWithFallback(lessonId, courseId, retake, site.id); entry.lastquestionpage = lastPage; - entry.timemodified = CoreTimeUtils.instance.timestamp(); + entry.timemodified = CoreTimeUtils.timestamp(); await site.getDb().insertRecord(RETAKES_TABLE_NAME, entry); } } -export class AddonModLessonOffline extends makeSingleton(AddonModLessonOfflineProvider) {} +export const AddonModLessonOffline = makeSingleton(AddonModLessonOfflineProvider); /** * Attempt DB record with parsed data. diff --git a/src/addons/mod/lesson/services/lesson-sync.ts b/src/addons/mod/lesson/services/lesson-sync.ts index 413118f71..298dfd9d2 100644 --- a/src/addons/mod/lesson/services/lesson-sync.ts +++ b/src/addons/mod/lesson/services/lesson-sync.ts @@ -55,10 +55,10 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid * @return Promise resolved when done. */ async deleteRetakeFinishedInSync(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Ignore errors, maybe there is none. - await CoreUtils.instance.ignoreErrors(site.getDb().deleteRecords(RETAKES_FINISHED_SYNC_TABLE_NAME, { lessonid: lessonId })); + await CoreUtils.ignoreErrors(site.getDb().deleteRecords(RETAKES_FINISHED_SYNC_TABLE_NAME, { lessonid: lessonId })); } /** @@ -72,9 +72,9 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid lessonId: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - return CoreUtils.instance.ignoreErrors(site.getDb().getRecord(RETAKES_FINISHED_SYNC_TABLE_NAME, { lessonid: lessonId })); + return CoreUtils.ignoreErrors(site.getDb().getRecord(RETAKES_FINISHED_SYNC_TABLE_NAME, { lessonid: lessonId })); } /** @@ -88,8 +88,8 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid async hasDataToSync(lessonId: number, retake: number, siteId?: string): Promise { const [hasAttempts, hasFinished] = await Promise.all([ - CoreUtils.instance.ignoreErrors(AddonModLessonOffline.instance.hasRetakeAttempts(lessonId, retake, siteId)), - CoreUtils.instance.ignoreErrors(AddonModLessonOffline.instance.hasFinishedRetake(lessonId, siteId)), + CoreUtils.ignoreErrors(AddonModLessonOffline.hasRetakeAttempts(lessonId, retake, siteId)), + CoreUtils.ignoreErrors(AddonModLessonOffline.hasFinishedRetake(lessonId, siteId)), ]); return !!(hasAttempts || hasFinished); @@ -105,13 +105,13 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid * @return Promise resolved when done. */ async setRetakeFinishedInSync(lessonId: number, retake: number, pageId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().insertRecord(RETAKES_FINISHED_SYNC_TABLE_NAME, { lessonid: lessonId, retake: Number(retake), pageid: Number(pageId), - timefinished: CoreTimeUtils.instance.timestamp(), + timefinished: CoreTimeUtils.timestamp(), }); } @@ -135,7 +135,7 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid */ protected async syncAllLessonsFunc(force: boolean, siteId: string): Promise { // Get all the lessons that have something to be synchronized. - const lessons = await AddonModLessonOffline.instance.getAllLessonsWithData(siteId); + const lessons = await AddonModLessonOffline.getAllLessonsWithData(siteId); // Sync all lessons that need it. await Promise.all(lessons.map(async (lesson) => { @@ -188,8 +188,8 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid ignoreBlock = false, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); - this.componentTranslate = this.componentTranslate || CoreCourse.instance.translateModuleName('lesson'); + siteId = siteId || CoreSites.getCurrentSiteId(); + this.componentTranslate = this.componentTranslate || CoreCourse.translateModuleName('lesson'); let syncPromise = this.getOngoingSync(lessonId, siteId); if (syncPromise) { @@ -198,10 +198,10 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid } // Verify that lesson isn't blocked. - if (!ignoreBlock && CoreSync.instance.isBlocked(AddonModLessonProvider.COMPONENT, lessonId, siteId)) { + if (!ignoreBlock && CoreSync.isBlocked(AddonModLessonProvider.COMPONENT, lessonId, siteId)) { this.logger.debug('Cannot sync lesson ' + lessonId + ' because it is blocked.'); - throw new CoreSyncBlockedError(Translate.instance.instant('core.errorsyncblocked', { $a: this.componentTranslate })); + throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); } this.logger.debug('Try to sync lesson ' + lessonId + ' in site ' + siteId); @@ -227,8 +227,8 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid siteId?: string, ): Promise { // Sync offline logs. - await CoreUtils.instance.ignoreErrors( - CoreCourseLogHelper.instance.syncActivity(AddonModLessonProvider.COMPONENT, lessonId, siteId), + await CoreUtils.ignoreErrors( + CoreCourseLogHelper.syncActivity(AddonModLessonProvider.COMPONENT, lessonId, siteId), ); const result: AddonModLessonSyncResult = { @@ -245,7 +245,7 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid if (result.updated && result.courseId) { try { // Data has been sent to server, update data. - const module = await CoreCourse.instance.getModuleBasicInfoByInstance(lessonId, 'lesson', siteId); + const module = await CoreCourse.getModuleBasicInfoByInstance(lessonId, 'lesson', siteId); await this.prefetchAfterUpdate(AddonModLessonPrefetchHandler.instance, module, result.courseId, undefined, siteId); } catch { // Ignore errors. @@ -253,7 +253,7 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid } // Sync finished, set sync time. - await CoreUtils.instance.ignoreErrors(this.setSyncTime(lessonId, siteId)); + await CoreUtils.ignoreErrors(this.setSyncTime(lessonId, siteId)); // All done, return the result. return result; @@ -273,11 +273,11 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid askPassword = false, siteId?: string, ): Promise { - let attempts = await AddonModLessonOffline.instance.getLessonAttempts(lessonId, siteId); + let attempts = await AddonModLessonOffline.getLessonAttempts(lessonId, siteId); if (!attempts.length) { return; - } else if (!CoreApp.instance.isOnline()) { + } else if (!CoreApp.isOnline()) { // Cannot sync in offline. throw new CoreNetworkError(); } @@ -286,9 +286,9 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid const attemptsLength = attempts.length; // Get the info, access info and the lesson password if needed. - const lesson = await AddonModLesson.instance.getLessonById(result.courseId, lessonId, { siteId }); + const lesson = await AddonModLesson.getLessonById(result.courseId, lessonId, { siteId }); - const passwordData = await AddonModLessonPrefetchHandler.instance.getLessonPassword(lessonId, { + const passwordData = await AddonModLessonPrefetchHandler.getLessonPassword(lessonId, { readingStrategy: CoreSitesReadingStrategy.OnlyNetwork, askPassword, siteId, @@ -304,7 +304,7 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid } // Attempt doesn't belong to current retake, delete. - promises.push(CoreUtils.instance.ignoreErrors(AddonModLessonOffline.instance.deleteAttempt( + promises.push(CoreUtils.ignoreErrors(AddonModLessonOffline.deleteAttempt( lesson.id, attempt.retake, attempt.pageid, @@ -317,10 +317,10 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid if (attempts.length != attemptsLength) { // Some attempts won't be sent, add a warning. - result.warnings.push(Translate.instance.instant('core.warningofflinedatadeleted', { + result.warnings.push(Translate.instant('core.warningofflinedatadeleted', { component: this.componentTranslate, name: lesson.name, - error: Translate.instance.instant('addon.mod_lesson.warningretakefinished'), + error: Translate.instant('addon.mod_lesson.warningretakefinished'), })); } @@ -338,7 +338,7 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid blocking: true, })); - await CoreUtils.instance.executeOrderedPromises(promisesData); + await CoreUtils.executeOrderedPromises(promisesData); return passwordData; } @@ -366,16 +366,16 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid try { // Send the page data. - await AddonModLesson.instance.processPageOnline(lesson.id, attempt.pageid, attempt.data || {}, { + await AddonModLesson.processPageOnline(lesson.id, attempt.pageid, attempt.data || {}, { password, siteId, }); result.updated = true; - await AddonModLessonOffline.instance.deleteAttempt(lesson.id, retake, pageId, timemodified, siteId); + await AddonModLessonOffline.deleteAttempt(lesson.id, retake, pageId, timemodified, siteId); } catch (error) { - if (!error || !CoreUtils.instance.isWebServiceError(error)) { + if (!error || !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server. throw error; } @@ -383,13 +383,13 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid // The WebService has thrown an error, this means that the attempt cannot be submitted. Delete it. result.updated = true; - await AddonModLessonOffline.instance.deleteAttempt(lesson.id, retake, pageId, timemodified, siteId); + await AddonModLessonOffline.deleteAttempt(lesson.id, retake, pageId, timemodified, siteId); // Attempt deleted, add a warning. - result.warnings.push(Translate.instance.instant('core.warningofflinedatadeleted', { + result.warnings.push(Translate.instant('core.warningofflinedatadeleted', { component: this.componentTranslate, name: lesson.name, - error: CoreTextUtils.instance.getErrorMessageFromError(error), + error: CoreTextUtils.getErrorMessageFromError(error), })); } } @@ -413,7 +413,7 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid siteId?: string, ): Promise { // Attempts sent or there was none. If there is a finished retake, send it. - const retake = await CoreUtils.instance.ignoreErrors(AddonModLessonOffline.instance.getRetake(lessonId, siteId)); + const retake = await CoreUtils.ignoreErrors(AddonModLessonOffline.getRetake(lessonId, siteId)); if (!retake) { // No retake to sync. @@ -422,10 +422,10 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid if (!retake.finished) { // The retake isn't marked as finished, nothing to send. Delete the retake. - await AddonModLessonOffline.instance.deleteRetake(lessonId, siteId); + await AddonModLessonOffline.deleteRetake(lessonId, siteId); return; - } else if (!CoreApp.instance.isOnline()) { + } else if (!CoreApp.isOnline()) { // Cannot sync in offline. throw new CoreNetworkError(); } @@ -434,8 +434,8 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid if (!passwordData?.lesson) { // Retrieve the needed data. - const lesson = await AddonModLesson.instance.getLessonById(result.courseId!, lessonId, { siteId }); - passwordData = await AddonModLessonPrefetchHandler.instance.getLessonPassword(lessonId, { + const lesson = await AddonModLesson.getLessonById(result.courseId!, lessonId, { siteId }); + passwordData = await AddonModLessonPrefetchHandler.getLessonPassword(lessonId, { readingStrategy: CoreSitesReadingStrategy.OnlyNetwork, askPassword, siteId, @@ -447,19 +447,19 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid if (retake.retake != passwordData.accessInfo.attemptscount) { // The retake changed, add a warning if it isn't there already. if (!result.warnings.length) { - result.warnings.push(Translate.instance.instant('core.warningofflinedatadeleted', { + result.warnings.push(Translate.instant('core.warningofflinedatadeleted', { component: this.componentTranslate, name: passwordData.lesson.name, - error: Translate.instance.instant('addon.mod_lesson.warningretakefinished'), + error: Translate.instant('addon.mod_lesson.warningretakefinished'), })); } - await AddonModLessonOffline.instance.deleteRetake(lessonId, siteId); + await AddonModLessonOffline.deleteRetake(lessonId, siteId); } try { // All good, finish the retake. - const response = await AddonModLesson.instance.finishRetakeOnline(lessonId, { + const response = await AddonModLesson.finishRetakeOnline(lessonId, { password: passwordData.password, siteId, }); @@ -468,16 +468,16 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid // Mark the retake as finished in a sync if it can be reviewed. if (!ignoreBlock && response.data?.reviewlesson) { - const params = CoreUrlUtils.instance.extractUrlParams( response.data.reviewlesson.value); + const params = CoreUrlUtils.extractUrlParams( response.data.reviewlesson.value); if (params.pageid) { // The retake can be reviewed, mark it as finished. Don't block the user for this. this.setRetakeFinishedInSync(lessonId, retake.retake, Number(params.pageid), siteId); } } - await AddonModLessonOffline.instance.deleteRetake(lessonId, siteId); + await AddonModLessonOffline.deleteRetake(lessonId, siteId); } catch (error) { - if (!error || !CoreUtils.instance.isWebServiceError(error)) { + if (!error || !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server. throw error; } @@ -485,20 +485,20 @@ export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvid // The WebService has thrown an error, this means that responses cannot be submitted. Delete them. result.updated = true; - await AddonModLessonOffline.instance.deleteRetake(lessonId, siteId); + await AddonModLessonOffline.deleteRetake(lessonId, siteId); // Retake deleted, add a warning. - result.warnings.push(Translate.instance.instant('core.warningofflinedatadeleted', { + result.warnings.push(Translate.instant('core.warningofflinedatadeleted', { component: this.componentTranslate, name: passwordData.lesson.name, - error: CoreTextUtils.instance.getErrorMessageFromError(error), + error: CoreTextUtils.getErrorMessageFromError(error), })); } } } -export class AddonModLessonSync extends makeSingleton(AddonModLessonSyncProvider) {} +export const AddonModLessonSync = makeSingleton(AddonModLessonSyncProvider, ['component', 'syncInterval']); /** * Data returned by a lesson sync. diff --git a/src/addons/mod/lesson/services/lesson.ts b/src/addons/mod/lesson/services/lesson.ts index 9baefdab0..929a73fa8 100644 --- a/src/addons/mod/lesson/services/lesson.ts +++ b/src/addons/mod/lesson/services/lesson.ts @@ -95,13 +95,13 @@ export class AddonModLessonProvider { className: string, ): string { // Add a table row containing the answer. - feedback += '' + (answerFormat ? answer : CoreTextUtils.instance.cleanTags(answer)) + + feedback += '' + (answerFormat ? answer : CoreTextUtils.cleanTags(answer)) + ''; // If the response exists, add a table row containing the response. If not, add en empty row. if (response?.trim()) { feedback += '' + - Translate.instance.instant('addon.mod_lesson.response') + ':
' + + Translate.instant('addon.mod_lesson.response') + ':
' + response + ''; } else { feedback += ''; @@ -119,7 +119,7 @@ export class AddonModLessonProvider { */ protected addMessage(messages: AddonModLessonMessageWSData[], stringId: string, stringParams?: Record): void { messages.push({ - message: Translate.instance.instant(stringId, stringParams), + message: Translate.instant(stringId, stringParams), type: '', }); } @@ -142,7 +142,7 @@ export class AddonModLessonProvider { if (addMessage) { const params = typeof value != 'boolean' ? { $a: value } : undefined; - message = Translate.instance.instant('addon.mod_lesson.' + name, params); + message = Translate.instant('addon.mod_lesson.' + name, params); } result.data[name] = { @@ -160,7 +160,7 @@ export class AddonModLessonProvider { */ answerPageIsContent(page: AddonModLessonUserAttemptAnswerPageWSData): boolean { // The page doesn't have any reliable field to use for checking this. Check qtype first (translated string). - if (page.qtype == Translate.instance.instant('addon.mod_lesson.branchtable')) { + if (page.qtype == Translate.instant('addon.mod_lesson.branchtable')) { return true; } @@ -169,7 +169,7 @@ export class AddonModLessonProvider { if (page.answerdata && !this.answerPageIsQuestion(page)) { // It isn't a question page, but it can be an end of branch, etc. Check if the first answer has a button. if (page.answerdata.answers && page.answerdata.answers[0]) { - const element = CoreDomUtils.instance.convertToElement(page.answerdata.answers[0][0]); + const element = CoreDomUtils.convertToElement(page.answerdata.answers[0][0]); return !!element.querySelector('input[type="button"]'); } @@ -259,7 +259,7 @@ export class AddonModLessonProvider { accessInfo: AddonModLessonGetAccessInformationWSResponse, options: AddonModLessonCalculateProgressOptions = {}, ): Promise { - options.siteId = options.siteId || CoreSites.instance.getCurrentSiteId(); + options.siteId = options.siteId || CoreSites.getCurrentSiteId(); // Check if the user is reviewing the attempt. if (options.review) { @@ -293,7 +293,7 @@ export class AddonModLessonProvider { const validPages = {}; let pageId = accessInfo.firstpageid; - viewedPagesIds = CoreUtils.instance.mergeArraysWithoutDuplicates(viewedPagesIds, viewedContentPagesIds); + viewedPagesIds = CoreUtils.mergeArraysWithoutDuplicates(viewedPagesIds, viewedContentPagesIds); // Filter out the following pages: // - End of Cluster @@ -306,7 +306,7 @@ export class AddonModLessonProvider { } // Progress calculation as a percent. - return CoreTextUtils.instance.roundToDecimals(viewedPagesIds.length / Object.keys(validPages).length, 2) * 100; + return CoreTextUtils.roundToDecimals(viewedPagesIds.length / Object.keys(validPages).length, 2) * 100; } /** @@ -460,7 +460,7 @@ export class AddonModLessonProvider { } const response = this.getUserResponseMatching(data); - const getAnswers = CoreUtils.instance.clone(pageData.answers); + const getAnswers = CoreUtils.clone(pageData.answers); const correct = getAnswers.shift(); const wrong = getAnswers.shift(); const answers: Record = {}; @@ -487,7 +487,7 @@ export class AddonModLessonProvider { return; } - value = CoreTextUtils.instance.decodeHTML(value); + value = CoreTextUtils.decodeHTML(value); userResponse.push(value); if (typeof answers[id] != 'undefined') { @@ -751,7 +751,7 @@ export class AddonModLessonProvider { } } else { expectedAnswer = expectedAnswer.replace('*', '#####'); - expectedAnswer = CoreTextUtils.instance.escapeForRegex(expectedAnswer); + expectedAnswer = CoreTextUtils.escapeForRegex(expectedAnswer); expectedAnswer = expectedAnswer.replace('#####', '.*'); } @@ -834,7 +834,7 @@ export class AddonModLessonProvider { this.checkOtherAnswers(lesson, pageData, result); result.userresponse = studentAnswer; - result.studentanswer = CoreTextUtils.instance.s(studentAnswer); // Clean student answer as it goes to output. + result.studentanswer = CoreTextUtils.s(studentAnswer); // Clean student answer as it goes to output. } /** @@ -950,7 +950,7 @@ export class AddonModLessonProvider { courseId: courseId, outOfTime: options.outOfTime, review: options.review, - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); return response; } @@ -966,7 +966,7 @@ export class AddonModLessonProvider { lessonId: number, options: AddonModLessonFinishRetakeOnlineOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonFinishAttemptWSParams = { lessonid: lessonId, @@ -985,7 +985,7 @@ export class AddonModLessonProvider { response.data.forEach((entry) => { if (entry.value && typeof entry.value == 'string' && entry.value !== '1') { // It's a JSON encoded object. Try to decode it. - entry.value = CoreTextUtils.instance.parseJSON(entry.value); + entry.value = CoreTextUtils.parseJSON(entry.value); } map[entry.name] = entry; @@ -1010,7 +1010,7 @@ export class AddonModLessonProvider { // First finish the retake offline. const retake = options.accessInfo!.attemptscount; - await AddonModLessonOffline.instance.finishRetake(lesson.id, courseId, retake, true, options.outOfTime, options.siteId); + await AddonModLessonOffline.finishRetake(lesson.id, courseId, retake, true, options.outOfTime, options.siteId); // Get the lesson grade. const newOptions = { @@ -1020,7 +1020,7 @@ export class AddonModLessonProvider { siteId: options.siteId, }; - const gradeInfo = await CoreUtils.instance.ignoreErrors(this.lessonGrade(lesson, retake, newOptions)); + const gradeInfo = await CoreUtils.ignoreErrors(this.lessonGrade(lesson, retake, newOptions)); // Retake marked, now return the response. return this.processEolPage(lesson, courseId, options, gradeInfo); @@ -1112,7 +1112,7 @@ export class AddonModLessonProvider { } if (lesson.grade !== undefined && lesson.grade != CoreGradesProvider.TYPE_NONE) { - entryData.grade = CoreTextUtils.instance.roundToDecimals(gradeInfo.grade * lesson.grade / 100, 1); + entryData.grade = CoreTextUtils.roundToDecimals(gradeInfo.grade * lesson.grade / 100, 1); entryData.total = lesson.grade; this.addResultValueEolPage(result, 'yourcurrentgradeisoutof', entryData, true); } @@ -1157,7 +1157,7 @@ export class AddonModLessonProvider { lessonId: number, options: CoreCourseCommonModWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonGetAccessInformationWSParams = { lessonid: lessonId, @@ -1167,7 +1167,7 @@ export class AddonModLessonProvider { updateFrequency: CoreSite.FREQUENCY_OFTEN, component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_lesson_get_lesson_access_information', params, preSets); @@ -1200,8 +1200,8 @@ export class AddonModLessonProvider { const [online, offline] = await Promise.all([ this.getContentPagesViewedOnline(lessonId, retake, options), - CoreUtils.instance.ignoreErrors( - AddonModLessonOffline.instance.getRetakeAttemptsForType(lessonId, retake, type, options.siteId), + CoreUtils.ignoreErrors( + AddonModLessonOffline.getRetakeAttemptsForType(lessonId, retake, type, options.siteId), ), ]); @@ -1273,7 +1273,7 @@ export class AddonModLessonProvider { options: CoreCourseCommonModWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonGetContentPagesViewedWSParams = { lessonid: lessonId, @@ -1283,7 +1283,7 @@ export class AddonModLessonProvider { cacheKey: this.getContentPagesViewedCacheKey(lessonId, retake), component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const result = await site.read( @@ -1348,12 +1348,12 @@ export class AddonModLessonProvider { retake: number, options: CoreCourseCommonModWSOptions = {}, ): Promise { - options.siteId = options.siteId || CoreSites.instance.getCurrentSiteId(); + options.siteId = options.siteId || CoreSites.getCurrentSiteId(); let lastPageSeen: number | undefined; // Get the last question answered. - const answer = await AddonModLessonOffline.instance.getLastQuestionPageAttempt(lessonId, retake, options.siteId); + const answer = await AddonModLessonOffline.getLastQuestionPageAttempt(lessonId, retake, options.siteId); if (answer) { lastPageSeen = answer.newpageid; @@ -1406,7 +1406,7 @@ export class AddonModLessonProvider { options: CoreSitesCommonWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonGetLessonsByCoursesWSParams = { courseids: [courseId], @@ -1415,7 +1415,7 @@ export class AddonModLessonProvider { cacheKey: this.getLessonDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModLessonProvider.COMPONENT, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read( @@ -1468,7 +1468,7 @@ export class AddonModLessonProvider { ): Promise { const validatePassword = options.validatePassword ?? true; - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonGetLessonWSParams = { lessonid: lessonId, @@ -1477,7 +1477,7 @@ export class AddonModLessonProvider { cacheKey: this.getLessonWithPasswordCacheKey(lessonId), component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; if (typeof options.password == 'string') { @@ -1492,9 +1492,9 @@ export class AddonModLessonProvider { if (validatePassword) { // Invalidate the data and reject. - await CoreUtils.instance.ignoreErrors(this.invalidateLessonWithPassword(lessonId, site.id)); + await CoreUtils.ignoreErrors(this.invalidateLessonWithPassword(lessonId, site.id)); - throw new CoreError(Translate.instance.instant('addon.mod_lesson.loginfail')); + throw new CoreError(Translate.instant('addon.mod_lesson.loginfail')); } } @@ -1546,7 +1546,7 @@ export class AddonModLessonProvider { ): Promise { if (accessInfo.canmanage) { - return Promise.resolve(Translate.instance.instant('addon.mod_lesson.teacherongoingwarning')); + return Promise.resolve(Translate.instant('addon.mod_lesson.teacherongoingwarning')); } else { let retake = accessInfo.attemptscount; if (options.review) { @@ -1555,12 +1555,12 @@ export class AddonModLessonProvider { return this.lessonGrade(lesson, retake, options).then((gradeInfo) => { if (lesson.custom) { - return Translate.instance.instant( + return Translate.instant( 'addon.mod_lesson.ongoingcustom', { $a: { score: gradeInfo.earned, currenthigh: gradeInfo.total } }, ); } else { - return Translate.instance.instant( + return Translate.instant( 'addon.mod_lesson.ongoingnormal', { $a: { correct: gradeInfo.earned, viewed: gradeInfo.attempts } }, ); @@ -1634,7 +1634,7 @@ export class AddonModLessonProvider { options: AddonModLessonGetPageDataOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonGetPageDataWSParams = { lessonid: lesson.id, @@ -1646,7 +1646,7 @@ export class AddonModLessonProvider { cacheKey: this.getPageDataCacheKey(lesson.id, pageId), component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; if (typeof options.password == 'string') { @@ -1707,7 +1707,7 @@ export class AddonModLessonProvider { */ async getPages(lessonId: number, options: AddonModLessonPwdReviewOptions = {}): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonGetPagesWSParams = { lessonid: lessonId, @@ -1717,7 +1717,7 @@ export class AddonModLessonProvider { updateFrequency: CoreSite.FREQUENCY_SOMETIMES, component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; if (typeof options.password == 'string') { @@ -1751,7 +1751,7 @@ export class AddonModLessonProvider { options: CoreCourseCommonModWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonGetPagesPossibleJumpsWSParams = { lessonid: lessonId, @@ -1760,7 +1760,7 @@ export class AddonModLessonProvider { cacheKey: this.getPagesPossibleJumpsCacheKey(lessonId), component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read( @@ -1818,8 +1818,8 @@ export class AddonModLessonProvider { if (this.lessonDisplayTeacherWarning(jumps)) { this.addMessage(messages, 'addon.mod_lesson.teacherjumpwarning', { $a: { - cluster: Translate.instance.instant('addon.mod_lesson.clusterjump'), - unseen: Translate.instance.instant('addon.mod_lesson.unseenpageinbranch'), + cluster: Translate.instant('addon.mod_lesson.clusterjump'), + unseen: Translate.instant('addon.mod_lesson.unseenpageinbranch'), }, }); } @@ -1892,7 +1892,7 @@ export class AddonModLessonProvider { // Tell student how many questions they have seen, how many are required and their grade. const retake = accessInfo.attemptscount; - const gradeInfo = await CoreUtils.instance.ignoreErrors(this.lessonGrade(lesson, retake, options)); + const gradeInfo = await CoreUtils.ignoreErrors(this.lessonGrade(lesson, retake, options)); if (gradeInfo?.attempts) { if (gradeInfo.nquestions < lesson.minquestions) { this.addMessage(messages, 'addon.mod_lesson.numberofpagesviewednotice', { @@ -1908,7 +1908,7 @@ export class AddonModLessonProvider { if (lesson.grade !== undefined && lesson.grade != CoreGradesProvider.TYPE_NONE) { this.addMessage(messages, 'addon.mod_lesson.yourcurrentgradeisoutof', { $a: { - grade: CoreTextUtils.instance.roundToDecimals(gradeInfo.grade * lesson.grade / 100, 1), + grade: CoreTextUtils.roundToDecimals(gradeInfo.grade * lesson.grade / 100, 1), total: lesson.grade, } }); } @@ -1924,8 +1924,8 @@ export class AddonModLessonProvider { // Warning for teachers to inform them that cluster and unseen does not work while logged in as a teacher. this.addMessage(messages, 'addon.mod_lesson.teacherjumpwarning', { $a: { - cluster: Translate.instance.instant('addon.mod_lesson.clusterjump'), - unseen: Translate.instance.instant('addon.mod_lesson.unseenpageinbranch'), + cluster: Translate.instant('addon.mod_lesson.clusterjump'), + unseen: Translate.instant('addon.mod_lesson.unseenpageinbranch'), }, }); } @@ -1950,7 +1950,7 @@ export class AddonModLessonProvider { const [online, offline] = await Promise.all([ this.getQuestionsAttemptsOnline(lessonId, retake, options), - CoreUtils.instance.ignoreErrors(AddonModLessonOffline.instance.getQuestionsAttempts( + CoreUtils.ignoreErrors(AddonModLessonOffline.getQuestionsAttempts( lessonId, retake, options.correct, @@ -2001,7 +2001,7 @@ export class AddonModLessonProvider { options: AddonModLessonGetQuestionsAttemptsOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const userId = options.userId || site.getUserId(); @@ -2015,7 +2015,7 @@ export class AddonModLessonProvider { cacheKey: this.getQuestionsAttemptsCacheKey(lessonId, retake, userId), component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read( @@ -2055,7 +2055,7 @@ export class AddonModLessonProvider { ): Promise { const groupId = options.groupId || 0; - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonGetAttemptsOverviewWSParams = { lessonid: lessonId, @@ -2066,7 +2066,7 @@ export class AddonModLessonProvider { updateFrequency: CoreSite.FREQUENCY_OFTEN, component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read( @@ -2107,7 +2107,7 @@ export class AddonModLessonProvider { * @return Promise resolved with password on success, rejected otherwise. */ async getStoredPassword(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entry = await site.getDb().getRecord(PASSWORD_TABLE_NAME, { lessonid: lessonId }); @@ -2147,7 +2147,7 @@ export class AddonModLessonProvider { * @return Promise resolved with the pages. */ async getTimers(lessonId: number, options: AddonModLessonUserOptions = {}): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const userId = options.userId || site.getUserId(); const params: ModLessonGetUserTimersWSParams = { @@ -2158,7 +2158,7 @@ export class AddonModLessonProvider { cacheKey: this.getTimersCacheKey(lessonId, userId), component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read('mod_lesson_get_user_timers', params, preSets); @@ -2194,7 +2194,7 @@ export class AddonModLessonProvider { * @return List of used answers. */ protected getUsedAnswersMultichoice(pageData: AddonModLessonGetPageDataWSResponse): AddonModLessonPageAnswerWSData[] { - const answers = CoreUtils.instance.clone(pageData.answers); + const answers = CoreUtils.clone(pageData.answers); return answers.filter((entry) => entry.answer !== undefined && entry.answer !== ''); } @@ -2267,7 +2267,7 @@ export class AddonModLessonProvider { options: AddonModLessonUserOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const userId = options.userId || site.getUserId(); const params: AddonModLessonGetUserAttemptWSParams = { @@ -2280,7 +2280,7 @@ export class AddonModLessonProvider { updateFrequency: CoreSite.FREQUENCY_SOMETIMES, component: AddonModLessonProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_lesson_get_user_attempt', params, preSets); @@ -2405,7 +2405,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAccessInformation(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAccessInformationCacheKey(lessonId)); } @@ -2418,7 +2418,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateContentPagesViewed(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getContentPagesViewedCommonCacheKey(lessonId)); } @@ -2432,7 +2432,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateContentPagesViewedForRetake(lessonId: number, retake: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getContentPagesViewedCacheKey(lessonId, retake)); } @@ -2445,7 +2445,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateLessonData(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getLessonDataCacheKey(courseId)); } @@ -2458,7 +2458,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateLessonWithPassword(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getLessonWithPasswordCacheKey(lessonId)); } @@ -2471,7 +2471,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidatePageData(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getPageDataCommonCacheKey(lessonId)); } @@ -2485,7 +2485,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidatePageDataForPage(lessonId: number, pageId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getPageDataCacheKey(lessonId, pageId)); } @@ -2498,7 +2498,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidatePages(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getPagesCacheKey(lessonId)); } @@ -2511,7 +2511,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidatePagesPossibleJumps(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getPagesPossibleJumpsCacheKey(lessonId)); } @@ -2524,7 +2524,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateQuestionsAttempts(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getQuestionsAttemptsCommonCacheKey(lessonId)); } @@ -2539,7 +2539,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateQuestionsAttemptsForRetake(lessonId: number, retake: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getQuestionsAttemptsCacheKey(lessonId, retake, userId || site.getUserId())); } @@ -2552,7 +2552,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateRetakesOverview(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getRetakesOverviewCommonCacheKey(lessonId)); } @@ -2566,7 +2566,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateRetakesOverviewForGroup(lessonId: number, groupId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getRetakesOverviewCacheKey(lessonId, groupId)); } @@ -2579,7 +2579,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateTimers(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getTimersCommonCacheKey(lessonId)); } @@ -2593,7 +2593,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateTimersForUser(lessonId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getTimersCacheKey(lessonId, userId || site.getUserId())); } @@ -2608,7 +2608,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserRetake(lessonId: number, retake: number, userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserRetakeCacheKey(lessonId, userId || site.getUserId(), retake)); } @@ -2621,7 +2621,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserRetakesForLesson(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUserRetakeLessonCacheKey(lessonId)); } @@ -2635,7 +2635,7 @@ export class AddonModLessonProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserRetakesForUser(lessonId: number, userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUserRetakeUserCacheKey(lessonId, userId || site.getUserId())); } @@ -2702,7 +2702,7 @@ export class AddonModLessonProvider { * @return Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise. */ async isPluginEnabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // All WS were introduced at the same time so checking one is enough. return site.wsAvailable('mod_lesson_get_lesson_access_information'); @@ -2735,7 +2735,7 @@ export class AddonModLessonProvider { review?: boolean, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModLessonLaunchAttemptWSParams = { lessonid: id, @@ -2753,7 +2753,7 @@ export class AddonModLessonProvider { CoreEvents.trigger(AddonModLessonProvider.DATA_SENT_EVENT, { lessonId: id, type: 'launch', - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); return response; } @@ -2937,7 +2937,7 @@ export class AddonModLessonProvider { } if (result.total) { // Not zero. - result.grade = CoreTextUtils.instance.roundToDecimals(result.earned * 100 / result.total, 5); + result.grade = CoreTextUtils.roundToDecimals(result.earned * 100 / result.total, 5); } return result; @@ -2961,7 +2961,7 @@ export class AddonModLessonProvider { params.password = password; } - await CoreCourseLogHelper.instance.logSingle( + await CoreCourseLogHelper.logSingle( 'mod_lesson_view_lesson', params, AddonModLessonProvider.COMPONENT, @@ -2991,7 +2991,7 @@ export class AddonModLessonProvider { options: AddonModLessonProcessPageOptions = {}, ): Promise { - options.siteId = options.siteId || CoreSites.instance.getCurrentSiteId(); + options.siteId = options.siteId || CoreSites.getCurrentSiteId(); if (!pageData.page) { throw new CoreError('Page data not supplied.'); } @@ -3008,7 +3008,7 @@ export class AddonModLessonProvider { courseId: courseId, pageId: pageId, review: options.review, - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); response.sent = true; @@ -3105,12 +3105,12 @@ export class AddonModLessonProvider { options: AddonModLessonProcessPageOnlineOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModLessonProcessPageWSParams = { lessonid: lessonId, pageid: pageId, - data: CoreUtils.instance.objectToArrayOfObjects(data, 'name', 'value', true), + data: CoreUtils.objectToArrayOfObjects(data, 'name', 'value', true), review: !!options.review, }; @@ -3160,7 +3160,7 @@ export class AddonModLessonProvider { if (result.inmediatejump) { if (pageData.page?.qtype == AddonModLessonProvider.LESSON_PAGE_BRANCHTABLE) { // Store the content page data. In Moodle this is stored in a separate table, during checkAnswer. - await AddonModLessonOffline.instance.processPage( + await AddonModLessonOffline.processPage( lesson.id, courseId, retake, @@ -3185,7 +3185,7 @@ export class AddonModLessonProvider { if (result.noanswer) { result.newpageid = pageData.page.id; // Display same page again. - result.feedback = Translate.instance.instant('addon.mod_lesson.noanswer'); + result.feedback = Translate.instant('addon.mod_lesson.noanswer'); return result; } @@ -3203,7 +3203,7 @@ export class AddonModLessonProvider { // Check if they have reached (or exceeded) the maximum number of attempts allowed. if (lesson.maxattempts && lesson.maxattempts > 0 && nAttempts >= lesson.maxattempts) { result.maxattemptsreached = true; - result.feedback = Translate.instance.instant('addon.mod_lesson.maximumnumberofattemptsreached'); + result.feedback = Translate.instant('addon.mod_lesson.maximumnumberofattemptsreached'); result.newpageid = AddonModLessonProvider.LESSON_NEXTPAGE; return result; @@ -3215,7 +3215,7 @@ export class AddonModLessonProvider { // Calculate and store the new page ID to prevent having to recalculate it later. const newPageId = this.getNewPageId(pageData.page.id, result.newpageid, jumps); - await AddonModLessonOffline.instance.processPage( + await AddonModLessonOffline.processPage( lesson.id, courseId, retake, @@ -3255,11 +3255,11 @@ export class AddonModLessonProvider { // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question). result.nodefaultresponse = true; } else if (result.isessayquestion) { - result.response = Translate.instance.instant('addon.mod_lesson.defaultessayresponse'); + result.response = Translate.instant('addon.mod_lesson.defaultessayresponse'); } else if (result.correctanswer) { - result.response = Translate.instance.instant('addon.mod_lesson.thatsthecorrectanswer'); + result.response = Translate.instant('addon.mod_lesson.thatsthecorrectanswer'); } else { - result.response = Translate.instance.instant('addon.mod_lesson.thatsthewronganswer'); + result.response = Translate.instant('addon.mod_lesson.thatsthewronganswer'); } } @@ -3281,7 +3281,7 @@ export class AddonModLessonProvider { const messageId = nAttempts == 1 ? 'firstwrong' : 'secondpluswrong'; - result.feedback = ''; + result.feedback = ''; } else { result.feedback = ''; } @@ -3295,7 +3295,7 @@ export class AddonModLessonProvider { result.feedback += '
' + pageData.page.contents + '
'; result.feedback += '
' + - Translate.instance.instant('addon.mod_lesson.youranswer') + ' : ' + + Translate.instant('addon.mod_lesson.youranswer') + ' : ' + '
'; // Create a table containing the answers and responses. @@ -3339,7 +3339,7 @@ export class AddonModLessonProvider { * @return Promise resolved when removed. */ async removeStoredPassword(lessonId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(PASSWORD_TABLE_NAME, { lessonid: lessonId }); } @@ -3353,7 +3353,7 @@ export class AddonModLessonProvider { * @return Promise resolved when stored. */ async storePassword(lessonId: number, password: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entry: AddonModLessonPasswordDBRecord = { lessonid: lessonId, @@ -3412,7 +3412,7 @@ export class AddonModLessonProvider { } -export class AddonModLesson extends makeSingleton(AddonModLessonProvider) {} +export const AddonModLesson = makeSingleton(AddonModLessonProvider); /** * Result of check answer. diff --git a/src/addons/mod/page/components/index/index.ts b/src/addons/mod/page/components/index/index.ts index 09e2c57a1..7cf5feb5a 100644 --- a/src/addons/mod/page/components/index/index.ts +++ b/src/addons/mod/page/components/index/index.ts @@ -54,13 +54,13 @@ export class AddonModPageIndexComponent extends CoreCourseModuleMainResourceComp async ngOnInit(): Promise { super.ngOnInit(); - this.canGetPage = AddonModPage.instance.isGetPageWSAvailable(); + this.canGetPage = AddonModPage.isGetPageWSAvailable(); await this.loadContent(); try { - await AddonModPage.instance.logView(this.module!.instance!, this.module!.name); - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + await AddonModPage.logView(this.module!.instance!, this.module!.name); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); } catch { // Ignore errors. } @@ -72,7 +72,7 @@ export class AddonModPageIndexComponent extends CoreCourseModuleMainResourceComp * @return Resolved when done. */ protected async invalidateContent(): Promise { - await AddonModPage.instance.invalidateContent(this.module!.id, this.courseId!); + await AddonModPage.invalidateContent(this.module!.id, this.courseId!); } /** @@ -92,9 +92,9 @@ export class AddonModPageIndexComponent extends CoreCourseModuleMainResourceComp // Get the module to get the latest title and description. Data should've been updated in download. if (this.canGetPage) { - getPagePromise = AddonModPage.instance.getPageData(this.courseId!, this.module!.id); + getPagePromise = AddonModPage.getPageData(this.courseId!, this.module!.id); } else { - getPagePromise = CoreCourse.instance.getModule(this.module!.id, this.courseId!); + getPagePromise = CoreCourse.getModule(this.module!.id, this.courseId!); } promises.push(getPagePromise.then((page) => { @@ -114,12 +114,12 @@ export class AddonModPageIndexComponent extends CoreCourseModuleMainResourceComp // Check if description and timemodified should be displayed. if ('displayoptions' in this.page) { const options: Record = - CoreTextUtils.instance.unserialize(this.page.displayoptions) || {}; + CoreTextUtils.unserialize(this.page.displayoptions) || {}; this.displayDescription = typeof options.printintro == 'undefined' || - CoreUtils.instance.isTrueOrOne(options.printintro); + CoreUtils.isTrueOrOne(options.printintro); this.displayTimemodified = typeof options.printlastmodified == 'undefined' || - CoreUtils.instance.isTrueOrOne(options.printlastmodified); + CoreUtils.isTrueOrOne(options.printlastmodified); } else { this.displayDescription = true; this.displayTimemodified = true; @@ -133,7 +133,7 @@ export class AddonModPageIndexComponent extends CoreCourseModuleMainResourceComp })); // Get the page HTML. - promises.push(AddonModPageHelper.instance.getPageHtml(this.module!.contents, this.module!.id).then((content) => { + promises.push(AddonModPageHelper.getPageHtml(this.module!.contents, this.module!.id).then((content) => { this.contents = content; this.warning = downloadResult?.failed ? this.getErrorDownloadingSomeFilesMessage(downloadResult.error!) : ''; diff --git a/src/addons/mod/page/page.module.ts b/src/addons/mod/page/page.module.ts index eeeeeb12a..ffeb2558f 100644 --- a/src/addons/mod/page/page.module.ts +++ b/src/addons/mod/page/page.module.ts @@ -44,11 +44,11 @@ const routes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreCourseModuleDelegate.instance.registerHandler(AddonModPageModuleHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModPageIndexLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModPageListLinkHandler.instance); - CoreCourseModulePrefetchDelegate.instance.registerHandler(AddonModPagePrefetchHandler.instance); - CorePluginFileDelegate.instance.registerHandler(AddonModPagePluginFileHandler.instance); + CoreCourseModuleDelegate.registerHandler(AddonModPageModuleHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModPageIndexLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModPageListLinkHandler.instance); + CoreCourseModulePrefetchDelegate.registerHandler(AddonModPagePrefetchHandler.instance); + CorePluginFileDelegate.registerHandler(AddonModPagePluginFileHandler.instance); }, }, ], diff --git a/src/addons/mod/page/pages/index/index.ts b/src/addons/mod/page/pages/index/index.ts index 93b51ce66..729250f56 100644 --- a/src/addons/mod/page/pages/index/index.ts +++ b/src/addons/mod/page/pages/index/index.ts @@ -37,8 +37,8 @@ export class AddonModPageIndexPage implements OnInit { * Component being initialized. */ ngOnInit(): void { - this.module = CoreNavigator.instance.getRouteParam('module'); - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId'); + this.module = CoreNavigator.getRouteParam('module'); + this.courseId = CoreNavigator.getRouteNumberParam('courseId'); this.title = this.module?.name; } diff --git a/src/addons/mod/page/services/handlers/index-link.ts b/src/addons/mod/page/services/handlers/index-link.ts index 6cda5a026..378c2e27d 100644 --- a/src/addons/mod/page/services/handlers/index-link.ts +++ b/src/addons/mod/page/services/handlers/index-link.ts @@ -36,9 +36,9 @@ export class AddonModPageIndexLinkHandlerService extends CoreContentLinksModuleI * @return Whether the handler is enabled for the URL and site. */ isEnabled(siteId: string): Promise { - return AddonModPage.instance.isPluginEnabled(siteId); + return AddonModPage.isPluginEnabled(siteId); } } -export class AddonModPageIndexLinkHandler extends makeSingleton(AddonModPageIndexLinkHandlerService) {} +export const AddonModPageIndexLinkHandler = makeSingleton(AddonModPageIndexLinkHandlerService); diff --git a/src/addons/mod/page/services/handlers/list-link.ts b/src/addons/mod/page/services/handlers/list-link.ts index 22a176266..322de780f 100644 --- a/src/addons/mod/page/services/handlers/list-link.ts +++ b/src/addons/mod/page/services/handlers/list-link.ts @@ -36,9 +36,9 @@ export class AddonModPageListLinkHandlerService extends CoreContentLinksModuleLi * @return Whether or not the handler is enabled on a site level. */ isEnabled(siteId: string): Promise { - return AddonModPage.instance.isPluginEnabled(siteId); + return AddonModPage.isPluginEnabled(siteId); } } -export class AddonModPageListLinkHandler extends makeSingleton(AddonModPageListLinkHandlerService) {} +export const AddonModPageListLinkHandler = makeSingleton(AddonModPageListLinkHandlerService); diff --git a/src/addons/mod/page/services/handlers/module.ts b/src/addons/mod/page/services/handlers/module.ts index dec3d123e..7344acbd6 100644 --- a/src/addons/mod/page/services/handlers/module.ts +++ b/src/addons/mod/page/services/handlers/module.ts @@ -51,7 +51,7 @@ export class AddonModPageModuleHandlerService implements CoreCourseModuleHandler * @return Whether or not the handler is enabled on a site level. */ isEnabled(): Promise { - return AddonModPage.instance.isPluginEnabled(); + return AddonModPage.isPluginEnabled(); } /** @@ -62,7 +62,7 @@ export class AddonModPageModuleHandlerService implements CoreCourseModuleHandler */ getData(module: CoreCourseAnyModuleData): CoreCourseModuleHandlerData { return { - icon: CoreCourse.instance.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), + icon: CoreCourse.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), title: module.name, class: 'addon-mod_page-handler', showDownloadButton: true, @@ -72,7 +72,7 @@ export class AddonModPageModuleHandlerService implements CoreCourseModuleHandler Object.assign(options.params, { module }); const routeParams = '/' + courseId + '/' + module.id; - CoreNavigator.instance.navigateToSitePath(AddonModPageModuleHandlerService.PAGE_NAME + routeParams, options); + CoreNavigator.navigateToSitePath(AddonModPageModuleHandlerService.PAGE_NAME + routeParams, options); }, }; } @@ -90,4 +90,4 @@ export class AddonModPageModuleHandlerService implements CoreCourseModuleHandler } } -export class AddonModPageModuleHandler extends makeSingleton(AddonModPageModuleHandlerService) {} +export const AddonModPageModuleHandler = makeSingleton(AddonModPageModuleHandlerService); diff --git a/src/addons/mod/page/services/handlers/pluginfile.ts b/src/addons/mod/page/services/handlers/pluginfile.ts index 7a442ae1f..066fa5765 100644 --- a/src/addons/mod/page/services/handlers/pluginfile.ts +++ b/src/addons/mod/page/services/handlers/pluginfile.ts @@ -60,4 +60,4 @@ export class AddonModPagePluginFileHandlerService implements CorePluginFileHandl } -export class AddonModPagePluginFileHandler extends makeSingleton(AddonModPagePluginFileHandlerService) {} +export const AddonModPagePluginFileHandler = makeSingleton(AddonModPagePluginFileHandlerService); diff --git a/src/addons/mod/page/services/handlers/prefetch.ts b/src/addons/mod/page/services/handlers/prefetch.ts index 36b8bafc6..187d77fd6 100644 --- a/src/addons/mod/page/services/handlers/prefetch.ts +++ b/src/addons/mod/page/services/handlers/prefetch.ts @@ -43,8 +43,8 @@ export class AddonModPagePrefetchHandlerService extends CoreCourseResourcePrefet promises.push(super.downloadOrPrefetch(module, courseId, prefetch)); - if (AddonModPage.instance.isGetPageWSAvailable()) { - promises.push(AddonModPage.instance.getPageData(courseId, module.id)); + if (AddonModPage.isGetPageWSAvailable()) { + promises.push(AddonModPage.getPageData(courseId, module.id)); } await Promise.all(promises); @@ -58,7 +58,7 @@ export class AddonModPagePrefetchHandlerService extends CoreCourseResourcePrefet * @return Promise resolved when the data is invalidated. */ async invalidateContent(moduleId: number, courseId: number): Promise { - await AddonModPage.instance.invalidateContent(moduleId, courseId); + await AddonModPage.invalidateContent(moduleId, courseId); } /** @@ -71,10 +71,10 @@ export class AddonModPagePrefetchHandlerService extends CoreCourseResourcePrefet async invalidateModule(module: CoreCourseAnyModuleData, courseId: number): Promise { const promises: Promise[] = []; - promises.push(AddonModPage.instance.invalidatePageData(courseId)); - promises.push(CoreCourse.instance.invalidateModule(module.id)); + promises.push(AddonModPage.invalidatePageData(courseId)); + promises.push(CoreCourse.invalidateModule(module.id)); - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); } /** @@ -83,8 +83,8 @@ export class AddonModPagePrefetchHandlerService extends CoreCourseResourcePrefet * @return A boolean, or a promise resolved with a boolean, indicating if the handler is enabled. */ isEnabled(): Promise { - return AddonModPage.instance.isPluginEnabled(); + return AddonModPage.isPluginEnabled(); } } -export class AddonModPagePrefetchHandler extends makeSingleton(AddonModPagePrefetchHandlerService) {} +export const AddonModPagePrefetchHandler = makeSingleton(AddonModPagePrefetchHandlerService); diff --git a/src/addons/mod/page/services/page-helper.ts b/src/addons/mod/page/services/page-helper.ts index b3bb4f58c..a57f37e6e 100644 --- a/src/addons/mod/page/services/page-helper.ts +++ b/src/addons/mod/page/services/page-helper.ts @@ -54,7 +54,7 @@ export class AddonModPageHelperProvider { // Add the folders without the leading slash. key = content.filepath.substr(1) + key; } - paths[CoreTextUtils.instance.decodeURIComponent(key)] = url; + paths[CoreTextUtils.decodeURIComponent(key)] = url; } }); @@ -65,10 +65,10 @@ export class AddonModPageHelperProvider { } let url: string; - if (CoreFile.instance.isAvailable()) { + if (CoreFile.isAvailable()) { // The file system is available. - url = await CoreFilepool.instance.downloadUrl( - CoreSites.instance.getCurrentSiteId(), + url = await CoreFilepool.downloadUrl( + CoreSites.getCurrentSiteId(), indexUrl, false, AddonModPageProvider.COMPONENT, @@ -76,14 +76,14 @@ export class AddonModPageHelperProvider { ); } else { // We return the live URL. - url = await CoreSites.instance.getCurrentSite()?.checkAndFixPluginfileURL(indexUrl) || ''; + url = await CoreSites.getCurrentSite()?.checkAndFixPluginfileURL(indexUrl) || ''; } - const content = await CoreWS.instance.getText(url); + const content = await CoreWS.getText(url); // Now that we have the content, we update the SRC to point back to the external resource. // That will be caught by core-format-text. - return CoreDomUtils.instance.restoreSourcesInHtml(content, paths); + return CoreDomUtils.restoreSourcesInHtml(content, paths); } /** @@ -102,4 +102,4 @@ export class AddonModPageHelperProvider { } } -export class AddonModPageHelper extends makeSingleton(AddonModPageHelperProvider) {} +export const AddonModPageHelper = makeSingleton(AddonModPageHelperProvider); diff --git a/src/addons/mod/page/services/page.ts b/src/addons/mod/page/services/page.ts index 77955dc3f..cbebdc9a8 100644 --- a/src/addons/mod/page/services/page.ts +++ b/src/addons/mod/page/services/page.ts @@ -60,7 +60,7 @@ export class AddonModPageProvider { value: number, options: CoreSitesCommonWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModPageGetPagesByCoursesWSParams = { courseids: [courseId], @@ -69,7 +69,7 @@ export class AddonModPageProvider { cacheKey: this.getPageCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModPageProvider.COMPONENT, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), }; const response = await site.read('mod_page_get_pages_by_courses', params, preSets); @@ -100,15 +100,15 @@ export class AddonModPageProvider { * @param siteId Site ID. If not defined, current site. */ invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const promises: Promise[] = []; promises.push(this.invalidatePageData(courseId, siteId)); - promises.push(CoreFilepool.instance.invalidateFilesByComponent(siteId, AddonModPageProvider.COMPONENT, moduleId)); - promises.push(CoreCourse.instance.invalidateModule(moduleId, siteId)); + promises.push(CoreFilepool.invalidateFilesByComponent(siteId, AddonModPageProvider.COMPONENT, moduleId)); + promises.push(CoreCourse.invalidateModule(moduleId, siteId)); - return CoreUtils.instance.allPromises(promises); + return CoreUtils.allPromises(promises); } /** @@ -119,7 +119,7 @@ export class AddonModPageProvider { * @return Promise resolved when the data is invalidated. */ async invalidatePageData(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getPageCacheKey(courseId)); } @@ -131,7 +131,7 @@ export class AddonModPageProvider { * @since 3.3 */ isGetPageWSAvailable(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('mod_page_get_pages_by_courses'); + return CoreSites.wsAvailableInCurrentSite('mod_page_get_pages_by_courses'); } /** @@ -141,7 +141,7 @@ export class AddonModPageProvider { * @return Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise. */ async isPluginEnabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.canDownloadFiles(); } @@ -159,7 +159,7 @@ export class AddonModPageProvider { pageid, }; - return CoreCourseLogHelper.instance.logSingle( + return CoreCourseLogHelper.logSingle( 'mod_page_view_page', params, AddonModPageProvider.COMPONENT, @@ -173,7 +173,7 @@ export class AddonModPageProvider { } -export class AddonModPage extends makeSingleton(AddonModPageProvider) {} +export const AddonModPage = makeSingleton(AddonModPageProvider); /** diff --git a/src/addons/mod/quiz/accessrules/delaybetweenattempts/delaybetweenattempts.module.ts b/src/addons/mod/quiz/accessrules/delaybetweenattempts/delaybetweenattempts.module.ts index feefd7d1f..6f2b96191 100644 --- a/src/addons/mod/quiz/accessrules/delaybetweenattempts/delaybetweenattempts.module.ts +++ b/src/addons/mod/quiz/accessrules/delaybetweenattempts/delaybetweenattempts.module.ts @@ -26,7 +26,7 @@ import { AddonModQuizAccessDelayBetweenAttemptsHandler } from './services/handle multi: true, deps: [], useFactory: () => () => { - AddonModQuizAccessRuleDelegate.instance.registerHandler(AddonModQuizAccessDelayBetweenAttemptsHandler.instance); + AddonModQuizAccessRuleDelegate.registerHandler(AddonModQuizAccessDelayBetweenAttemptsHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/accessrules/delaybetweenattempts/services/handlers/delaybetweenattempts.ts b/src/addons/mod/quiz/accessrules/delaybetweenattempts/services/handlers/delaybetweenattempts.ts index e66527e48..34f8bcfb8 100644 --- a/src/addons/mod/quiz/accessrules/delaybetweenattempts/services/handlers/delaybetweenattempts.ts +++ b/src/addons/mod/quiz/accessrules/delaybetweenattempts/services/handlers/delaybetweenattempts.ts @@ -50,5 +50,4 @@ export class AddonModQuizAccessDelayBetweenAttemptsHandlerService implements Add } -export class AddonModQuizAccessDelayBetweenAttemptsHandler - extends makeSingleton(AddonModQuizAccessDelayBetweenAttemptsHandlerService) {} +export const AddonModQuizAccessDelayBetweenAttemptsHandler = makeSingleton(AddonModQuizAccessDelayBetweenAttemptsHandlerService); diff --git a/src/addons/mod/quiz/accessrules/ipaddress/ipaddress.module.ts b/src/addons/mod/quiz/accessrules/ipaddress/ipaddress.module.ts index 693912758..5f33d6adb 100644 --- a/src/addons/mod/quiz/accessrules/ipaddress/ipaddress.module.ts +++ b/src/addons/mod/quiz/accessrules/ipaddress/ipaddress.module.ts @@ -26,7 +26,7 @@ import { AddonModQuizAccessIpAddressHandler } from './services/handlers/ipaddres multi: true, deps: [], useFactory: () => () => { - AddonModQuizAccessRuleDelegate.instance.registerHandler(AddonModQuizAccessIpAddressHandler.instance); + AddonModQuizAccessRuleDelegate.registerHandler(AddonModQuizAccessIpAddressHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/accessrules/ipaddress/services/handlers/ipaddress.ts b/src/addons/mod/quiz/accessrules/ipaddress/services/handlers/ipaddress.ts index ca96e8ef7..5a92082b5 100644 --- a/src/addons/mod/quiz/accessrules/ipaddress/services/handlers/ipaddress.ts +++ b/src/addons/mod/quiz/accessrules/ipaddress/services/handlers/ipaddress.ts @@ -50,4 +50,4 @@ export class AddonModQuizAccessIpAddressHandlerService implements AddonModQuizAc } -export class AddonModQuizAccessIpAddressHandler extends makeSingleton(AddonModQuizAccessIpAddressHandlerService) {} +export const AddonModQuizAccessIpAddressHandler = makeSingleton(AddonModQuizAccessIpAddressHandlerService); diff --git a/src/addons/mod/quiz/accessrules/numattempts/numattempts.module.ts b/src/addons/mod/quiz/accessrules/numattempts/numattempts.module.ts index 5ce73b554..d6774518c 100644 --- a/src/addons/mod/quiz/accessrules/numattempts/numattempts.module.ts +++ b/src/addons/mod/quiz/accessrules/numattempts/numattempts.module.ts @@ -26,7 +26,7 @@ import { AddonModQuizAccessNumAttemptsHandler } from './services/handlers/numatt multi: true, deps: [], useFactory: () => () => { - AddonModQuizAccessRuleDelegate.instance.registerHandler(AddonModQuizAccessNumAttemptsHandler.instance); + AddonModQuizAccessRuleDelegate.registerHandler(AddonModQuizAccessNumAttemptsHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/accessrules/numattempts/services/handlers/numattempts.ts b/src/addons/mod/quiz/accessrules/numattempts/services/handlers/numattempts.ts index 347bc6a77..df8b6ed64 100644 --- a/src/addons/mod/quiz/accessrules/numattempts/services/handlers/numattempts.ts +++ b/src/addons/mod/quiz/accessrules/numattempts/services/handlers/numattempts.ts @@ -50,4 +50,4 @@ export class AddonModQuizAccessNumAttemptsHandlerService implements AddonModQuiz } -export class AddonModQuizAccessNumAttemptsHandler extends makeSingleton(AddonModQuizAccessNumAttemptsHandlerService) {} +export const AddonModQuizAccessNumAttemptsHandler = makeSingleton(AddonModQuizAccessNumAttemptsHandlerService); diff --git a/src/addons/mod/quiz/accessrules/offlineattempts/component/offlineattempts.ts b/src/addons/mod/quiz/accessrules/offlineattempts/component/offlineattempts.ts index d6566ebc0..b976fcaff 100644 --- a/src/addons/mod/quiz/accessrules/offlineattempts/component/offlineattempts.ts +++ b/src/addons/mod/quiz/accessrules/offlineattempts/component/offlineattempts.ts @@ -48,9 +48,9 @@ export class AddonModQuizAccessOfflineAttemptsComponent implements OnInit { return; } - const time = await AddonModQuizSync.instance.getSyncTime(this.quiz.id); + const time = await AddonModQuizSync.getSyncTime(this.quiz.id); - this.syncTimeReadable = AddonModQuizSync.instance.getReadableTimeFromTimestamp(time); + this.syncTimeReadable = AddonModQuizSync.getReadableTimeFromTimestamp(time); } } diff --git a/src/addons/mod/quiz/accessrules/offlineattempts/offlineattempts.module.ts b/src/addons/mod/quiz/accessrules/offlineattempts/offlineattempts.module.ts index bfd496662..9f25e7429 100644 --- a/src/addons/mod/quiz/accessrules/offlineattempts/offlineattempts.module.ts +++ b/src/addons/mod/quiz/accessrules/offlineattempts/offlineattempts.module.ts @@ -32,7 +32,7 @@ import { AddonModQuizAccessOfflineAttemptsHandler } from './services/handlers/of multi: true, deps: [], useFactory: () => () => { - AddonModQuizAccessRuleDelegate.instance.registerHandler(AddonModQuizAccessOfflineAttemptsHandler.instance); + AddonModQuizAccessRuleDelegate.registerHandler(AddonModQuizAccessOfflineAttemptsHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/accessrules/offlineattempts/services/handlers/offlineattempts.ts b/src/addons/mod/quiz/accessrules/offlineattempts/services/handlers/offlineattempts.ts index d0d7ba2af..bc1cf2b82 100644 --- a/src/addons/mod/quiz/accessrules/offlineattempts/services/handlers/offlineattempts.ts +++ b/src/addons/mod/quiz/accessrules/offlineattempts/services/handlers/offlineattempts.ts @@ -91,12 +91,12 @@ export class AddonModQuizAccessOfflineAttemptsHandlerService implements AddonMod return true; } - const syncTime = await AddonModQuizSync.instance.getSyncTime(quiz.id); + const syncTime = await AddonModQuizSync.getSyncTime(quiz.id); // Show warning if last sync was a while ago. - return Date.now() - AddonModQuizSync.instance.syncInterval > syncTime; + return Date.now() - AddonModQuizSync.syncInterval > syncTime; } } -export class AddonModQuizAccessOfflineAttemptsHandler extends makeSingleton(AddonModQuizAccessOfflineAttemptsHandlerService) {} +export const AddonModQuizAccessOfflineAttemptsHandler = makeSingleton(AddonModQuizAccessOfflineAttemptsHandlerService); diff --git a/src/addons/mod/quiz/accessrules/openclosedate/openclosedate.module.ts b/src/addons/mod/quiz/accessrules/openclosedate/openclosedate.module.ts index 3f19048f8..536df6a30 100644 --- a/src/addons/mod/quiz/accessrules/openclosedate/openclosedate.module.ts +++ b/src/addons/mod/quiz/accessrules/openclosedate/openclosedate.module.ts @@ -26,7 +26,7 @@ import { AddonModQuizAccessOpenCloseDateHandler } from './services/handlers/open multi: true, deps: [], useFactory: () => () => { - AddonModQuizAccessRuleDelegate.instance.registerHandler(AddonModQuizAccessOpenCloseDateHandler.instance); + AddonModQuizAccessRuleDelegate.registerHandler(AddonModQuizAccessOpenCloseDateHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/accessrules/openclosedate/services/handlers/openclosedate.ts b/src/addons/mod/quiz/accessrules/openclosedate/services/handlers/openclosedate.ts index 58d2854ef..8cd0628b5 100644 --- a/src/addons/mod/quiz/accessrules/openclosedate/services/handlers/openclosedate.ts +++ b/src/addons/mod/quiz/accessrules/openclosedate/services/handlers/openclosedate.ts @@ -73,4 +73,4 @@ export class AddonModQuizAccessOpenCloseDateHandlerService implements AddonModQu } -export class AddonModQuizAccessOpenCloseDateHandler extends makeSingleton(AddonModQuizAccessOpenCloseDateHandlerService) {} +export const AddonModQuizAccessOpenCloseDateHandler = makeSingleton(AddonModQuizAccessOpenCloseDateHandlerService); diff --git a/src/addons/mod/quiz/accessrules/password/password.module.ts b/src/addons/mod/quiz/accessrules/password/password.module.ts index ebad48b4c..9e1cefb3e 100644 --- a/src/addons/mod/quiz/accessrules/password/password.module.ts +++ b/src/addons/mod/quiz/accessrules/password/password.module.ts @@ -40,7 +40,7 @@ import { SITE_SCHEMA } from './services/database/password'; multi: true, deps: [], useFactory: () => () => { - AddonModQuizAccessRuleDelegate.instance.registerHandler(AddonModQuizAccessPasswordHandler.instance); + AddonModQuizAccessRuleDelegate.registerHandler(AddonModQuizAccessPasswordHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/accessrules/password/services/handlers/password.ts b/src/addons/mod/quiz/accessrules/password/services/handlers/password.ts index 3e37f4331..447b336b6 100644 --- a/src/addons/mod/quiz/accessrules/password/services/handlers/password.ts +++ b/src/addons/mod/quiz/accessrules/password/services/handlers/password.ts @@ -70,7 +70,7 @@ export class AddonModQuizAccessPasswordHandlerService implements AddonModQuizAcc * @return Promise resolved with the DB entry on success. */ protected async getPasswordEntry(quizId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecord(PASSWORD_TABLE_NAME, { id: quizId }); } @@ -111,7 +111,7 @@ export class AddonModQuizAccessPasswordHandlerService implements AddonModQuizAcc siteId?: string, ): Promise { // If there's a password stored don't require the preflight since we'll use the stored one. - const entry = await CoreUtils.instance.ignoreErrors(this.getPasswordEntry(quiz.id, siteId)); + const entry = await CoreUtils.ignoreErrors(this.getPasswordEntry(quiz.id, siteId)); return !entry; } @@ -168,7 +168,7 @@ export class AddonModQuizAccessPasswordHandlerService implements AddonModQuizAcc * @return Promise resolved when done. */ protected async removePassword(quizId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(PASSWORD_TABLE_NAME, { id: quizId }); } @@ -182,7 +182,7 @@ export class AddonModQuizAccessPasswordHandlerService implements AddonModQuizAcc * @return Promise resolved when done. */ protected async storePassword(quizId: number, password: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entry: AddonModQuizAccessPasswordDBRecord = { id: quizId, @@ -195,4 +195,4 @@ export class AddonModQuizAccessPasswordHandlerService implements AddonModQuizAcc } -export class AddonModQuizAccessPasswordHandler extends makeSingleton(AddonModQuizAccessPasswordHandlerService) {} +export const AddonModQuizAccessPasswordHandler = makeSingleton(AddonModQuizAccessPasswordHandlerService); diff --git a/src/addons/mod/quiz/accessrules/safebrowser/safebrowser.module.ts b/src/addons/mod/quiz/accessrules/safebrowser/safebrowser.module.ts index 8078e2f93..d7762e27d 100644 --- a/src/addons/mod/quiz/accessrules/safebrowser/safebrowser.module.ts +++ b/src/addons/mod/quiz/accessrules/safebrowser/safebrowser.module.ts @@ -26,7 +26,7 @@ import { AddonModQuizAccessSafeBrowserHandler } from './services/handlers/safebr multi: true, deps: [], useFactory: () => () => { - AddonModQuizAccessRuleDelegate.instance.registerHandler(AddonModQuizAccessSafeBrowserHandler.instance); + AddonModQuizAccessRuleDelegate.registerHandler(AddonModQuizAccessSafeBrowserHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/accessrules/safebrowser/services/handlers/safebrowser.ts b/src/addons/mod/quiz/accessrules/safebrowser/services/handlers/safebrowser.ts index f85bba085..631e08e56 100644 --- a/src/addons/mod/quiz/accessrules/safebrowser/services/handlers/safebrowser.ts +++ b/src/addons/mod/quiz/accessrules/safebrowser/services/handlers/safebrowser.ts @@ -50,4 +50,4 @@ export class AddonModQuizAccessSafeBrowserHandlerService implements AddonModQuiz } -export class AddonModQuizAccessSafeBrowserHandler extends makeSingleton(AddonModQuizAccessSafeBrowserHandlerService) {} +export const AddonModQuizAccessSafeBrowserHandler = makeSingleton(AddonModQuizAccessSafeBrowserHandlerService); diff --git a/src/addons/mod/quiz/accessrules/securewindow/securewindow.module.ts b/src/addons/mod/quiz/accessrules/securewindow/securewindow.module.ts index 748371fb9..7a8f1da71 100644 --- a/src/addons/mod/quiz/accessrules/securewindow/securewindow.module.ts +++ b/src/addons/mod/quiz/accessrules/securewindow/securewindow.module.ts @@ -26,7 +26,7 @@ import { AddonModQuizAccessSecureWindowHandler } from './services/handlers/secur multi: true, deps: [], useFactory: () => () => { - AddonModQuizAccessRuleDelegate.instance.registerHandler(AddonModQuizAccessSecureWindowHandler.instance); + AddonModQuizAccessRuleDelegate.registerHandler(AddonModQuizAccessSecureWindowHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/accessrules/securewindow/services/handlers/securewindow.ts b/src/addons/mod/quiz/accessrules/securewindow/services/handlers/securewindow.ts index e44bc366a..ae2d50ea5 100644 --- a/src/addons/mod/quiz/accessrules/securewindow/services/handlers/securewindow.ts +++ b/src/addons/mod/quiz/accessrules/securewindow/services/handlers/securewindow.ts @@ -50,4 +50,4 @@ export class AddonModQuizAccessSecureWindowHandlerService implements AddonModQui } -export class AddonModQuizAccessSecureWindowHandler extends makeSingleton(AddonModQuizAccessSecureWindowHandlerService) {} +export const AddonModQuizAccessSecureWindowHandler = makeSingleton(AddonModQuizAccessSecureWindowHandlerService); diff --git a/src/addons/mod/quiz/accessrules/timelimit/component/timelimit.ts b/src/addons/mod/quiz/accessrules/timelimit/component/timelimit.ts index 0cf94ba9b..d68cc64fa 100644 --- a/src/addons/mod/quiz/accessrules/timelimit/component/timelimit.ts +++ b/src/addons/mod/quiz/accessrules/timelimit/component/timelimit.ts @@ -41,7 +41,7 @@ export class AddonModQuizAccessTimeLimitComponent implements OnInit { return; } - this.readableTimeLimit = CoreTimeUtils.instance.formatTime(this.quiz?.timelimit); + this.readableTimeLimit = CoreTimeUtils.formatTime(this.quiz?.timelimit); } } diff --git a/src/addons/mod/quiz/accessrules/timelimit/services/handlers/timelimit.ts b/src/addons/mod/quiz/accessrules/timelimit/services/handlers/timelimit.ts index ee8c7bf1a..232489112 100644 --- a/src/addons/mod/quiz/accessrules/timelimit/services/handlers/timelimit.ts +++ b/src/addons/mod/quiz/accessrules/timelimit/services/handlers/timelimit.ts @@ -80,4 +80,4 @@ export class AddonModQuizAccessTimeLimitHandlerService implements AddonModQuizAc } -export class AddonModQuizAccessTimeLimitHandler extends makeSingleton(AddonModQuizAccessTimeLimitHandlerService) {} +export const AddonModQuizAccessTimeLimitHandler = makeSingleton(AddonModQuizAccessTimeLimitHandlerService); diff --git a/src/addons/mod/quiz/accessrules/timelimit/timelimit.module.ts b/src/addons/mod/quiz/accessrules/timelimit/timelimit.module.ts index f482484f4..e8d3ac8bf 100644 --- a/src/addons/mod/quiz/accessrules/timelimit/timelimit.module.ts +++ b/src/addons/mod/quiz/accessrules/timelimit/timelimit.module.ts @@ -32,7 +32,7 @@ import { AddonModQuizAccessTimeLimitHandler } from './services/handlers/timelimi multi: true, deps: [], useFactory: () => () => { - AddonModQuizAccessRuleDelegate.instance.registerHandler(AddonModQuizAccessTimeLimitHandler.instance); + AddonModQuizAccessRuleDelegate.registerHandler(AddonModQuizAccessTimeLimitHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/classes/auto-save.ts b/src/addons/mod/quiz/classes/auto-save.ts index 981d4bd89..45021ed00 100644 --- a/src/addons/mod/quiz/classes/auto-save.ts +++ b/src/addons/mod/quiz/classes/auto-save.ts @@ -113,7 +113,7 @@ export class AddonModQuizAutoSave { * @return Answers. */ protected getAnswers(): CoreQuestionsAnswers { - return CoreQuestionHelper.instance.getAnswersFromForm(document.forms[this.formName]); + return CoreQuestionHelper.getAnswersFromForm(document.forms[this.formName]); } /** @@ -149,7 +149,7 @@ export class AddonModQuizAutoSave { offline?: boolean, ): void { // Don't schedule if already shceduled or quiz is almost closed. - if (!quiz.autosaveperiod || this.autoSaveTimeout || AddonModQuiz.instance.isAttemptTimeNearlyOver(quiz, attempt)) { + if (!quiz.autosaveperiod || this.autoSaveTimeout || AddonModQuiz.isAttemptTimeNearlyOver(quiz, attempt)) { return; } @@ -160,7 +160,7 @@ export class AddonModQuizAutoSave { this.previousAnswers = answers; // Update previous answers to match what we're sending to the server. try { - await AddonModQuiz.instance.saveAttempt(quiz, attempt, answers, preflightData, offline); + await AddonModQuiz.saveAttempt(quiz, attempt, answers, preflightData, offline); // Save successful, we can hide the connection error if it was shown. this.hideAutoSaveError(); @@ -197,7 +197,7 @@ export class AddonModQuizAutoSave { }; this.popoverShown = true; - this.popover = await PopoverController.instance.create({ + this.popover = await PopoverController.create({ component: AddonModQuizConnectionErrorComponent, event: event, }); diff --git a/src/addons/mod/quiz/components/index/index.ts b/src/addons/mod/quiz/components/index/index.ts index a3fd16fa3..f81710cc9 100644 --- a/src/addons/mod/quiz/components/index/index.ts +++ b/src/addons/mod/quiz/components/index/index.ts @@ -127,9 +127,9 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp } try { - await AddonModQuiz.instance.logViewQuiz(this.quiz.id, this.quiz.name); + await AddonModQuiz.logViewQuiz(this.quiz.id, this.quiz.name); - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); } catch { // Ignore errors. } @@ -144,7 +144,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp return; } - if (!AddonModQuiz.instance.isQuizOffline(this.quiz)) { + if (!AddonModQuiz.isQuizOffline(this.quiz)) { // Quiz isn't offline, just open it. return this.openQuiz(); } @@ -153,7 +153,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp // If the site doesn't support check updates, always prefetch it because we cannot tell if there's something new. const isDownloaded = this.currentStatus == CoreConstants.DOWNLOADED; - if (isDownloaded && CoreCourseModulePrefetchDelegate.instance.canCheckUpdates()) { + if (isDownloaded && CoreCourseModulePrefetchDelegate.canCheckUpdates()) { // Already downloaded, open it. return this.openQuiz(); } @@ -162,17 +162,17 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp this.showStatusSpinner = true; try { - await AddonModQuizPrefetchHandler.instance.prefetch(this.module!, this.courseId, true); + await AddonModQuizPrefetchHandler.prefetch(this.module!, this.courseId, true); // Success downloading, open quiz. this.openQuiz(); } catch (error) { - if (this.hasOffline || (isDownloaded && !CoreCourseModulePrefetchDelegate.instance.canCheckUpdates())) { + if (this.hasOffline || (isDownloaded && !CoreCourseModulePrefetchDelegate.canCheckUpdates())) { // Error downloading but there is something offline, allow continuing it. // If the site doesn't support check updates, continue too because we cannot tell if there's something new. this.openQuiz(); } else { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); } } finally { this.showStatusSpinner = false; @@ -190,25 +190,25 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp protected async fetchContent(refresh: boolean = false, sync: boolean = false, showErrors: boolean = false): Promise { try { // First get the quiz instance. - const quiz = await AddonModQuiz.instance.getQuiz(this.courseId!, this.module!.id); + const quiz = await AddonModQuiz.getQuiz(this.courseId!, this.module!.id); - this.gradeMethodReadable = AddonModQuiz.instance.getQuizGradeMethod(quiz.grademethod); + this.gradeMethodReadable = AddonModQuiz.getQuizGradeMethod(quiz.grademethod); this.now = Date.now(); this.dataRetrieved.emit(quiz); this.description = quiz.intro || this.description; this.candidateQuiz = quiz; // Try to get warnings from automatic sync. - const warnings = await AddonModQuizSync.instance.getSyncWarnings(quiz.id); + const warnings = await AddonModQuizSync.getSyncWarnings(quiz.id); if (warnings?.length) { // Show warnings and delete them so they aren't shown again. - CoreDomUtils.instance.showErrorModal(CoreTextUtils.instance.buildMessage(warnings)); + CoreDomUtils.showErrorModal(CoreTextUtils.buildMessage(warnings)); - await AddonModQuizSync.instance.setSyncWarnings(quiz.id, []); + await AddonModQuizSync.setSyncWarnings(quiz.id, []); } - if (AddonModQuiz.instance.isQuizOffline(quiz) && sync) { + if (AddonModQuiz.isQuizOffline(quiz) && sync) { // Try to sync the quiz. try { await this.syncActivity(showErrors); @@ -221,30 +221,30 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp this.showStatusSpinner = false; } - if (AddonModQuiz.instance.isQuizOffline(quiz)) { + if (AddonModQuiz.isQuizOffline(quiz)) { // Handle status. this.setStatusListener(); // Get last synchronization time and check if sync button should be seen. - this.syncTime = await AddonModQuizSync.instance.getReadableSyncTime(quiz.id); - this.hasOffline = await AddonModQuizSync.instance.hasDataToSync(quiz.id); + this.syncTime = await AddonModQuizSync.getReadableSyncTime(quiz.id); + this.hasOffline = await AddonModQuizSync.hasDataToSync(quiz.id); } // Get quiz access info. - this.quizAccessInfo = await AddonModQuiz.instance.getQuizAccessInformation(quiz.id, { cmId: this.module!.id }); + this.quizAccessInfo = await AddonModQuiz.getQuizAccessInformation(quiz.id, { cmId: this.module!.id }); this.showReviewColumn = this.quizAccessInfo.canreviewmyattempts; this.accessRules = this.quizAccessInfo.accessrules; - this.unsupportedRules = AddonModQuiz.instance.getUnsupportedRules(this.quizAccessInfo.activerulenames); + this.unsupportedRules = AddonModQuiz.getUnsupportedRules(this.quizAccessInfo.activerulenames); if (quiz.preferredbehaviour) { - this.behaviourSupported = CoreQuestionBehaviourDelegate.instance.isBehaviourSupported(quiz.preferredbehaviour); + this.behaviourSupported = CoreQuestionBehaviourDelegate.isBehaviourSupported(quiz.preferredbehaviour); } // Get question types in the quiz. - const types = await AddonModQuiz.instance.getQuizRequiredQtypes(quiz.id, { cmId: this.module!.id }); + const types = await AddonModQuiz.getQuizRequiredQtypes(quiz.id, { cmId: this.module!.id }); - this.unsupportedQuestions = AddonModQuiz.instance.getUnsupportedQuestions(types); + this.unsupportedQuestions = AddonModQuiz.getUnsupportedQuestions(types); this.hasSupportedQuestions = !!types.find((type) => type != 'random' && this.unsupportedQuestions.indexOf(type) == -1); await this.getAttempts(quiz); @@ -265,17 +265,17 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp protected async getAttempts(quiz: AddonModQuizQuizData): Promise { // Get access information of last attempt (it also works if no attempts made). - this.attemptAccessInfo = await AddonModQuiz.instance.getAttemptAccessInformation(quiz.id, 0, { cmId: this.module!.id }); + this.attemptAccessInfo = await AddonModQuiz.getAttemptAccessInformation(quiz.id, 0, { cmId: this.module!.id }); // Get attempts. - const attempts = await AddonModQuiz.instance.getUserAttempts(quiz.id, { cmId: this.module!.id }); + const attempts = await AddonModQuiz.getUserAttempts(quiz.id, { cmId: this.module!.id }); this.attempts = await this.treatAttempts(quiz, attempts); // Check if user can create/continue attempts. if (this.attempts.length) { const last = this.attempts[this.attempts.length - 1]; - this.moreAttempts = !AddonModQuiz.instance.isAttemptFinished(last.state) || !this.attemptAccessInfo.isfinished; + this.moreAttempts = !AddonModQuiz.isAttemptFinished(last.state) || !this.attemptAccessInfo.isfinished; } else { this.moreAttempts = !this.attemptAccessInfo.isfinished; } @@ -294,7 +294,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp this.buttonText = ''; if (quiz.hasquestions !== 0) { - if (this.attempts.length && !AddonModQuiz.instance.isAttemptFinished(this.attempts[this.attempts.length - 1].state)) { + if (this.attempts.length && !AddonModQuiz.isAttemptFinished(this.attempts[this.attempts.length - 1].state)) { // Last attempt is unfinished. if (this.quizAccessInfo?.canattempt) { this.buttonText = 'addon.mod_quiz.continueattemptquiz'; @@ -350,8 +350,8 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp return; } - const formattedGradebookGrade = AddonModQuiz.instance.formatGrade(this.gradebookData.grade, quiz.decimalpoints); - const formattedBestGrade = AddonModQuiz.instance.formatGrade(this.bestGrade.grade, quiz.decimalpoints); + const formattedGradebookGrade = AddonModQuiz.formatGrade(this.gradebookData.grade, quiz.decimalpoints); + const formattedBestGrade = AddonModQuiz.formatGrade(this.bestGrade.grade, quiz.decimalpoints); let gradeToShow = formattedGradebookGrade; // By default we show the grade in the gradebook. this.showResults = true; @@ -368,24 +368,24 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp if (this.overallStats) { // Show the quiz grade. The message shown is different if the quiz is finished. if (this.moreAttempts) { - this.gradeResult = Translate.instance.instant('addon.mod_quiz.gradesofar', { $a: { + this.gradeResult = Translate.instant('addon.mod_quiz.gradesofar', { $a: { method: this.gradeMethodReadable, mygrade: gradeToShow, quizgrade: quiz.gradeFormatted, } }); } else { - const outOfShort = Translate.instance.instant('addon.mod_quiz.outofshort', { $a: { + const outOfShort = Translate.instant('addon.mod_quiz.outofshort', { $a: { grade: gradeToShow, maxgrade: quiz.gradeFormatted, } }); - this.gradeResult = Translate.instance.instant('addon.mod_quiz.yourfinalgradeis', { $a: outOfShort }); + this.gradeResult = Translate.instant('addon.mod_quiz.yourfinalgradeis', { $a: outOfShort }); } } if (quiz.showFeedbackColumn) { // Get the quiz overall feedback. - const response = await AddonModQuiz.instance.getFeedbackForGrade(quiz.id, this.gradebookData.grade, { + const response = await AddonModQuiz.getFeedbackForGrade(quiz.id, this.gradebookData.grade, { cmId: this.module!.id, }); @@ -404,16 +404,16 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp } // If we go to auto review it means an attempt was finished. Check completion status. - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); // Verify that user can see the review. const attemptId = this.autoReview.attemptId; if (this.quizAccessInfo?.canreviewmyattempts) { try { - await AddonModQuiz.instance.getAttemptReview(attemptId, { page: -1, cmId: this.module!.id }); + await AddonModQuiz.getAttemptReview(attemptId, { page: -1, cmId: this.module!.id }); - await CoreNavigator.instance.navigate(`review/${attemptId}`); + await CoreNavigator.navigate(`review/${attemptId}`); } catch { // Ignore errors. } @@ -429,7 +429,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp protected hasSyncSucceed(result: AddonModQuizSyncResult): boolean { if (result.attemptFinished) { // An attempt was finished, check completion status. - CoreCourse.instance.checkModuleCompletion(this.courseId!, this.module!.completiondata); + CoreCourse.checkModuleCompletion(this.courseId!, this.module!.completiondata); } // If the sync call isn't rejected it means the sync was successful. @@ -465,7 +465,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp this.content?.scrollToTop(); await promise; - await CoreUtils.instance.ignoreErrors(this.refreshContent(true)); + await CoreUtils.ignoreErrors(this.refreshContent(true)); this.loaded = true; this.refreshIcon = CoreConstants.ICON_REFRESH; @@ -488,16 +488,16 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp protected async invalidateContent(): Promise { const promises: Promise[] = []; - promises.push(AddonModQuiz.instance.invalidateQuizData(this.courseId!)); + promises.push(AddonModQuiz.invalidateQuizData(this.courseId!)); if (this.quiz) { - promises.push(AddonModQuiz.instance.invalidateUserAttemptsForUser(this.quiz.id)); - promises.push(AddonModQuiz.instance.invalidateQuizAccessInformation(this.quiz.id)); - promises.push(AddonModQuiz.instance.invalidateQuizRequiredQtypes(this.quiz.id)); - promises.push(AddonModQuiz.instance.invalidateAttemptAccessInformation(this.quiz.id)); - promises.push(AddonModQuiz.instance.invalidateCombinedReviewOptionsForUser(this.quiz.id)); - promises.push(AddonModQuiz.instance.invalidateUserBestGradeForUser(this.quiz.id)); - promises.push(AddonModQuiz.instance.invalidateGradeFromGradebook(this.courseId!)); + promises.push(AddonModQuiz.invalidateUserAttemptsForUser(this.quiz.id)); + promises.push(AddonModQuiz.invalidateQuizAccessInformation(this.quiz.id)); + promises.push(AddonModQuiz.invalidateQuizRequiredQtypes(this.quiz.id)); + promises.push(AddonModQuiz.invalidateAttemptAccessInformation(this.quiz.id)); + promises.push(AddonModQuiz.invalidateCombinedReviewOptionsForUser(this.quiz.id)); + promises.push(AddonModQuiz.invalidateUserBestGradeForUser(this.quiz.id)); + promises.push(AddonModQuiz.invalidateGradeFromGradebook(this.courseId!)); } await Promise.all(promises); @@ -516,7 +516,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp if (syncEventData.attemptFinished) { // An attempt was finished, check completion status. - CoreCourse.instance.checkModuleCompletion(this.courseId, this.module.completiondata); + CoreCourse.checkModuleCompletion(this.courseId, this.module.completiondata); } if (this.quiz && syncEventData.quizId == this.quiz.id) { @@ -534,7 +534,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp protected openQuiz(): void { this.hasPlayed = true; - CoreNavigator.instance.navigate('player', { + CoreNavigator.navigate('player', { params: { moduleUrl: this.module?.url, }, @@ -563,7 +563,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp * @return Promise resolved when done. */ protected sync(): Promise { - return AddonModQuizSync.instance.syncQuiz(this.candidateQuiz!, true); + return AddonModQuizSync.syncQuiz(this.candidateQuiz!, true); } /** @@ -581,7 +581,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp return []; } - const lastFinished = AddonModQuiz.instance.getLastFinishedAttemptFromList(attempts); + const lastFinished = AddonModQuiz.getLastFinishedAttemptFromList(attempts); const promises: Promise[] = []; if (this.autoReview && lastFinished && lastFinished.id >= this.autoReview.attemptId) { @@ -594,7 +594,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp } // Get combined review options. - promises.push(AddonModQuiz.instance.getCombinedReviewOptions(quiz.id, { cmId: this.module!.id }).then((options) => { + promises.push(AddonModQuiz.getCombinedReviewOptions(quiz.id, { cmId: this.module!.id }).then((options) => { this.options = options; return; @@ -606,10 +606,10 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp await Promise.all(promises); const grade = typeof this.gradebookData?.grade != 'undefined' ? this.gradebookData.grade : this.bestGrade?.grade; - const quizGrade = AddonModQuiz.instance.formatGrade(grade, quiz.decimalpoints); + const quizGrade = AddonModQuiz.formatGrade(grade, quiz.decimalpoints); // Calculate data to construct the header of the attempts table. - AddonModQuizHelper.instance.setQuizCalculatedData(quiz, this.options!); + AddonModQuizHelper.setQuizCalculatedData(quiz, this.options!); this.overallStats = !!lastFinished && this.options!.alloptions.marks >= AddonModQuizProvider.QUESTION_OPTIONS_MARK_AND_MAX; @@ -620,7 +620,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp attempts.length > 1; const isLast = index == attempts.length - 1; - return AddonModQuizHelper.instance.setAttemptCalculatedData(quiz, attempt, shouldHighlight, quizGrade, isLast); + return AddonModQuizHelper.setAttemptCalculatedData(quiz, attempt, shouldHighlight, quizGrade, isLast); })); return formattedAttempts; @@ -633,11 +633,11 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp * @return Promise resolved when done. */ protected async getQuizGrade(quiz: AddonModQuizQuizData): Promise { - this.bestGrade = await AddonModQuiz.instance.getUserBestGrade(quiz.id, { cmId: this.module!.id }); + this.bestGrade = await AddonModQuiz.getUserBestGrade(quiz.id, { cmId: this.module!.id }); try { // Get gradebook grade. - const data = await AddonModQuiz.instance.getGradeFromGradebook(this.courseId!, this.module!.id); + const data = await AddonModQuiz.getGradeFromGradebook(this.courseId!, this.module!.id); if (data) { this.gradebookData = { @@ -659,7 +659,7 @@ export class AddonModQuizIndexComponent extends CoreCourseModuleMainActivityComp * @return Promise resolved when done. */ async viewAttempt(attemptId: number): Promise { - CoreNavigator.instance.navigate(`attempt/${attemptId}`); + CoreNavigator.navigate(`attempt/${attemptId}`); } /** diff --git a/src/addons/mod/quiz/components/navigation-modal/navigation-modal.ts b/src/addons/mod/quiz/components/navigation-modal/navigation-modal.ts index d081e47c1..f8ae64c15 100644 --- a/src/addons/mod/quiz/components/navigation-modal/navigation-modal.ts +++ b/src/addons/mod/quiz/components/navigation-modal/navigation-modal.ts @@ -40,7 +40,7 @@ export class AddonModQuizNavigationModalComponent { * Close modal. */ closeModal(): void { - ModalController.instance.dismiss(); + ModalController.dismiss(); } /** @@ -50,7 +50,7 @@ export class AddonModQuizNavigationModalComponent { * @param slot Slot of the question to scroll to. */ loadPage(page: number, slot?: number): void { - ModalController.instance.dismiss({ + ModalController.dismiss({ action: AddonModQuizNavigationModalComponent.CHANGE_PAGE, page, slot, @@ -61,7 +61,7 @@ export class AddonModQuizNavigationModalComponent { * Switch mode in review. */ switchMode(): void { - ModalController.instance.dismiss({ + ModalController.dismiss({ action: AddonModQuizNavigationModalComponent.SWITCH_MODE, }); } diff --git a/src/addons/mod/quiz/components/preflight-modal/preflight-modal.ts b/src/addons/mod/quiz/components/preflight-modal/preflight-modal.ts index ae2632ced..5a9dd4c12 100644 --- a/src/addons/mod/quiz/components/preflight-modal/preflight-modal.ts +++ b/src/addons/mod/quiz/components/preflight-modal/preflight-modal.ts @@ -57,8 +57,8 @@ export class AddonModQuizPreflightModalComponent implements OnInit { * Component being initialized. */ async ngOnInit(): Promise { - this.title = this.title || Translate.instance.instant('addon.mod_quiz.startattempt'); - this.siteId = this.siteId || CoreSites.instance.getCurrentSiteId(); + this.title = this.title || Translate.instant('addon.mod_quiz.startattempt'); + this.siteId = this.siteId || CoreSites.getCurrentSiteId(); this.rules = this.rules || []; if (!this.quiz) { @@ -68,7 +68,7 @@ export class AddonModQuizPreflightModalComponent implements OnInit { try { await Promise.all(this.rules.map(async (rule) => { // Check if preflight is required for rule and, if so, get the component to render it. - const required = await AddonModQuizAccessRuleDelegate.instance.isPreflightCheckRequiredForRule( + const required = await AddonModQuizAccessRuleDelegate.isPreflightCheckRequiredForRule( rule, this.quiz!, this.attempt, @@ -80,7 +80,7 @@ export class AddonModQuizPreflightModalComponent implements OnInit { return; } - const component = await AddonModQuizAccessRuleDelegate.instance.getPreflightComponent(rule); + const component = await AddonModQuizAccessRuleDelegate.getPreflightComponent(rule); if (!component) { return; } @@ -99,7 +99,7 @@ export class AddonModQuizPreflightModalComponent implements OnInit { })); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading rules'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading rules'); } finally { this.loaded = true; } @@ -116,19 +116,19 @@ export class AddonModQuizPreflightModalComponent implements OnInit { if (!this.preflightForm.valid) { // Form not valid. Scroll to the first element with errors. - const hasScrolled = CoreDomUtils.instance.scrollToInputError( + const hasScrolled = CoreDomUtils.scrollToInputError( this.elementRef.nativeElement, this.content, ); if (!hasScrolled) { // Input not found, show an error modal. - CoreDomUtils.instance.showErrorModal('core.errorinvalidform', true); + CoreDomUtils.showErrorModal('core.errorinvalidform', true); } } else { - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, false, this.siteId); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, false, this.siteId); - ModalController.instance.dismiss(this.preflightForm.value); + ModalController.dismiss(this.preflightForm.value); } } @@ -136,9 +136,9 @@ export class AddonModQuizPreflightModalComponent implements OnInit { * Close modal. */ closeModal(): void { - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, this.siteId); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, this.siteId); - ModalController.instance.dismiss(); + ModalController.dismiss(); } } diff --git a/src/addons/mod/quiz/pages/attempt/attempt.ts b/src/addons/mod/quiz/pages/attempt/attempt.ts index fe1ee3d27..74fa31df3 100644 --- a/src/addons/mod/quiz/pages/attempt/attempt.ts +++ b/src/addons/mod/quiz/pages/attempt/attempt.ts @@ -52,9 +52,9 @@ export class AddonModQuizAttemptPage implements OnInit { * Component being initialized. */ ngOnInit(): void { - this.cmId = CoreNavigator.instance.getRouteNumberParam('cmId')!; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.attemptId = CoreNavigator.instance.getRouteNumberParam('attemptId')!; + this.cmId = CoreNavigator.getRouteNumberParam('cmId')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.attemptId = CoreNavigator.getRouteNumberParam('attemptId')!; this.fetchQuizData().finally(() => { this.loaded = true; @@ -79,31 +79,31 @@ export class AddonModQuizAttemptPage implements OnInit { */ protected async fetchQuizData(): Promise { try { - this.quiz = await AddonModQuiz.instance.getQuiz(this.courseId, this.cmId); + this.quiz = await AddonModQuiz.getQuiz(this.courseId, this.cmId); this.componentId = this.quiz.coursemodule; // Load attempt data. const [options, accessInfo, attempt] = await Promise.all([ - AddonModQuiz.instance.getCombinedReviewOptions(this.quiz.id, { cmId: this.quiz.coursemodule }), + AddonModQuiz.getCombinedReviewOptions(this.quiz.id, { cmId: this.quiz.coursemodule }), this.fetchAccessInfo(), this.fetchAttempt(), ]); // Set calculated data. this.showReviewColumn = accessInfo.canreviewmyattempts; - AddonModQuizHelper.instance.setQuizCalculatedData(this.quiz, options); + AddonModQuizHelper.setQuizCalculatedData(this.quiz, options); - this.attempt = await AddonModQuizHelper.instance.setAttemptCalculatedData(this.quiz!, attempt, false, undefined, true); + this.attempt = await AddonModQuizHelper.setAttemptCalculatedData(this.quiz!, attempt, false, undefined, true); // Check if the feedback should be displayed. const grade = Number(this.attempt!.rescaledGrade); - if (this.quiz.showFeedbackColumn && AddonModQuiz.instance.isAttemptFinished(this.attempt!.state) && + if (this.quiz.showFeedbackColumn && AddonModQuiz.isAttemptFinished(this.attempt!.state) && options.someoptions.overallfeedback && !isNaN(grade)) { // Feedback should be displayed, get the feedback for the grade. - const response = await AddonModQuiz.instance.getFeedbackForGrade(this.quiz.id, grade, { + const response = await AddonModQuiz.getFeedbackForGrade(this.quiz.id, grade, { cmId: this.quiz.coursemodule, }); @@ -112,7 +112,7 @@ export class AddonModQuizAttemptPage implements OnInit { delete this.feedback; } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_quiz.errorgetattempt', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_quiz.errorgetattempt', true); } } @@ -123,7 +123,7 @@ export class AddonModQuizAttemptPage implements OnInit { */ protected async fetchAttempt(): Promise { // Get all the attempts and search the one we want. - const attempts = await AddonModQuiz.instance.getUserAttempts(this.quiz!.id, { cmId: this.cmId }); + const attempts = await AddonModQuiz.getUserAttempts(this.quiz!.id, { cmId: this.cmId }); const attempt = attempts.find(attempt => attempt.id == this.attemptId); @@ -131,7 +131,7 @@ export class AddonModQuizAttemptPage implements OnInit { // Attempt not found, error. this.attempt = undefined; - throw new CoreError(Translate.instance.instant('addon.mod_quiz.errorgetattempt')); + throw new CoreError(Translate.instant('addon.mod_quiz.errorgetattempt')); } return attempt; @@ -143,17 +143,17 @@ export class AddonModQuizAttemptPage implements OnInit { * @return Promise resolved when done. */ protected async fetchAccessInfo(): Promise { - const accessInfo = await AddonModQuiz.instance.getQuizAccessInformation(this.quiz!.id, { cmId: this.cmId }); + const accessInfo = await AddonModQuiz.getQuizAccessInformation(this.quiz!.id, { cmId: this.cmId }); if (!accessInfo.canreviewmyattempts) { return accessInfo; } // Check if the user can review the attempt. - await CoreUtils.instance.ignoreErrors(AddonModQuiz.instance.invalidateAttemptReviewForPage(this.attemptId, -1)); + await CoreUtils.ignoreErrors(AddonModQuiz.invalidateAttemptReviewForPage(this.attemptId, -1)); try { - await AddonModQuiz.instance.getAttemptReview(this.attemptId, { page: -1, cmId: this.quiz!.coursemodule }); + await AddonModQuiz.getAttemptReview(this.attemptId, { page: -1, cmId: this.quiz!.coursemodule }); } catch { // Error getting the review, assume the user cannot review the attempt. accessInfo.canreviewmyattempts = false; @@ -170,20 +170,20 @@ export class AddonModQuizAttemptPage implements OnInit { protected async refreshData(): Promise { const promises: Promise[] = []; - promises.push(AddonModQuiz.instance.invalidateQuizData(this.courseId)); - promises.push(AddonModQuiz.instance.invalidateAttemptReview(this.attemptId)); + promises.push(AddonModQuiz.invalidateQuizData(this.courseId)); + promises.push(AddonModQuiz.invalidateAttemptReview(this.attemptId)); if (this.quiz) { - promises.push(AddonModQuiz.instance.invalidateUserAttemptsForUser(this.quiz.id)); - promises.push(AddonModQuiz.instance.invalidateQuizAccessInformation(this.quiz.id)); - promises.push(AddonModQuiz.instance.invalidateCombinedReviewOptionsForUser(this.quiz.id)); + promises.push(AddonModQuiz.invalidateUserAttemptsForUser(this.quiz.id)); + promises.push(AddonModQuiz.invalidateQuizAccessInformation(this.quiz.id)); + promises.push(AddonModQuiz.invalidateCombinedReviewOptionsForUser(this.quiz.id)); if (this.attempt && typeof this.feedback != 'undefined') { - promises.push(AddonModQuiz.instance.invalidateFeedback(this.quiz.id)); + promises.push(AddonModQuiz.invalidateFeedback(this.quiz.id)); } } - await CoreUtils.instance.ignoreErrors(Promise.all(promises)); + await CoreUtils.ignoreErrors(Promise.all(promises)); await this.fetchQuizData(); } @@ -194,7 +194,7 @@ export class AddonModQuizAttemptPage implements OnInit { * @return Promise resolved when done. */ async reviewAttempt(): Promise { - CoreNavigator.instance.navigate(`../../review/${this.attempt!.id}`); + CoreNavigator.navigate(`../../review/${this.attempt!.id}`); } } diff --git a/src/addons/mod/quiz/pages/index/index.ts b/src/addons/mod/quiz/pages/index/index.ts index 7bfccfd4b..6ecbdb4f5 100644 --- a/src/addons/mod/quiz/pages/index/index.ts +++ b/src/addons/mod/quiz/pages/index/index.ts @@ -38,8 +38,8 @@ export class AddonModQuizIndexPage implements OnInit { * Component being initialized. */ ngOnInit(): void { - this.module = CoreNavigator.instance.getRouteParam('module'); - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId'); + this.module = CoreNavigator.getRouteParam('module'); + this.courseId = CoreNavigator.getRouteNumberParam('courseId'); this.title = this.module?.name; } diff --git a/src/addons/mod/quiz/pages/player/player.ts b/src/addons/mod/quiz/pages/player/player.ts index 3eb0a3d82..fc5029f7c 100644 --- a/src/addons/mod/quiz/pages/player/player.ts +++ b/src/addons/mod/quiz/pages/player/player.ts @@ -104,9 +104,9 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { * Component being initialized. */ ngOnInit(): void { - this.cmId = CoreNavigator.instance.getRouteNumberParam('cmId')!; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.moduleUrl = CoreNavigator.instance.getRouteParam('moduleUrl'); + this.cmId = CoreNavigator.getRouteNumberParam('cmId')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.moduleUrl = CoreNavigator.getRouteParam('moduleUrl'); // Create the auto save instance. this.autoSave = new AddonModQuizAutoSave( @@ -135,7 +135,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { if (this.quiz) { // Unblock the quiz so it can be synced. - CoreSync.instance.unblockOperation(AddonModQuizProvider.COMPONENT, this.quiz.id); + CoreSync.unblockOperation(AddonModQuizProvider.COMPONENT, this.quiz.id); } } @@ -150,7 +150,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { } // Save answers. - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { await this.processAttempt(false, false); @@ -158,9 +158,9 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { // Save attempt failed. Show confirmation. modal.dismiss(); - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('addon.mod_quiz.confirmleavequizonerror')); + await CoreDomUtils.showConfirm(Translate.instant('addon.mod_quiz.confirmleavequizonerror')); - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); } finally { modal.dismiss(); } @@ -171,7 +171,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { */ async ionViewWillLeave(): Promise { // Close any modal if present. - const modal = await ModalController.instance.getTop(); + const modal = await ModalController.getTop(); modal?.dismiss(); } @@ -193,9 +193,9 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { try { // Confirm that the user really wants to do it. - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.areyousure')); + await CoreDomUtils.showConfirm(Translate.instant('core.areyousure')); - modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + modal = await CoreDomUtils.showModalLoading('core.sending', true); // Get the answers. const answers = await this.prepareAnswers(); @@ -204,7 +204,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { answers[button.name] = button.value; // Behaviour checks are always in online. - await AddonModQuiz.instance.processAttempt(this.quiz!, this.attempt!, answers, this.preflightData); + await AddonModQuiz.processAttempt(this.quiz!, this.attempt!, answers, this.preflightData); this.reloadNavigation = true; // Data sent to server, navigation should be reloaded. @@ -225,7 +225,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { } } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error performing action.'); + CoreDomUtils.showErrorModalDefault(error, 'Error performing action.'); } finally { modal?.dismiss(); } @@ -265,14 +265,14 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { // First try to save the attempt data. We only save it if we're not seeing the summary. if (!this.showSummary) { - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { await this.processAttempt(false, false); modal.dismiss(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_quiz.errorsaveattempt', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_quiz.errorsaveattempt', true); modal.dismiss(); return; @@ -299,7 +299,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { this.autoSave.startCheckChangesProcess(this.quiz!, this.attempt, this.preflightData, this.offline); } - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquestions', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquestions', true); } finally { this.loaded = true; @@ -319,37 +319,37 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { */ protected async fetchData(): Promise { try { - this.quiz = await AddonModQuiz.instance.getQuiz(this.courseId, this.cmId); + this.quiz = await AddonModQuiz.getQuiz(this.courseId, this.cmId); // Block the quiz so it cannot be synced. - CoreSync.instance.blockOperation(AddonModQuizProvider.COMPONENT, this.quiz.id); + CoreSync.blockOperation(AddonModQuizProvider.COMPONENT, this.quiz.id); // Wait for any ongoing sync to finish. We won't sync a quiz while it's being played. - await AddonModQuizSync.instance.waitForSync(this.quiz.id); + await AddonModQuizSync.waitForSync(this.quiz.id); - this.isSequential = AddonModQuiz.instance.isNavigationSequential(this.quiz); + this.isSequential = AddonModQuiz.isNavigationSequential(this.quiz); - if (AddonModQuiz.instance.isQuizOffline(this.quiz)) { + if (AddonModQuiz.isQuizOffline(this.quiz)) { // Quiz supports offline. this.offline = true; } else { // Quiz doesn't support offline right now, but maybe it did and then the setting was changed. // If we have an unfinished offline attempt then we'll use offline mode. - this.offline = await AddonModQuiz.instance.isLastAttemptOfflineUnfinished(this.quiz); + this.offline = await AddonModQuiz.isLastAttemptOfflineUnfinished(this.quiz); } if (this.quiz!.timelimit && this.quiz!.timelimit > 0) { - this.readableTimeLimit = CoreTimeUtils.instance.formatTime(this.quiz.timelimit); + this.readableTimeLimit = CoreTimeUtils.formatTime(this.quiz.timelimit); } // Get access information for the quiz. - this.quizAccessInfo = await AddonModQuiz.instance.getQuizAccessInformation(this.quiz.id, { + this.quizAccessInfo = await AddonModQuiz.getQuizAccessInformation(this.quiz.id, { cmId: this.quiz.coursemodule, readingStrategy: this.offline ? CoreSitesReadingStrategy.PreferCache : CoreSitesReadingStrategy.OnlyNetwork, }); // Get user attempts to determine last attempt. - const attempts = await AddonModQuiz.instance.getUserAttempts(this.quiz.id, { + const attempts = await AddonModQuiz.getUserAttempts(this.quiz.id, { cmId: this.quiz.coursemodule, readingStrategy: this.offline ? CoreSitesReadingStrategy.PreferCache : CoreSitesReadingStrategy.OnlyNetwork, }); @@ -362,7 +362,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { } // Get the last attempt. If it's finished, start a new one. - this.lastAttempt = await AddonModQuizHelper.instance.setAttemptCalculatedData( + this.lastAttempt = await AddonModQuizHelper.setAttemptCalculatedData( this.quiz, attempts[attempts.length - 1], false, @@ -370,9 +370,9 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { true, ); - this.newAttempt = AddonModQuiz.instance.isAttemptFinished(this.lastAttempt.state); + this.newAttempt = AddonModQuiz.isAttemptFinished(this.lastAttempt.state); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquiz', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquiz', true); } } @@ -389,10 +389,10 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { try { // Show confirm if the user clicked the finish button and the quiz is in progress. if (!timeUp && this.attempt!.state == AddonModQuizProvider.ATTEMPT_IN_PROGRESS) { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('addon.mod_quiz.confirmclose')); + await CoreDomUtils.showConfirm(Translate.instant('addon.mod_quiz.confirmclose')); } - modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + modal = await CoreDomUtils.showModalLoading('core.sending', true); await this.processAttempt(userFinish, timeUp); @@ -401,15 +401,15 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { quizId: this.quiz!.id, attemptId: this.attempt!.id, synced: !this.offline, - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); CoreEvents.trigger(CoreEvents.ACTIVITY_DATA_SENT, { module: 'quiz' }); // Leave the player. this.forceLeave = true; - CoreNavigator.instance.back(); + CoreNavigator.back(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_quiz.errorsaveattempt', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_quiz.errorsaveattempt', true); } finally { modal?.dismiss(); } @@ -422,7 +422,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { */ protected async fixSequenceChecks(): Promise { // Get current page data again to get the latest sequencechecks. - const data = await AddonModQuiz.instance.getAttemptData(this.attempt!.id, this.attempt!.currentpage!, this.preflightData, { + const data = await AddonModQuiz.getAttemptData(this.attempt!.id, this.attempt!.currentpage!, this.preflightData, { cmId: this.quiz!.coursemodule, readingStrategy: this.offline ? CoreSitesReadingStrategy.PreferCache : CoreSitesReadingStrategy.OnlyNetwork, }); @@ -430,7 +430,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { const newSequenceChecks: Record = {}; data.questions.forEach((question) => { - const sequenceCheck = CoreQuestionHelper.instance.getQuestionSequenceCheckFromHtml(question.html); + const sequenceCheck = CoreQuestionHelper.getQuestionSequenceCheckFromHtml(question.html); if (sequenceCheck) { newSequenceChecks[question.slot] = sequenceCheck; } @@ -448,7 +448,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { * @return Object with the answers. */ protected getAnswers(): CoreQuestionsAnswers { - return CoreQuestionHelper.instance.getAnswersFromForm(document.forms['addon-mod_quiz-player-form']); + return CoreQuestionHelper.getAnswersFromForm(document.forms['addon-mod_quiz-player-form']); } /** @@ -460,7 +460,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { } // Quiz has an end time. Check if time left should be shown. - const shouldShowTime = AddonModQuiz.instance.shouldShowTimeLeft( + const shouldShowTime = AddonModQuiz.shouldShowTimeLeft( this.quizAccessInfo!.activerulenames, this.attempt!, this.attemptAccessInfo.endtime, @@ -480,7 +480,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ protected async loadPage(page: number): Promise { - const data = await AddonModQuiz.instance.getAttemptData(this.attempt!.id, page, this.preflightData, { + const data = await AddonModQuiz.getAttemptData(this.attempt!.id, page, this.preflightData, { cmId: this.quiz!.coursemodule, readingStrategy: this.offline ? CoreSitesReadingStrategy.PreferCache : CoreSitesReadingStrategy.OnlyNetwork, }); @@ -496,20 +496,20 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { this.questions.forEach((question) => { // Get the readable mark for each question. - question.readableMark = AddonModQuizHelper.instance.getQuestionMarkFromHtml(question.html); + question.readableMark = AddonModQuizHelper.getQuestionMarkFromHtml(question.html); // Extract the question info box. - CoreQuestionHelper.instance.extractQuestionInfoBox(question, '.info'); + CoreQuestionHelper.extractQuestionInfoBox(question, '.info'); // Check if the question is blocked. If it is, treat it as a description question. - if (AddonModQuiz.instance.isQuestionBlocked(question)) { + if (AddonModQuiz.isQuestionBlocked(question)) { question.type = 'description'; } }); // Mark the page as viewed. - CoreUtils.instance.ignoreErrors( - AddonModQuiz.instance.logViewAttempt(this.attempt.id, page, this.preflightData, this.offline, this.quiz), + CoreUtils.ignoreErrors( + AddonModQuiz.logViewAttempt(this.attempt.id, page, this.preflightData, this.offline, this.quiz), ); // Start looking for changes. @@ -524,7 +524,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { protected async loadSummary(): Promise { this.summaryQuestions = []; - this.summaryQuestions = await AddonModQuiz.instance.getAttemptSummary(this.attempt!.id, this.preflightData, { + this.summaryQuestions = await AddonModQuiz.getAttemptSummary(this.attempt!.id, this.preflightData, { cmId: this.quiz!.coursemodule, loadLocal: this.offline, readingStrategy: this.offline ? CoreSitesReadingStrategy.PreferCache : CoreSitesReadingStrategy.OnlyNetwork, @@ -532,13 +532,13 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { this.showSummary = true; this.canReturn = this.attempt!.state == AddonModQuizProvider.ATTEMPT_IN_PROGRESS && !this.attempt!.finishedOffline; - this.preventSubmitMessages = AddonModQuiz.instance.getPreventSubmitMessages(this.summaryQuestions); + this.preventSubmitMessages = AddonModQuiz.getPreventSubmitMessages(this.summaryQuestions); - this.dueDateWarning = AddonModQuiz.instance.getAttemptDueDateWarning(this.quiz!, this.attempt!); + this.dueDateWarning = AddonModQuiz.getAttemptDueDateWarning(this.quiz!, this.attempt!); // Log summary as viewed. - CoreUtils.instance.ignoreErrors( - AddonModQuiz.instance.logViewAttemptSummary(this.attempt!.id, this.preflightData, this.quiz!.id, this.quiz!.name), + CoreUtils.ignoreErrors( + AddonModQuiz.logViewAttemptSummary(this.attempt!.id, this.preflightData, this.quiz!.id, this.quiz!.name), ); } @@ -549,14 +549,14 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { */ protected async loadNavigation(): Promise { // We use the attempt summary to build the navigation because it contains all the questions. - this.navigation = await AddonModQuiz.instance.getAttemptSummary(this.attempt!.id, this.preflightData, { + this.navigation = await AddonModQuiz.getAttemptSummary(this.attempt!.id, this.preflightData, { cmId: this.quiz!.coursemodule, loadLocal: this.offline, readingStrategy: this.offline ? CoreSitesReadingStrategy.PreferCache : CoreSitesReadingStrategy.OnlyNetwork, }); this.navigation.forEach((question) => { - question.stateClass = CoreQuestionHelper.instance.getQuestionStateClass(question.state || ''); + question.stateClass = CoreQuestionHelper.getQuestionStateClass(question.state || ''); }); } @@ -569,16 +569,16 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { if (this.reloadNavigation) { // Some data has changed, reload the navigation. - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); - await CoreUtils.instance.ignoreErrors(this.loadNavigation()); + await CoreUtils.ignoreErrors(this.loadNavigation()); modal.dismiss(); this.reloadNavigation = false; } // Create the navigation modal. - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: AddonModQuizNavigationModalComponent, componentProps: { navigation: this.navigation, @@ -608,7 +608,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { * @return Promise resolved with the answers. */ protected prepareAnswers(): Promise { - return CoreQuestionHelper.instance.prepareAnswers( + return CoreQuestionHelper.prepareAnswers( this.questions, this.getAnswers(), this.offline, @@ -635,7 +635,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { try { // Send the answers. - await AddonModQuiz.instance.processAttempt( + await AddonModQuiz.processAttempt( this.quiz!, this.attempt!, answers, @@ -670,10 +670,10 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { this.autoSave.hideAutoSaveError(); if (this.formElement) { - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, !this.offline, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, !this.offline, CoreSites.getCurrentSiteId()); } - return CoreQuestionHelper.instance.clearTmpData(this.questions, this.component, this.quiz!.coursemodule); + return CoreQuestionHelper.clearTmpData(this.questions, this.component, this.quiz!.coursemodule); } /** @@ -682,7 +682,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { * @param slot Slot of the question to scroll to. */ protected scrollToQuestion(slot: number): void { - CoreDomUtils.instance.scrollToElementBySelector( + CoreDomUtils.scrollToElementBySelector( this.elementRef.nativeElement, this.content, '#addon-mod_quiz-question-' + slot, @@ -729,7 +729,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { let attempt = this.newAttempt ? undefined : this.lastAttempt; // Get the preflight data and start attempt if needed. - attempt = await AddonModQuizHelper.instance.getAndCheckPreflightData( + attempt = await AddonModQuizHelper.getAndCheckPreflightData( this.quiz!, this.quizAccessInfo!, this.preflightData, @@ -740,7 +740,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { ); // Re-fetch attempt access information with the right attempt (might have changed because a new attempt was created). - this.attemptAccessInfo = await AddonModQuiz.instance.getAttemptAccessInformation(this.quiz!.id, attempt.id, { + this.attemptAccessInfo = await AddonModQuiz.getAttemptAccessInformation(this.quiz!.id, attempt.id, { cmId: this.quiz!.coursemodule, readingStrategy: this.offline ? CoreSitesReadingStrategy.PreferCache : CoreSitesReadingStrategy.OnlyNetwork, }); @@ -759,7 +759,7 @@ export class AddonModQuizPlayerPage implements OnInit, OnDestroy { await this.loadSummary(); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquestions', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquestions', true); } } diff --git a/src/addons/mod/quiz/pages/review/review.ts b/src/addons/mod/quiz/pages/review/review.ts index 49ec63a6d..0b00bf887 100644 --- a/src/addons/mod/quiz/pages/review/review.ts +++ b/src/addons/mod/quiz/pages/review/review.ts @@ -82,17 +82,17 @@ export class AddonModQuizReviewPage implements OnInit { * Component being initialized. */ async ngOnInit(): Promise { - this.cmId = CoreNavigator.instance.getRouteNumberParam('cmId')!; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId')!; - this.attemptId = CoreNavigator.instance.getRouteNumberParam('attemptId')!; - this.currentPage = CoreNavigator.instance.getRouteNumberParam('page') || -1; + this.cmId = CoreNavigator.getRouteNumberParam('cmId')!; + this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; + this.attemptId = CoreNavigator.getRouteNumberParam('attemptId')!; + this.currentPage = CoreNavigator.getRouteNumberParam('page') || -1; this.showAll = this.currentPage == -1; try { await this.fetchData(); - CoreUtils.instance.ignoreErrors( - AddonModQuiz.instance.logViewAttemptReview(this.attemptId, this.quiz!.id, this.quiz!.name), + CoreUtils.ignoreErrors( + AddonModQuiz.logViewAttemptReview(this.attemptId, this.quiz!.id, this.quiz!.name), ); } finally { this.loaded = true; @@ -123,7 +123,7 @@ export class AddonModQuizReviewPage implements OnInit { try { await this.loadPage(page); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquestions', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquestions', true); } finally { this.loaded = true; @@ -143,9 +143,9 @@ export class AddonModQuizReviewPage implements OnInit { */ protected async fetchData(): Promise { try { - this.quiz = await AddonModQuiz.instance.getQuiz(this.courseId, this.cmId); + this.quiz = await AddonModQuiz.getQuiz(this.courseId, this.cmId); - this.options = await AddonModQuiz.instance.getCombinedReviewOptions(this.quiz.id, { cmId: this.cmId }); + this.options = await AddonModQuiz.getCombinedReviewOptions(this.quiz.id, { cmId: this.cmId }); // Load the navigation data. await this.loadNavigation(); @@ -153,7 +153,7 @@ export class AddonModQuizReviewPage implements OnInit { // Load questions. await this.loadPage(this.currentPage); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquiz', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.mod_quiz.errorgetquiz', true); } } @@ -164,7 +164,7 @@ export class AddonModQuizReviewPage implements OnInit { * @return Promise resolved when done. */ protected async loadPage(page: number): Promise { - const data = await AddonModQuiz.instance.getAttemptReview(this.attemptId, { page, cmId: this.quiz!.coursemodule }); + const data = await AddonModQuiz.getAttemptReview(this.attemptId, { page, cmId: this.quiz!.coursemodule }); this.attempt = data.attempt; this.attempt.currentpage = page; @@ -179,10 +179,10 @@ export class AddonModQuizReviewPage implements OnInit { this.questions.forEach((question) => { // Get the readable mark for each question. - question.readableMark = AddonModQuizHelper.instance.getQuestionMarkFromHtml(question.html); + question.readableMark = AddonModQuizHelper.getQuestionMarkFromHtml(question.html); // Extract the question info box. - CoreQuestionHelper.instance.extractQuestionInfoBox(question, '.info'); + CoreQuestionHelper.extractQuestionInfoBox(question, '.info'); }); } @@ -193,12 +193,12 @@ export class AddonModQuizReviewPage implements OnInit { */ protected async loadNavigation(): Promise { // Get all questions in single page to retrieve all the questions. - const data = await AddonModQuiz.instance.getAttemptReview(this.attemptId, { page: -1, cmId: this.quiz!.coursemodule }); + const data = await AddonModQuiz.getAttemptReview(this.attemptId, { page: -1, cmId: this.quiz!.coursemodule }); this.navigation = data.questions; this.navigation.forEach((question) => { - question.stateClass = CoreQuestionHelper.instance.getQuestionStateClass(question.state || ''); + question.stateClass = CoreQuestionHelper.getQuestionStateClass(question.state || ''); }); const lastQuestion = data.questions[data.questions.length - 1]; @@ -213,13 +213,13 @@ export class AddonModQuizReviewPage implements OnInit { async refreshData(refresher: IonRefresher): Promise { const promises: Promise[] = []; - promises.push(AddonModQuiz.instance.invalidateQuizData(this.courseId)); - promises.push(AddonModQuiz.instance.invalidateAttemptReview(this.attemptId)); + promises.push(AddonModQuiz.invalidateQuizData(this.courseId)); + promises.push(AddonModQuiz.invalidateAttemptReview(this.attemptId)); if (this.quiz) { - promises.push(AddonModQuiz.instance.invalidateCombinedReviewOptionsForUser(this.quiz.id)); + promises.push(AddonModQuiz.invalidateCombinedReviewOptionsForUser(this.quiz.id)); } - await CoreUtils.instance.ignoreErrors(Promise.all(promises)); + await CoreUtils.ignoreErrors(Promise.all(promises)); try { await this.fetchData(); @@ -234,7 +234,7 @@ export class AddonModQuizReviewPage implements OnInit { * @param slot Slot of the question to scroll to. */ protected scrollToQuestion(slot: number): void { - CoreDomUtils.instance.scrollToElementBySelector( + CoreDomUtils.scrollToElementBySelector( this.elementRef.nativeElement, this.content, `#addon-mod_quiz-question-${slot}`, @@ -251,7 +251,7 @@ export class AddonModQuizReviewPage implements OnInit { return; } - this.readableState = AddonModQuiz.instance.getAttemptReadableStateName(this.attempt!.state || ''); + this.readableState = AddonModQuiz.getAttemptReadableStateName(this.attempt!.state || ''); if (this.attempt.state != AddonModQuizProvider.ATTEMPT_FINISHED) { return; @@ -263,11 +263,11 @@ export class AddonModQuizReviewPage implements OnInit { const timeTaken = (this.attempt.timefinish || 0) - (this.attempt.timestart || 0); if (timeTaken > 0) { // Format time taken. - this.timeTaken = CoreTimeUtils.instance.formatTime(timeTaken); + this.timeTaken = CoreTimeUtils.formatTime(timeTaken); // Calculate overdue time. if (this.quiz.timelimit && timeTaken > this.quiz.timelimit + 60) { - this.overTime = CoreTimeUtils.instance.formatTime(timeTaken - this.quiz.timelimit); + this.overTime = CoreTimeUtils.formatTime(timeTaken - this.quiz.timelimit); } } else { this.timeTaken = undefined; @@ -275,33 +275,33 @@ export class AddonModQuizReviewPage implements OnInit { // Treat grade. if (this.options!.someoptions.marks >= AddonModQuizProvider.QUESTION_OPTIONS_MARK_AND_MAX && - AddonModQuiz.instance.quizHasGrades(this.quiz)) { + AddonModQuiz.quizHasGrades(this.quiz)) { if (data.grade === null || typeof data.grade == 'undefined') { - this.readableGrade = AddonModQuiz.instance.formatGrade(data.grade, this.quiz.decimalpoints); + this.readableGrade = AddonModQuiz.formatGrade(data.grade, this.quiz.decimalpoints); } else { // Show raw marks only if they are different from the grade (like on the entry page). if (this.quiz.grade != this.quiz.sumgrades) { - this.readableMark = Translate.instance.instant('addon.mod_quiz.outofshort', { $a: { - grade: AddonModQuiz.instance.formatGrade(this.attempt.sumgrades, this.quiz.decimalpoints), - maxgrade: AddonModQuiz.instance.formatGrade(this.quiz.sumgrades, this.quiz.decimalpoints), + this.readableMark = Translate.instant('addon.mod_quiz.outofshort', { $a: { + grade: AddonModQuiz.formatGrade(this.attempt.sumgrades, this.quiz.decimalpoints), + maxgrade: AddonModQuiz.formatGrade(this.quiz.sumgrades, this.quiz.decimalpoints), } }); } // Now the scaled grade. const gradeObject: Record = { - grade: AddonModQuiz.instance.formatGrade(Number(data.grade), this.quiz.decimalpoints), - maxgrade: AddonModQuiz.instance.formatGrade(this.quiz.grade, this.quiz.decimalpoints), + grade: AddonModQuiz.formatGrade(Number(data.grade), this.quiz.decimalpoints), + maxgrade: AddonModQuiz.formatGrade(this.quiz.grade, this.quiz.decimalpoints), }; if (this.quiz.grade != 100) { - gradeObject.percent = CoreTextUtils.instance.roundToDecimals( + gradeObject.percent = CoreTextUtils.roundToDecimals( this.attempt.sumgrades! * 100 / this.quiz.sumgrades!, 0, ); - this.readableGrade = Translate.instance.instant('addon.mod_quiz.outofpercent', { $a: gradeObject }); + this.readableGrade = Translate.instant('addon.mod_quiz.outofpercent', { $a: gradeObject }); } else { - this.readableGrade = Translate.instance.instant('addon.mod_quiz.outof', { $a: gradeObject }); + this.readableGrade = Translate.instant('addon.mod_quiz.outof', { $a: gradeObject }); } } } @@ -309,7 +309,7 @@ export class AddonModQuizReviewPage implements OnInit { // Treat additional data. this.additionalData.forEach((data) => { // Remove help links from additional data. - data.content = CoreDomUtils.instance.removeElementFromHtml(data.content, '.helptooltip'); + data.content = CoreDomUtils.removeElementFromHtml(data.content, '.helptooltip'); }); } @@ -325,7 +325,7 @@ export class AddonModQuizReviewPage implements OnInit { async openNavigation(): Promise { // Create the navigation modal. - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: AddonModQuizNavigationModalComponent, componentProps: { navigation: this.navigation, diff --git a/src/addons/mod/quiz/quiz.module.ts b/src/addons/mod/quiz/quiz.module.ts index c39a6deb3..b1e7f6401 100644 --- a/src/addons/mod/quiz/quiz.module.ts +++ b/src/addons/mod/quiz/quiz.module.ts @@ -58,14 +58,14 @@ const routes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreCourseModuleDelegate.instance.registerHandler(AddonModQuizModuleHandler.instance); - CoreCourseModulePrefetchDelegate.instance.registerHandler(AddonModQuizPrefetchHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModQuizGradeLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModQuizIndexLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModQuizListLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(AddonModQuizReviewLinkHandler.instance); - CorePushNotificationsDelegate.instance.registerClickHandler(AddonModQuizPushClickHandler.instance); - CoreCronDelegate.instance.register(AddonModQuizSyncCronHandler.instance); + CoreCourseModuleDelegate.registerHandler(AddonModQuizModuleHandler.instance); + CoreCourseModulePrefetchDelegate.registerHandler(AddonModQuizPrefetchHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModQuizGradeLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModQuizIndexLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModQuizListLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(AddonModQuizReviewLinkHandler.instance); + CorePushNotificationsDelegate.registerClickHandler(AddonModQuizPushClickHandler.instance); + CoreCronDelegate.register(AddonModQuizSyncCronHandler.instance); }, }, ], diff --git a/src/addons/mod/quiz/services/access-rules-delegate.ts b/src/addons/mod/quiz/services/access-rules-delegate.ts index 3f6142853..0bb48b4e5 100644 --- a/src/addons/mod/quiz/services/access-rules-delegate.ts +++ b/src/addons/mod/quiz/services/access-rules-delegate.ts @@ -162,7 +162,7 @@ export class AddonModQuizAccessRuleDelegateService extends CoreDelegate { rules = rules || []; - await CoreUtils.instance.ignoreErrors(CoreUtils.instance.allPromises(rules.map(async (rule) => { + await CoreUtils.ignoreErrors(CoreUtils.allPromises(rules.map(async (rule) => { await this.executeFunctionOnEnabled(rule, 'getFixedPreflightData', [quiz, preflightData, attempt, prefetch, siteId]); }))); } @@ -207,7 +207,7 @@ export class AddonModQuizAccessRuleDelegateService extends CoreDelegate { + await CoreUtils.ignoreErrors(CoreUtils.allPromises(rules.map(async (rule) => { const ruleRequired = await this.isPreflightCheckRequiredForRule(rule, quiz, attempt, prefetch, siteId); isRequired = isRequired || ruleRequired; @@ -259,7 +259,7 @@ export class AddonModQuizAccessRuleDelegateService extends CoreDelegate { rules = rules || []; - await CoreUtils.instance.ignoreErrors(CoreUtils.instance.allPromises(rules.map(async (rule) => { + await CoreUtils.ignoreErrors(CoreUtils.allPromises(rules.map(async (rule) => { await this.executeFunctionOnEnabled( rule, 'notifyPreflightCheckPassed', @@ -289,7 +289,7 @@ export class AddonModQuizAccessRuleDelegateService extends CoreDelegate { rules = rules || []; - await CoreUtils.instance.ignoreErrors(CoreUtils.instance.allPromises(rules.map(async (rule) => { + await CoreUtils.ignoreErrors(CoreUtils.allPromises(rules.map(async (rule) => { await this.executeFunctionOnEnabled( rule, 'notifyPreflightCheckFailed', @@ -323,4 +323,4 @@ export class AddonModQuizAccessRuleDelegateService extends CoreDelegate { try { - const quiz = await AddonModQuiz.instance.getQuiz(courseId, module.id); + const quiz = await AddonModQuiz.getQuiz(courseId, module.id); const files = this.getIntroFilesFromInstance(module, quiz); - const attempts = await AddonModQuiz.instance.getUserAttempts(quiz.id, { + const attempts = await AddonModQuiz.getUserAttempts(quiz.id, { cmId: module.id, readingStrategy: CoreSitesReadingStrategy.OnlyNetwork, }); @@ -110,21 +110,21 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet attempts: AddonModQuizAttemptWSData[], siteId?: string, ): Promise { - const getInlineFiles = CoreSites.instance.getCurrentSite()?.isVersionGreaterEqualThan('3.2'); + const getInlineFiles = CoreSites.getCurrentSite()?.isVersionGreaterEqualThan('3.2'); let files: CoreWSExternalFile[] = []; await Promise.all(attempts.map(async (attempt) => { - if (!AddonModQuiz.instance.isAttemptFinished(attempt.state)) { + if (!AddonModQuiz.isAttemptFinished(attempt.state)) { // Attempt not finished, no feedback files. return; } - const attemptGrade = AddonModQuiz.instance.rescaleGrade(attempt.sumgrades, quiz, false); + const attemptGrade = AddonModQuiz.rescaleGrade(attempt.sumgrades, quiz, false); if (typeof attemptGrade == 'undefined') { return; } - const feedback = await AddonModQuiz.instance.getFeedbackForGrade(quiz.id, Number(attemptGrade), { + const feedback = await AddonModQuiz.getFeedbackForGrade(quiz.id, Number(attemptGrade), { cmId: quiz.coursemodule, readingStrategy: CoreSitesReadingStrategy.OnlyNetwork, siteId, @@ -134,7 +134,7 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet files = files.concat(feedback.feedbackinlinefiles); } else if (feedback.feedbacktext && !getInlineFiles) { files = files.concat( - CoreFilepool.instance.extractDownloadableFilesFromHtmlAsFakeFileObjects(feedback.feedbacktext), + CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(feedback.feedbacktext), ); } })); @@ -165,7 +165,7 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet if (askPreflight) { // We can ask preflight, check if it's needed and get the data. - await AddonModQuizHelper.instance.getAndCheckPreflightData( + await AddonModQuizHelper.getAndCheckPreflightData( quiz, accessInfo, preflightData, @@ -179,11 +179,11 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet // Get some fixed preflight data from access rules (data that doesn't require user interaction). const rules = accessInfo?.activerulenames || []; - await AddonModQuizAccessRuleDelegate.instance.getFixedPreflightData(rules, quiz, preflightData, attempt, true, siteId); + await AddonModQuizAccessRuleDelegate.getFixedPreflightData(rules, quiz, preflightData, attempt, true, siteId); if (!attempt) { // We need to create a new attempt. - await AddonModQuiz.instance.startAttempt(quiz.id, preflightData, false, siteId); + await AddonModQuiz.startAttempt(quiz.id, preflightData, false, siteId); } } @@ -198,7 +198,7 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet * @return Promise resolved when the data is invalidated. */ invalidateContent(moduleId: number, courseId: number): Promise { - return AddonModQuiz.instance.invalidateContent(moduleId, courseId); + return AddonModQuiz.invalidateContent(moduleId, courseId); } /** @@ -211,8 +211,8 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet async invalidateModule(module: CoreCourseAnyModuleData, courseId: number): Promise { // Invalidate the calls required to check if a quiz is downloadable. await Promise.all([ - AddonModQuiz.instance.invalidateQuizData(courseId), - AddonModQuiz.instance.invalidateUserAttemptsForUser(module.instance!), + AddonModQuiz.invalidateQuizData(courseId), + AddonModQuiz.invalidateUserAttemptsForUser(module.instance!), ]); } @@ -224,26 +224,26 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet * @return Whether the module can be downloaded. The promise should never be rejected. */ async isDownloadable(module: CoreCourseAnyModuleData, courseId: number): Promise { - if (CoreSites.instance.getCurrentSite()?.isOfflineDisabled()) { + if (CoreSites.getCurrentSite()?.isOfflineDisabled()) { // Don't allow downloading the quiz if offline is disabled to prevent wasting a lot of data when opening it. return false; } - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); - const quiz = await AddonModQuiz.instance.getQuiz(courseId, module.id, { siteId }); + const quiz = await AddonModQuiz.getQuiz(courseId, module.id, { siteId }); if (quiz.allowofflineattempts !== 1 || quiz.hasquestions === 0) { return false; } // Not downloadable if we reached max attempts or the quiz has an unfinished attempt. - const attempts = await AddonModQuiz.instance.getUserAttempts(quiz.id, { + const attempts = await AddonModQuiz.getUserAttempts(quiz.id, { cmId: module.id, siteId, }); - const isLastFinished = !attempts.length || AddonModQuiz.instance.isAttemptFinished(attempts[attempts.length - 1].state); + const isLastFinished = !attempts.length || AddonModQuiz.isAttemptFinished(attempts[attempts.length - 1].state); return quiz.attempts === 0 || quiz.attempts! > attempts.length || !isLastFinished; } @@ -282,7 +282,7 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet return; } - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); return this.prefetchPackage(module, courseId, this.prefetchQuiz.bind(this, module, courseId, single, siteId, canStart)); } @@ -314,18 +314,18 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet }; // Get quiz. - const quiz = await AddonModQuiz.instance.getQuiz(courseId, module.id, commonOptions); + const quiz = await AddonModQuiz.getQuiz(courseId, module.id, commonOptions); const introFiles = this.getIntroFilesFromInstance(module, quiz); // Prefetch some quiz data. // eslint-disable-next-line prefer-const let [quizAccessInfo, attempts, attemptAccessInfo] = await Promise.all([ - AddonModQuiz.instance.getQuizAccessInformation(quiz.id, modOptions), - AddonModQuiz.instance.getUserAttempts(quiz.id, modOptions), - AddonModQuiz.instance.getAttemptAccessInformation(quiz.id, 0, modOptions), - AddonModQuiz.instance.getQuizRequiredQtypes(quiz.id, modOptions), - CoreFilepool.instance.addFilesToQueue(siteId, introFiles, AddonModQuizProvider.COMPONENT, module.id), + AddonModQuiz.getQuizAccessInformation(quiz.id, modOptions), + AddonModQuiz.getUserAttempts(quiz.id, modOptions), + AddonModQuiz.getAttemptAccessInformation(quiz.id, 0, modOptions), + AddonModQuiz.getQuizRequiredQtypes(quiz.id, modOptions), + CoreFilepool.addFilesToQueue(siteId, introFiles, AddonModQuizProvider.COMPONENT, module.id), ]); // Check if we need to start a new attempt. @@ -334,10 +334,10 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet let startAttempt = false; if (canStart || attempt) { - if (canStart && (!attempt || AddonModQuiz.instance.isAttemptFinished(attempt.state))) { + if (canStart && (!attempt || AddonModQuiz.isAttemptFinished(attempt.state))) { // Check if the user can attempt the quiz. if (attemptAccessInfo.preventnewattemptreasons.length) { - throw new CoreError(CoreTextUtils.instance.buildMessage(attemptAccessInfo.preventnewattemptreasons)); + throw new CoreError(CoreTextUtils.buildMessage(attemptAccessInfo.preventnewattemptreasons)); } startAttempt = true; @@ -352,29 +352,29 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet if (startAttempt) { // Re-fetch user attempts since we created a new one. - promises.push(AddonModQuiz.instance.getUserAttempts(quiz.id, modOptions).then(async (atts) => { + promises.push(AddonModQuiz.getUserAttempts(quiz.id, modOptions).then(async (atts) => { attempts = atts; const attemptFiles = await this.getAttemptsFeedbackFiles(quiz, attempts, siteId); - return CoreFilepool.instance.addFilesToQueue(siteId, attemptFiles, AddonModQuizProvider.COMPONENT, module.id); + return CoreFilepool.addFilesToQueue(siteId, attemptFiles, AddonModQuizProvider.COMPONENT, module.id); })); // Update the download time to prevent detecting the new attempt as an update. - promises.push(CoreUtils.instance.ignoreErrors( - CoreFilepool.instance.updatePackageDownloadTime(siteId, AddonModQuizProvider.COMPONENT, module.id), + promises.push(CoreUtils.ignoreErrors( + CoreFilepool.updatePackageDownloadTime(siteId, AddonModQuizProvider.COMPONENT, module.id), )); } else { // Use the already fetched attempts. promises.push(this.getAttemptsFeedbackFiles(quiz, attempts, siteId).then((attemptFiles) => - CoreFilepool.instance.addFilesToQueue(siteId, attemptFiles, AddonModQuizProvider.COMPONENT, module.id))); + CoreFilepool.addFilesToQueue(siteId, attemptFiles, AddonModQuizProvider.COMPONENT, module.id))); } // Fetch attempt related data. - promises.push(AddonModQuiz.instance.getCombinedReviewOptions(quiz.id, modOptions)); - promises.push(AddonModQuiz.instance.getUserBestGrade(quiz.id, modOptions)); + promises.push(AddonModQuiz.getCombinedReviewOptions(quiz.id, modOptions)); + promises.push(AddonModQuiz.getUserBestGrade(quiz.id, modOptions)); promises.push(this.prefetchGradeAndFeedback(quiz, modOptions, siteId)); - promises.push(AddonModQuiz.instance.getAttemptAccessInformation(quiz.id, 0, modOptions)); // Last attempt. + promises.push(AddonModQuiz.getAttemptAccessInformation(quiz.id, 0, modOptions)); // Last attempt. await Promise.all(promises); @@ -389,10 +389,10 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet } // If there's nothing to send, mark the quiz as synchronized. - const hasData = await AddonModQuizSync.instance.hasDataToSync(quiz.id, siteId); + const hasData = await AddonModQuizSync.hasDataToSync(quiz.id, siteId); if (!hasData) { - AddonModQuizSync.instance.setSyncTime(quiz.id, siteId); + AddonModQuizSync.setSyncTime(quiz.id, siteId); } } @@ -411,8 +411,8 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet preflightData: Record, siteId?: string, ): Promise { - const pages = AddonModQuiz.instance.getPagesFromLayout(attempt.layout); - const isSequential = AddonModQuiz.instance.isNavigationSequential(quiz); + const pages = AddonModQuiz.getPagesFromLayout(attempt.layout); + const isSequential = AddonModQuiz.isNavigationSequential(quiz); let promises: Promise[] = []; const modOptions: CoreCourseCommonModWSOptions = { @@ -421,16 +421,16 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet siteId, }; - if (AddonModQuiz.instance.isAttemptFinished(attempt.state)) { + if (AddonModQuiz.isAttemptFinished(attempt.state)) { // Attempt is finished, get feedback and review data. - const attemptGrade = AddonModQuiz.instance.rescaleGrade(attempt.sumgrades, quiz, false); + const attemptGrade = AddonModQuiz.rescaleGrade(attempt.sumgrades, quiz, false); if (typeof attemptGrade != 'undefined') { - promises.push(AddonModQuiz.instance.getFeedbackForGrade(quiz.id, Number(attemptGrade), modOptions)); + promises.push(AddonModQuiz.getFeedbackForGrade(quiz.id, Number(attemptGrade), modOptions)); } // Get the review for each page. pages.forEach((page) => { - promises.push(CoreUtils.instance.ignoreErrors(AddonModQuiz.instance.getAttemptReview(attempt.id, { + promises.push(CoreUtils.ignoreErrors(AddonModQuiz.getAttemptReview(attempt.id, { page, ...modOptions, // Include all options. }))); @@ -441,8 +441,8 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet } else { // Attempt not finished, get data needed to continue the attempt. - promises.push(AddonModQuiz.instance.getAttemptAccessInformation(quiz.id, attempt.id, modOptions)); - promises.push(AddonModQuiz.instance.getAttemptSummary(attempt.id, preflightData, modOptions)); + promises.push(AddonModQuiz.getAttemptAccessInformation(quiz.id, attempt.id, modOptions)); + promises.push(AddonModQuiz.getAttemptSummary(attempt.id, preflightData, modOptions)); if (attempt.state == AddonModQuizProvider.ATTEMPT_IN_PROGRESS) { // Get data for each page. @@ -452,11 +452,11 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet return; } - const data = await AddonModQuiz.instance.getAttemptData(attempt.id, page, preflightData, modOptions); + const data = await AddonModQuiz.getAttemptData(attempt.id, page, preflightData, modOptions); // Download the files inside the questions. await Promise.all(data.questions.map(async (question) => { - await CoreQuestionHelper.instance.prefetchQuestionFiles( + await CoreQuestionHelper.prefetchQuestionFiles( question, this.component, quiz.coursemodule, @@ -488,7 +488,7 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet siteId?: string, ): Promise { // Get the review for all questions in same page. - const data = await CoreUtils.instance.ignoreErrors(AddonModQuiz.instance.getAttemptReview(attempt.id, { + const data = await CoreUtils.ignoreErrors(AddonModQuiz.getAttemptReview(attempt.id, { page: -1, ...modOptions, // Include all options. })); @@ -498,7 +498,7 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet } // Download the files inside the questions. await Promise.all(data.questions.map((question) => { - CoreQuestionHelper.instance.prefetchQuestionFiles( + CoreQuestionHelper.prefetchQuestionFiles( question, this.component, quiz.coursemodule, @@ -522,10 +522,10 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet siteId?: string, ): Promise { try { - const gradebookData = await AddonModQuiz.instance.getGradeFromGradebook(quiz.course, quiz.coursemodule, true, siteId); + const gradebookData = await AddonModQuiz.getGradeFromGradebook(quiz.course, quiz.coursemodule, true, siteId); if (gradebookData && 'graderaw' in gradebookData && gradebookData.graderaw !== undefined) { - await AddonModQuiz.instance.getFeedbackForGrade(quiz.id, gradebookData.graderaw, modOptions); + await AddonModQuiz.getFeedbackForGrade(quiz.id, gradebookData.graderaw, modOptions); } } catch { // Ignore errors. @@ -542,7 +542,7 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet * @return Promise resolved when done. */ async prefetchQuizAndLastAttempt(quiz: AddonModQuizQuizWSData, askPreflight?: boolean, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const modOptions = { cmId: quiz.coursemodule, @@ -552,13 +552,13 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet // Get quiz data. const [quizAccessInfo, attempts] = await Promise.all([ - AddonModQuiz.instance.getQuizAccessInformation(quiz.id, modOptions), - AddonModQuiz.instance.getUserAttempts(quiz.id, modOptions), - AddonModQuiz.instance.getQuizRequiredQtypes(quiz.id, modOptions), - AddonModQuiz.instance.getCombinedReviewOptions(quiz.id, modOptions), - AddonModQuiz.instance.getUserBestGrade(quiz.id, modOptions), + AddonModQuiz.getQuizAccessInformation(quiz.id, modOptions), + AddonModQuiz.getUserAttempts(quiz.id, modOptions), + AddonModQuiz.getQuizRequiredQtypes(quiz.id, modOptions), + AddonModQuiz.getCombinedReviewOptions(quiz.id, modOptions), + AddonModQuiz.getUserBestGrade(quiz.id, modOptions), this.prefetchGradeAndFeedback(quiz, modOptions, siteId), - AddonModQuiz.instance.getAttemptAccessInformation(quiz.id, 0, modOptions), // Last attempt. + AddonModQuiz.getAttemptAccessInformation(quiz.id, 0, modOptions), // Last attempt. ]); const lastAttempt = attempts[attempts.length - 1]; @@ -592,17 +592,17 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet quiz: AddonModQuizQuizWSData, options: AddonModQuizSetStatusAfterPrefetchOptions = {}, ): Promise { - options.siteId = options.siteId || CoreSites.instance.getCurrentSiteId(); + options.siteId = options.siteId || CoreSites.getCurrentSiteId(); let attempts = options.attempts; if (!attempts) { // Get the attempts. - attempts = await AddonModQuiz.instance.getUserAttempts(quiz.id, options); + attempts = await AddonModQuiz.getUserAttempts(quiz.id, options); } // Check the current status of the quiz. - const status = await CoreFilepool.instance.getPackageStatus(options.siteId, this.component, quiz.coursemodule); + const status = await CoreFilepool.getPackageStatus(options.siteId, this.component, quiz.coursemodule); if (status === CoreConstants.NOT_DOWNLOADED) { return; @@ -611,10 +611,10 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet // Quiz was downloaded, set the new status. // If no attempts or last is finished we'll mark it as not downloaded to show download icon. const lastAttempt = attempts[attempts.length - 1]; - const isLastFinished = !lastAttempt || AddonModQuiz.instance.isAttemptFinished(lastAttempt.state); + const isLastFinished = !lastAttempt || AddonModQuiz.isAttemptFinished(lastAttempt.state); const newStatus = isLastFinished ? CoreConstants.NOT_DOWNLOADED : CoreConstants.DOWNLOADED; - await CoreFilepool.instance.storePackageStatus(options.siteId, newStatus, this.component, quiz.coursemodule); + await CoreFilepool.storePackageStatus(options.siteId, newStatus, this.component, quiz.coursemodule); } /** @@ -626,10 +626,10 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet * @return Promise resolved when done. */ async sync(module: SyncedModule, courseId: number, siteId?: string): Promise { - const quiz = await AddonModQuiz.instance.getQuiz(courseId, module.id, { siteId }); + const quiz = await AddonModQuiz.getQuiz(courseId, module.id, { siteId }); try { - const result = await AddonModQuizSync.instance.syncQuiz(quiz, false, siteId); + const result = await AddonModQuizSync.syncQuiz(quiz, false, siteId); module.attemptFinished = result.attemptFinished || false; @@ -642,7 +642,7 @@ export class AddonModQuizPrefetchHandlerService extends CoreCourseActivityPrefet } -export class AddonModQuizPrefetchHandler extends makeSingleton(AddonModQuizPrefetchHandlerService) {} +export const AddonModQuizPrefetchHandler = makeSingleton(AddonModQuizPrefetchHandlerService); /** * Options to pass to setStatusAfterPrefetch. diff --git a/src/addons/mod/quiz/services/handlers/push-click.ts b/src/addons/mod/quiz/services/handlers/push-click.ts index b969577ef..b326cc699 100644 --- a/src/addons/mod/quiz/services/handlers/push-click.ts +++ b/src/addons/mod/quiz/services/handlers/push-click.ts @@ -42,7 +42,7 @@ export class AddonModQuizPushClickHandlerService implements CorePushNotification * @return Whether the notification click is handled by this handler */ async handles(notification: AddonModQuizPushNotificationData): Promise { - return CoreUtils.instance.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'mod_quiz' && + return CoreUtils.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'mod_quiz' && this.SUPPORTED_NAMES.indexOf(notification.name!) != -1; } @@ -53,13 +53,13 @@ export class AddonModQuizPushClickHandlerService implements CorePushNotification * @return Promise resolved when done. */ async handleClick(notification: AddonModQuizPushNotificationData): Promise { - const contextUrlParams = CoreUrlUtils.instance.extractUrlParams(notification.contexturl || ''); + const contextUrlParams = CoreUrlUtils.extractUrlParams(notification.contexturl || ''); const data = notification.customdata || {}; const courseId = Number(notification.courseid); if (notification.name == 'submission') { // A student made a submission, go to view the attempt. - return AddonModQuizHelper.instance.handleReviewLink( + return AddonModQuizHelper.handleReviewLink( Number(contextUrlParams.attempt), Number(contextUrlParams.page), courseId, @@ -71,14 +71,14 @@ export class AddonModQuizPushClickHandlerService implements CorePushNotification // Open the activity. const moduleId = Number(contextUrlParams.id); - await CoreUtils.instance.ignoreErrors(AddonModQuiz.instance.invalidateContent(moduleId, courseId, notification.site)); + await CoreUtils.ignoreErrors(AddonModQuiz.invalidateContent(moduleId, courseId, notification.site)); - return CoreCourseHelper.instance.navigateToModule(moduleId, notification.site, courseId); + return CoreCourseHelper.navigateToModule(moduleId, notification.site, courseId); } } -export class AddonModQuizPushClickHandler extends makeSingleton(AddonModQuizPushClickHandlerService) {} +export const AddonModQuizPushClickHandler = makeSingleton(AddonModQuizPushClickHandlerService); type AddonModQuizPushNotificationData = CorePushNotificationsNotificationBasicData & { contexturl?: string; diff --git a/src/addons/mod/quiz/services/handlers/review-link.ts b/src/addons/mod/quiz/services/handlers/review-link.ts index 7c9f40a63..413aea88b 100644 --- a/src/addons/mod/quiz/services/handlers/review-link.ts +++ b/src/addons/mod/quiz/services/handlers/review-link.ts @@ -56,11 +56,11 @@ export class AddonModQuizReviewLinkHandlerService extends CoreContentLinksHandle const page = parseInt(params.page, 10); const quizId = data!.instance ? Number(data!.instance) : undefined; - AddonModQuizHelper.instance.handleReviewLink(attemptId, page, courseId, quizId, siteId); + AddonModQuizHelper.handleReviewLink(attemptId, page, courseId, quizId, siteId); }, }]; } } -export class AddonModQuizReviewLinkHandler extends makeSingleton(AddonModQuizReviewLinkHandlerService) {} +export const AddonModQuizReviewLinkHandler = makeSingleton(AddonModQuizReviewLinkHandlerService); diff --git a/src/addons/mod/quiz/services/handlers/sync-cron.ts b/src/addons/mod/quiz/services/handlers/sync-cron.ts index 9477bbf5e..998680fb6 100644 --- a/src/addons/mod/quiz/services/handlers/sync-cron.ts +++ b/src/addons/mod/quiz/services/handlers/sync-cron.ts @@ -35,7 +35,7 @@ export class AddonModQuizSyncCronHandlerService implements CoreCronHandler { * @return Promise resolved when done, rejected if failure. */ execute(siteId?: string, force?: boolean): Promise { - return AddonModQuizSync.instance.syncAllQuizzes(siteId, force); + return AddonModQuizSync.syncAllQuizzes(siteId, force); } /** @@ -44,9 +44,9 @@ export class AddonModQuizSyncCronHandlerService implements CoreCronHandler { * @return Time between consecutive executions (in ms). */ getInterval(): number { - return AddonModQuizSync.instance.syncInterval; + return AddonModQuizSync.syncInterval; } } -export class AddonModQuizSyncCronHandler extends makeSingleton(AddonModQuizSyncCronHandlerService) {} +export const AddonModQuizSyncCronHandler = makeSingleton(AddonModQuizSyncCronHandlerService); diff --git a/src/addons/mod/quiz/services/quiz-helper.ts b/src/addons/mod/quiz/services/quiz-helper.ts index 8df6627a6..7a02c7a8e 100644 --- a/src/addons/mod/quiz/services/quiz-helper.ts +++ b/src/addons/mod/quiz/services/quiz-helper.ts @@ -70,7 +70,7 @@ export class AddonModQuizHelperProvider { const rules = accessInfo?.activerulenames; // Check if the user needs to input preflight data. - const preflightCheckRequired = await AddonModQuizAccessRuleDelegate.instance.isPreflightCheckRequired( + const preflightCheckRequired = await AddonModQuizAccessRuleDelegate.isPreflightCheckRequired( rules, quiz, attempt, @@ -87,7 +87,7 @@ export class AddonModQuizHelperProvider { } // Get some fixed preflight data from access rules (data that doesn't require user interaction). - await AddonModQuizAccessRuleDelegate.instance.getFixedPreflightData(rules, quiz, preflightData, attempt, prefetch, siteId); + await AddonModQuizAccessRuleDelegate.getFixedPreflightData(rules, quiz, preflightData, attempt, prefetch, siteId); try { // All the preflight data is gathered, now validate it. @@ -106,7 +106,7 @@ export class AddonModQuizHelperProvider { // Show error and ask for the preflight again. // Wait to show the error because we want it to be shown over the preflight modal. setTimeout(() => { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.error', true); + CoreDomUtils.showErrorModalDefault(error, 'core.error', true); }, 100); return this.getAndCheckPreflightData( @@ -147,19 +147,19 @@ export class AddonModQuizHelperProvider { // Check if there is any unsupported rule. rules.forEach((rule) => { - if (!AddonModQuizAccessRuleDelegate.instance.isAccessRuleSupported(rule)) { + if (!AddonModQuizAccessRuleDelegate.isAccessRuleSupported(rule)) { notSupported.push(rule); } }); if (notSupported.length) { throw new CoreError( - Translate.instance.instant('addon.mod_quiz.errorrulesnotsupported') + ' ' + JSON.stringify(notSupported), + Translate.instant('addon.mod_quiz.errorrulesnotsupported') + ' ' + JSON.stringify(notSupported), ); } // Create and show the modal. - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: AddonModQuizPreflightModalComponent, componentProps: { title: title, @@ -190,9 +190,9 @@ export class AddonModQuizHelperProvider { * @return Question's mark. */ getQuestionMarkFromHtml(html: string): string | undefined { - const element = CoreDomUtils.instance.convertToElement(html); + const element = CoreDomUtils.convertToElement(html); - return CoreDomUtils.instance.getContentsOfElement(element, '.grade'); + return CoreDomUtils.getContentsOfElement(element, '.grade'); } /** @@ -204,7 +204,7 @@ export class AddonModQuizHelperProvider { */ async getQuizIdByAttemptId(attemptId: number, options: { cmId?: number; siteId?: string } = {}): Promise { // Use getAttemptReview to retrieve the quiz ID. - const reviewData = await AddonModQuiz.instance.getAttemptReview(attemptId, options); + const reviewData = await AddonModQuiz.getAttemptReview(attemptId, options); if (reviewData.attempt.quiz) { return reviewData.attempt.quiz; @@ -224,28 +224,28 @@ export class AddonModQuizHelperProvider { * @return Promise resolved when done. */ async handleReviewLink(attemptId: number, page?: number, courseId?: number, quizId?: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { if (!quizId) { quizId = await this.getQuizIdByAttemptId(attemptId, { siteId }); } - const module = await CoreCourse.instance.getModuleBasicInfoByInstance(quizId, 'quiz', siteId); + const module = await CoreCourse.getModuleBasicInfoByInstance(quizId, 'quiz', siteId); courseId = courseId || module.course; // Go to the review page. - await CoreNavigator.instance.navigateToSitePath(`mod_quiz/${courseId}/${module.id}/review/${attemptId}`, { + await CoreNavigator.navigateToSitePath(`mod_quiz/${courseId}/${module.id}/review/${attemptId}`, { params: { page: page == undefined || isNaN(page) ? -1 : page, }, siteId, }); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'An error occurred while loading the required data.'); + CoreDomUtils.showErrorModalDefault(error, 'An error occurred while loading the required data.'); } finally { modal.dismiss(); } @@ -271,18 +271,18 @@ export class AddonModQuizHelperProvider { ): Promise { const formattedAttempt = attempt; - formattedAttempt.rescaledGrade = AddonModQuiz.instance.rescaleGrade(attempt.sumgrades, quiz, false); - formattedAttempt.finished = AddonModQuiz.instance.isAttemptFinished(attempt.state); - formattedAttempt.readableState = AddonModQuiz.instance.getAttemptReadableState(quiz, attempt); + formattedAttempt.rescaledGrade = AddonModQuiz.rescaleGrade(attempt.sumgrades, quiz, false); + formattedAttempt.finished = AddonModQuiz.isAttemptFinished(attempt.state); + formattedAttempt.readableState = AddonModQuiz.getAttemptReadableState(quiz, attempt); if (quiz.showMarkColumn && formattedAttempt.finished) { - formattedAttempt.readableMark = AddonModQuiz.instance.formatGrade(attempt.sumgrades, quiz.decimalpoints); + formattedAttempt.readableMark = AddonModQuiz.formatGrade(attempt.sumgrades, quiz.decimalpoints); } else { formattedAttempt.readableMark = ''; } if (quiz.showGradeColumn && formattedAttempt.finished) { - formattedAttempt.readableGrade = AddonModQuiz.instance.formatGrade( + formattedAttempt.readableGrade = AddonModQuiz.formatGrade( Number(formattedAttempt.rescaledGrade), quiz.decimalpoints, ); @@ -295,7 +295,7 @@ export class AddonModQuizHelperProvider { } if (isLastAttempt || isLastAttempt === undefined) { - formattedAttempt.finishedOffline = await AddonModQuiz.instance.isAttemptFinishedOffline(attempt.id, siteId); + formattedAttempt.finishedOffline = await AddonModQuiz.isAttemptFinishedOffline(attempt.id, siteId); } return formattedAttempt; @@ -310,12 +310,12 @@ export class AddonModQuizHelperProvider { setQuizCalculatedData(quiz: AddonModQuizQuizWSData, options: AddonModQuizCombinedReviewOptions): AddonModQuizQuizData { const formattedQuiz = quiz; - formattedQuiz.sumGradesFormatted = AddonModQuiz.instance.formatGrade(quiz.sumgrades, quiz.decimalpoints); - formattedQuiz.gradeFormatted = AddonModQuiz.instance.formatGrade(quiz.grade, quiz.decimalpoints); + formattedQuiz.sumGradesFormatted = AddonModQuiz.formatGrade(quiz.sumgrades, quiz.decimalpoints); + formattedQuiz.gradeFormatted = AddonModQuiz.formatGrade(quiz.grade, quiz.decimalpoints); formattedQuiz.showAttemptColumn = quiz.attempts != 1; formattedQuiz.showGradeColumn = options.someoptions.marks >= AddonModQuizProvider.QUESTION_OPTIONS_MARK_AND_MAX && - AddonModQuiz.instance.quizHasGrades(quiz); + AddonModQuiz.quizHasGrades(quiz); formattedQuiz.showMarkColumn = formattedQuiz.showGradeColumn && quiz.grade != quiz.sumgrades; formattedQuiz.showFeedbackColumn = !!quiz.hasfeedback && !!options.alloptions.overallfeedback; @@ -357,12 +357,12 @@ export class AddonModQuizHelperProvider { if (attempt) { if (attempt.state != AddonModQuizProvider.ATTEMPT_OVERDUE && !attempt.finishedOffline) { // We're continuing an attempt. Call getAttemptData to validate the preflight data. - await AddonModQuiz.instance.getAttemptData(attempt.id, attempt.currentpage!, preflightData, modOptions); + await AddonModQuiz.getAttemptData(attempt.id, attempt.currentpage!, preflightData, modOptions); if (offline) { // Get current page stored in local. - const storedAttempt = await CoreUtils.instance.ignoreErrors( - AddonModQuizOffline.instance.getAttemptById(attempt.id), + const storedAttempt = await CoreUtils.ignoreErrors( + AddonModQuizOffline.getAttemptById(attempt.id), ); attempt.currentpage = storedAttempt?.currentpage ?? attempt.currentpage; @@ -370,15 +370,15 @@ export class AddonModQuizHelperProvider { } else { // Attempt is overdue or finished in offline, we can only see the summary. // Call getAttemptSummary to validate the preflight data. - await AddonModQuiz.instance.getAttemptSummary(attempt.id, preflightData, modOptions); + await AddonModQuiz.getAttemptSummary(attempt.id, preflightData, modOptions); } } else { // We're starting a new attempt, call startAttempt. - attempt = await AddonModQuiz.instance.startAttempt(quiz.id, preflightData, false, siteId); + attempt = await AddonModQuiz.startAttempt(quiz.id, preflightData, false, siteId); } // Preflight data validated. - AddonModQuizAccessRuleDelegate.instance.notifyPreflightCheckPassed( + AddonModQuizAccessRuleDelegate.notifyPreflightCheckPassed( rules, quiz, attempt, @@ -389,9 +389,9 @@ export class AddonModQuizHelperProvider { return attempt; } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // The WebService returned an error, assume the preflight failed. - AddonModQuizAccessRuleDelegate.instance.notifyPreflightCheckFailed( + AddonModQuizAccessRuleDelegate.notifyPreflightCheckFailed( rules, quiz, attempt, @@ -407,7 +407,7 @@ export class AddonModQuizHelperProvider { } -export class AddonModQuizHelper extends makeSingleton(AddonModQuizHelperProvider) {} +export const AddonModQuizHelper = makeSingleton(AddonModQuizHelperProvider); /** * Quiz data with calculated data. diff --git a/src/addons/mod/quiz/services/quiz-offline.ts b/src/addons/mod/quiz/services/quiz-offline.ts index b4ce83f33..4b96ba247 100644 --- a/src/addons/mod/quiz/services/quiz-offline.ts +++ b/src/addons/mod/quiz/services/quiz-offline.ts @@ -48,8 +48,8 @@ export class AddonModQuizOfflineProvider { // Classify the answers in each question. for (const name in answers) { - const slot = CoreQuestion.instance.getQuestionSlotFromName(name); - const nameWithoutPrefix = CoreQuestion.instance.removeQuestionPrefix(name); + const slot = CoreQuestion.getQuestionSlotFromName(name); + const nameWithoutPrefix = CoreQuestion.removeQuestionPrefix(name); if (!questionsWithAnswers[slot]) { questionsWithAnswers[slot] = { @@ -90,7 +90,7 @@ export class AddonModQuizOfflineProvider { * @return Promise resolved with the offline attempts. */ async getAllAttempts(siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); return db.getAllRecords(ATTEMPTS_TABLE_NAME); } @@ -103,7 +103,7 @@ export class AddonModQuizOfflineProvider { * @return Promise resolved with the answers. */ getAttemptAnswers(attemptId: number, siteId?: string): Promise { - return CoreQuestion.instance.getAttemptAnswers(AddonModQuizProvider.COMPONENT, attemptId, siteId); + return CoreQuestion.getAttemptAnswers(AddonModQuizProvider.COMPONENT, attemptId, siteId); } /** @@ -114,7 +114,7 @@ export class AddonModQuizOfflineProvider { * @return Promise resolved with the attempt. */ async getAttemptById(attemptId: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); return db.getRecord(ATTEMPTS_TABLE_NAME, { id: attemptId }); } @@ -128,7 +128,7 @@ export class AddonModQuizOfflineProvider { * @return Promise resolved with the attempts. */ async getQuizAttempts(quizId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecords(ATTEMPTS_TABLE_NAME, { quizid: quizId, userid: userId || site.getUserId() }); } @@ -148,8 +148,8 @@ export class AddonModQuizOfflineProvider { ): Promise { await Promise.all(questions.map(async (question) => { - const dbQuestion = await CoreUtils.instance.ignoreErrors( - CoreQuestion.instance.getQuestion(AddonModQuizProvider.COMPONENT, attemptId, question.slot, siteId), + const dbQuestion = await CoreUtils.ignoreErrors( + CoreQuestion.getQuestion(AddonModQuizProvider.COMPONENT, attemptId, question.slot, siteId), ); if (!dbQuestion) { @@ -157,9 +157,9 @@ export class AddonModQuizOfflineProvider { return; } - const state = CoreQuestion.instance.getState(dbQuestion.state); + const state = CoreQuestion.getState(dbQuestion.state); question.state = dbQuestion.state; - question.status = Translate.instance.instant('core.question.' + state.status); + question.status = Translate.instant('core.question.' + state.status); })); return questions; @@ -184,13 +184,13 @@ export class AddonModQuizOfflineProvider { finish?: boolean, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); - const now = CoreTimeUtils.instance.timestamp(); + siteId = siteId || CoreSites.getCurrentSiteId(); + const now = CoreTimeUtils.timestamp(); - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); // Check if an attempt already exists. Return a new one if it doesn't. - let entry = await CoreUtils.instance.ignoreErrors(this.getAttemptById(attempt.id, siteId)); + let entry = await CoreUtils.ignoreErrors(this.getAttemptById(attempt.id, siteId)); if (entry) { entry.timemodified = now; @@ -224,13 +224,13 @@ export class AddonModQuizOfflineProvider { * @return Promise resolved when done. */ async removeAttemptAndAnswers(attemptId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await Promise.all([ - CoreQuestion.instance.removeAttemptAnswers(AddonModQuizProvider.COMPONENT, attemptId, siteId), - CoreQuestion.instance.removeAttemptQuestions(AddonModQuizProvider.COMPONENT, attemptId, siteId), + CoreQuestion.removeAttemptAnswers(AddonModQuizProvider.COMPONENT, attemptId, siteId), + CoreQuestion.removeAttemptQuestions(AddonModQuizProvider.COMPONENT, attemptId, siteId), db.deleteRecords(ATTEMPTS_TABLE_NAME, { id: attemptId }), ]); } @@ -244,11 +244,11 @@ export class AddonModQuizOfflineProvider { * @return Promise resolved when finished. */ async removeQuestionAndAnswers(attemptId: number, slot: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); await Promise.all([ - CoreQuestion.instance.removeQuestion(AddonModQuizProvider.COMPONENT, attemptId, slot, siteId), - CoreQuestion.instance.removeQuestionAnswers(AddonModQuizProvider.COMPONENT, attemptId, slot, siteId), + CoreQuestion.removeQuestion(AddonModQuizProvider.COMPONENT, attemptId, slot, siteId), + CoreQuestion.removeQuestionAnswers(AddonModQuizProvider.COMPONENT, attemptId, slot, siteId), ]); } @@ -271,16 +271,16 @@ export class AddonModQuizOfflineProvider { timeMod?: number, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); - timeMod = timeMod || CoreTimeUtils.instance.timestamp(); + siteId = siteId || CoreSites.getCurrentSiteId(); + timeMod = timeMod || CoreTimeUtils.timestamp(); const questionsWithAnswers: Record = {}; const newStates: Record = {}; // Classify the answers in each question. for (const name in answers) { - const slot = CoreQuestion.instance.getQuestionSlotFromName(name); - const nameWithoutPrefix = CoreQuestion.instance.removeQuestionPrefix(name); + const slot = CoreQuestion.getQuestionSlotFromName(name); + const nameWithoutPrefix = CoreQuestion.removeQuestionPrefix(name); if (questions[slot]) { if (!questionsWithAnswers[slot]) { @@ -294,7 +294,7 @@ export class AddonModQuizOfflineProvider { // First determine the new state of each question. We won't save the new state yet. await Promise.all(Object.values(questionsWithAnswers).map(async (question) => { - const state = await CoreQuestionBehaviourDelegate.instance.determineNewState( + const state = await CoreQuestionBehaviourDelegate.determineNewState( quiz.preferredbehaviour!, AddonModQuizProvider.COMPONENT, attempt.id, @@ -309,11 +309,11 @@ export class AddonModQuizOfflineProvider { } // Delete previously stored answers for this question. - await CoreQuestion.instance.removeQuestionAnswers(AddonModQuizProvider.COMPONENT, attempt.id, question.slot, siteId); + await CoreQuestion.removeQuestionAnswers(AddonModQuizProvider.COMPONENT, attempt.id, question.slot, siteId); })); // Now save the answers. - await CoreQuestion.instance.saveAnswers( + await CoreQuestion.saveAnswers( AddonModQuizProvider.COMPONENT, quiz.id, attempt.id, @@ -325,10 +325,10 @@ export class AddonModQuizOfflineProvider { try { // Answers have been saved, now we can save the questions with the states. - await CoreUtils.instance.allPromises(Object.keys(newStates).map(async (slot) => { + await CoreUtils.allPromises(Object.keys(newStates).map(async (slot) => { const question = questionsWithAnswers[Number(slot)]; - await CoreQuestion.instance.saveQuestion( + await CoreQuestion.saveQuestion( AddonModQuizProvider.COMPONENT, quiz.id, attempt.id, @@ -354,14 +354,14 @@ export class AddonModQuizOfflineProvider { * @return Promise resolved in success, rejected otherwise. */ async setAttemptCurrentPage(attemptId: number, page: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await db.updateRecords(ATTEMPTS_TABLE_NAME, { currentpage: page }, { id: attemptId }); } } -export class AddonModQuizOffline extends makeSingleton(AddonModQuizOfflineProvider) {} +export const AddonModQuizOffline = makeSingleton(AddonModQuizOfflineProvider); /** * Answers classified by question slot. diff --git a/src/addons/mod/quiz/services/quiz-sync.ts b/src/addons/mod/quiz/services/quiz-sync.ts index 061f0463b..b3424d191 100644 --- a/src/addons/mod/quiz/services/quiz-sync.ts +++ b/src/addons/mod/quiz/services/quiz-sync.ts @@ -66,18 +66,18 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider options = options || {}; // Invalidate the data for the quiz and attempt. - await CoreUtils.instance.ignoreErrors( - AddonModQuiz.instance.invalidateAllQuizData(quiz.id, courseId, options.attemptId, siteId), + await CoreUtils.ignoreErrors( + AddonModQuiz.invalidateAllQuizData(quiz.id, courseId, options.attemptId, siteId), ); if (options.removeAttempt && options.attemptId) { const promises: Promise[] = []; - promises.push(AddonModQuizOffline.instance.removeAttemptAndAnswers(options.attemptId, siteId)); + promises.push(AddonModQuizOffline.removeAttemptAndAnswers(options.attemptId, siteId)); if (options.onlineQuestions) { for (const slot in options.onlineQuestions) { - promises.push(CoreQuestionDelegate.instance.deleteOfflineData( + promises.push(CoreQuestionDelegate.deleteOfflineData( options.onlineQuestions[slot], AddonModQuizProvider.COMPONENT, quiz.coursemodule, @@ -92,7 +92,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider if (options.updated) { try { // Data has been sent. Update prefetched data. - const module = await CoreCourse.instance.getModuleBasicInfoByInstance(quiz.id, 'quiz', siteId); + const module = await CoreCourse.getModuleBasicInfoByInstance(quiz.id, 'quiz', siteId); await this.prefetchAfterUpdateQuiz(module, quiz, courseId, undefined, siteId); } catch { @@ -100,17 +100,17 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider } } - await CoreUtils.instance.ignoreErrors(this.setSyncTime(quiz.id, siteId)); + await CoreUtils.ignoreErrors(this.setSyncTime(quiz.id, siteId)); // Check if online attempt was finished because of the sync. let attemptFinished = false; - if (options.onlineAttempt && !AddonModQuiz.instance.isAttemptFinished(options.onlineAttempt.state)) { + if (options.onlineAttempt && !AddonModQuiz.isAttemptFinished(options.onlineAttempt.state)) { // Attempt wasn't finished at start. Check if it's finished now. - const attempts = await AddonModQuiz.instance.getUserAttempts(quiz.id, { cmId: quiz.coursemodule, siteId }); + const attempts = await AddonModQuiz.getUserAttempts(quiz.id, { cmId: quiz.coursemodule, siteId }); const attempt = attempts.find(attempt => attempt.id == options?.onlineAttempt?.id); - attemptFinished = attempt ? AddonModQuiz.instance.isAttemptFinished(attempt.state) : false; + attemptFinished = attempt ? AddonModQuiz.isAttemptFinished(attempt.state) : false; } return { warnings, attemptFinished, updated: !!options.updated || !!options.removeAttempt }; @@ -125,7 +125,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider */ async hasDataToSync(quizId: number, siteId?: string): Promise { try { - const attempts = await AddonModQuizOffline.instance.getQuizAttempts(quizId, siteId); + const attempts = await AddonModQuizOffline.getQuizAttempts(quizId, siteId); return !!attempts.length; } catch { @@ -155,19 +155,19 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider let shouldDownload = false; // Get the module updates to check if the data was updated or not. - const result = await CoreCourseModulePrefetchDelegate.instance.getModuleUpdates(module, courseId, true, siteId); + const result = await CoreCourseModulePrefetchDelegate.getModuleUpdates(module, courseId, true, siteId); if (result?.updates?.length) { // Only prefetch if files haven't changed. shouldDownload = !result.updates.find((entry) => entry.name.match(regex!)); if (shouldDownload) { - await AddonModQuizPrefetchHandler.instance.download(module, courseId, undefined, false, false); + await AddonModQuizPrefetchHandler.download(module, courseId, undefined, false, false); } } // Prefetch finished or not needed, set the right status. - await AddonModQuizPrefetchHandler.instance.setStatusAfterPrefetch(quiz, { + await AddonModQuizPrefetchHandler.setStatusAfterPrefetch(quiz, { cmId: module.id, readingStrategy: shouldDownload ? CoreSitesReadingStrategy.PreferCache : undefined, siteId, @@ -194,7 +194,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider */ protected async syncAllQuizzesFunc(siteId: string, force: boolean): Promise { // Get all offline attempts. - const attempts = await AddonModQuizOffline.instance.getAllAttempts(siteId); + const attempts = await AddonModQuizOffline.getAllAttempts(siteId); const quizIds: Record = {}; // To prevent duplicates. @@ -206,12 +206,12 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider } quizIds[attempt.quizid] = true; - if (CoreSync.instance.isBlocked(AddonModQuizProvider.COMPONENT, attempt.quizid, siteId)) { + if (CoreSync.isBlocked(AddonModQuizProvider.COMPONENT, attempt.quizid, siteId)) { return; } // Quiz not blocked, try to synchronize it. - const quiz = await AddonModQuiz.instance.getQuizById(attempt.courseid, attempt.quizid, { siteId }); + const quiz = await AddonModQuiz.getQuizById(attempt.courseid, attempt.quizid, { siteId }); const data = await (force ? this.syncQuiz(quiz, false, siteId) : this.syncQuizIfNeeded(quiz, false, siteId)); @@ -261,7 +261,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider * @return Promise resolved in success. */ syncQuiz(quiz: AddonModQuizQuizWSData, askPreflight?: boolean, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.isSyncing(quiz.id, siteId)) { // There's already a sync ongoing for this quiz, return the promise. @@ -269,11 +269,11 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider } // Verify that quiz isn't blocked. - if (CoreSync.instance.isBlocked(AddonModQuizProvider.COMPONENT, quiz.id, siteId)) { + if (CoreSync.isBlocked(AddonModQuizProvider.COMPONENT, quiz.id, siteId)) { this.logger.debug('Cannot sync quiz ' + quiz.id + ' because it is blocked.'); - this.componentTranslate = this.componentTranslate || CoreCourse.instance.translateModuleName('quiz'); + this.componentTranslate = this.componentTranslate || CoreCourse.translateModuleName('quiz'); - throw new CoreError(Translate.instance.instant('core.errorsyncblocked', { $a: this.componentTranslate })); + throw new CoreError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); } return this.addOngoingSync(quiz.id, this.performSyncQuiz(quiz, askPreflight, siteId), siteId); @@ -288,7 +288,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider * @return Promise resolved in success. */ async performSyncQuiz(quiz: AddonModQuizQuizWSData, askPreflight?: boolean, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const warnings: string[] = []; const courseId = quiz.course; @@ -301,34 +301,34 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider this.logger.debug('Try to sync quiz ' + quiz.id + ' in site ' + siteId); // Sync offline logs. - await CoreUtils.instance.ignoreErrors( - CoreCourseLogHelper.instance.syncActivity(AddonModQuizProvider.COMPONENT, quiz.id, siteId), + await CoreUtils.ignoreErrors( + CoreCourseLogHelper.syncActivity(AddonModQuizProvider.COMPONENT, quiz.id, siteId), ); // Get all the offline attempts for the quiz. It should always be 0 or 1 attempt - const offlineAttempts = await AddonModQuizOffline.instance.getQuizAttempts(quiz.id, siteId); + const offlineAttempts = await AddonModQuizOffline.getQuizAttempts(quiz.id, siteId); if (!offlineAttempts.length) { // Nothing to sync, finish. return this.finishSync(siteId, quiz, courseId, warnings); } - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // Cannot sync in offline. - throw new CoreError(Translate.instance.instant('core.cannotconnect')); + throw new CoreError(Translate.instant('core.cannotconnect')); } const offlineAttempt = offlineAttempts.pop()!; // Now get the list of online attempts to make sure this attempt exists and isn't finished. - const onlineAttempts = await AddonModQuiz.instance.getUserAttempts(quiz.id, modOptions); + const onlineAttempts = await AddonModQuiz.getUserAttempts(quiz.id, modOptions); const lastAttemptId = onlineAttempts.length ? onlineAttempts[onlineAttempts.length - 1].id : undefined; const onlineAttempt = onlineAttempts.find((attempt) => attempt.id == offlineAttempt.id); - if (!onlineAttempt || AddonModQuiz.instance.isAttemptFinished(onlineAttempt.state)) { + if (!onlineAttempt || AddonModQuiz.isAttemptFinished(onlineAttempt.state)) { // Attempt not found or it's finished in online. Discard it. - warnings.push(Translate.instance.instant('addon.mod_quiz.warningattemptfinished')); + warnings.push(Translate.instant('addon.mod_quiz.warningattemptfinished')); return this.finishSync(siteId, quiz, courseId, warnings, { attemptId: offlineAttempt.id, @@ -339,7 +339,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider } // Get the data stored in offline. - const answersList = await AddonModQuizOffline.instance.getAttemptAnswers(offlineAttempt.id, siteId); + const answersList = await AddonModQuizOffline.getAttemptAnswers(offlineAttempt.id, siteId); if (!answersList.length) { // No answers stored, finish. @@ -351,13 +351,13 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider }); } - const offlineAnswers = CoreQuestion.instance.convertAnswersArrayToObject(answersList); - const offlineQuestions = AddonModQuizOffline.instance.classifyAnswersInQuestions(offlineAnswers); + const offlineAnswers = CoreQuestion.convertAnswersArrayToObject(answersList); + const offlineQuestions = AddonModQuizOffline.classifyAnswersInQuestions(offlineAnswers); // We're going to need preflightData, get it. - const info = await AddonModQuiz.instance.getQuizAccessInformation(quiz.id, modOptions); + const info = await AddonModQuiz.getQuizAccessInformation(quiz.id, modOptions); - const preflightData = await AddonModQuizPrefetchHandler.instance.getPreflightData( + const preflightData = await AddonModQuizPrefetchHandler.getPreflightData( quiz, info, onlineAttempt, @@ -367,8 +367,8 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider ); // Now get the online questions data. - const onlineQuestions = await AddonModQuiz.instance.getAllQuestionsData(quiz, onlineAttempt, preflightData, { - pages: AddonModQuiz.instance.getPagesFromLayoutAndQuestions(onlineAttempt.layout || '', offlineQuestions), + const onlineQuestions = await AddonModQuiz.getAllQuestionsData(quiz, onlineAttempt, preflightData, { + pages: AddonModQuiz.getPagesFromLayoutAndQuestions(onlineAttempt.layout || '', offlineQuestions), readingStrategy: CoreSitesReadingStrategy.OnlyNetwork, siteId, }); @@ -381,7 +381,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider const slot = Number(slotString); const onlineQuestion = onlineQuestions[slot]; - await CoreQuestionDelegate.instance.prepareSyncData( + await CoreQuestionDelegate.prepareSyncData( onlineQuestion, offlineQuestions[slot].answers, AddonModQuizProvider.COMPONENT, @@ -391,24 +391,24 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider })); // Get the answers to send. - const answers = AddonModQuizOffline.instance.extractAnswersFromQuestions(offlineQuestions); + const answers = AddonModQuizOffline.extractAnswersFromQuestions(offlineQuestions); const finish = !!offlineAttempt.finished && !discardedData; if (discardedData) { if (offlineAttempt.finished) { - warnings.push(Translate.instance.instant('addon.mod_quiz.warningdatadiscardedfromfinished')); + warnings.push(Translate.instant('addon.mod_quiz.warningdatadiscardedfromfinished')); } else { - warnings.push(Translate.instance.instant('addon.mod_quiz.warningdatadiscarded')); + warnings.push(Translate.instant('addon.mod_quiz.warningdatadiscarded')); } } // Send the answers. - await AddonModQuiz.instance.processAttempt(quiz, onlineAttempt, answers, preflightData, finish, false, false, siteId); + await AddonModQuiz.processAttempt(quiz, onlineAttempt, answers, preflightData, finish, false, false, siteId); if (!finish) { // Answers sent, now set the current page. // Don't pass the quiz instance because we don't want to trigger a Firebase event in this case. - await CoreUtils.instance.ignoreErrors(AddonModQuiz.instance.logViewAttempt( + await CoreUtils.ignoreErrors(AddonModQuiz.logViewAttempt( onlineAttempt.id, offlineAttempt.currentpage, preflightData, @@ -454,9 +454,9 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider if (onlineQuestion) { // We found the online data for the question, validate that the sequence check is ok. - if (!CoreQuestionDelegate.instance.validateSequenceCheck(onlineQuestion, offlineSequenceCheck)) { + if (!CoreQuestionDelegate.validateSequenceCheck(onlineQuestion, offlineSequenceCheck)) { // Sequence check is not valid, remove the offline data. - await AddonModQuizOffline.instance.removeQuestionAndAnswers(attemptId, slot, siteId); + await AddonModQuizOffline.removeQuestionAndAnswers(attemptId, slot, siteId); discardedData = true; delete offlineQuestions[slot]; @@ -468,7 +468,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider // Online question not found, it can happen for 2 reasons: // 1- It's a sequential quiz and the question is in a page already passed. // 2- Quiz layout has changed (shouldn't happen since it's blocked if there are attempts). - await AddonModQuizOffline.instance.removeQuestionAndAnswers(attemptId, slot, siteId); + await AddonModQuizOffline.removeQuestionAndAnswers(attemptId, slot, siteId); discardedData = true; delete offlineQuestions[slot]; @@ -480,7 +480,7 @@ export class AddonModQuizSyncProvider extends CoreCourseActivitySyncBaseProvider } -export class AddonModQuizSync extends makeSingleton(AddonModQuizSyncProvider) {} +export const AddonModQuizSync = makeSingleton(AddonModQuizSyncProvider, ['component', 'syncInterval']); /** * Data returned by a quiz sync. diff --git a/src/addons/mod/quiz/services/quiz.ts b/src/addons/mod/quiz/services/quiz.ts index 92b25e9f3..33e3cbd89 100644 --- a/src/addons/mod/quiz/services/quiz.ts +++ b/src/addons/mod/quiz/services/quiz.ts @@ -87,10 +87,10 @@ export class AddonModQuizProvider { */ formatGrade(grade?: number | null, decimals?: number): string { if (grade === undefined || grade == -1 || grade === null || isNaN(grade)) { - return Translate.instance.instant('addon.mod_quiz.notyetgraded'); + return Translate.instant('addon.mod_quiz.notyetgraded'); } - return CoreUtils.instance.formatFloat(CoreTextUtils.instance.roundToDecimals(grade, decimals)); + return CoreUtils.formatFloat(CoreTextUtils.roundToDecimals(grade, decimals)); } /** @@ -166,7 +166,7 @@ export class AddonModQuizProvider { options: CoreCourseCommonModWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetAttemptAccessInformationWSParams = { quizid: quizId, @@ -176,7 +176,7 @@ export class AddonModQuizProvider { cacheKey: this.getAttemptAccessInformationCacheKey(quizId, attemptId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_quiz_get_attempt_access_information', params, preSets); @@ -219,12 +219,12 @@ export class AddonModQuizProvider { options: CoreCourseCommonModWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetAttemptDataWSParams = { attemptid: attemptId, page: page, - preflightdata: CoreUtils.instance.objectToArrayOfObjects( + preflightdata: CoreUtils.objectToArrayOfObjects( preflightData, 'name', 'value', @@ -235,12 +235,12 @@ export class AddonModQuizProvider { cacheKey: this.getAttemptDataCacheKey(attemptId, page), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const result = await site.read('mod_quiz_get_attempt_data', params, preSets); - result.questions = CoreQuestion.instance.parseQuestions(result.questions); + result.questions = CoreQuestion.parseQuestions(result.questions); return result; } @@ -297,12 +297,12 @@ export class AddonModQuizProvider { const dueDate = this.getAttemptDueDate(quiz, attempt); if (attempt.state === AddonModQuizProvider.ATTEMPT_OVERDUE) { - return Translate.instance.instant( + return Translate.instant( 'addon.mod_quiz.overduemustbesubmittedby', - { $a: CoreTimeUtils.instance.userDate(dueDate) }, + { $a: CoreTimeUtils.userDate(dueDate) }, ); } else if (dueDate) { - return Translate.instance.instant('addon.mod_quiz.mustbesubmittedby', { $a: CoreTimeUtils.instance.userDate(dueDate) }); + return Translate.instant('addon.mod_quiz.mustbesubmittedby', { $a: CoreTimeUtils.userDate(dueDate) }); } } @@ -315,23 +315,23 @@ export class AddonModQuizProvider { */ getAttemptReadableState(quiz: AddonModQuizQuizWSData, attempt: AddonModQuizAttempt): string[] { if (attempt.finishedOffline) { - return [Translate.instance.instant('addon.mod_quiz.finishnotsynced')]; + return [Translate.instant('addon.mod_quiz.finishnotsynced')]; } switch (attempt.state) { case AddonModQuizProvider.ATTEMPT_IN_PROGRESS: - return [Translate.instance.instant('addon.mod_quiz.stateinprogress')]; + return [Translate.instant('addon.mod_quiz.stateinprogress')]; case AddonModQuizProvider.ATTEMPT_OVERDUE: { const sentences: string[] = []; const dueDate = this.getAttemptDueDate(quiz, attempt); - sentences.push(Translate.instance.instant('addon.mod_quiz.stateoverdue')); + sentences.push(Translate.instant('addon.mod_quiz.stateoverdue')); if (dueDate) { - sentences.push(Translate.instance.instant( + sentences.push(Translate.instant( 'addon.mod_quiz.stateoverduedetails', - { $a: CoreTimeUtils.instance.userDate(dueDate) }, + { $a: CoreTimeUtils.userDate(dueDate) }, )); } @@ -340,15 +340,15 @@ export class AddonModQuizProvider { case AddonModQuizProvider.ATTEMPT_FINISHED: return [ - Translate.instance.instant('addon.mod_quiz.statefinished'), - Translate.instance.instant( + Translate.instant('addon.mod_quiz.statefinished'), + Translate.instant( 'addon.mod_quiz.statefinisheddetails', - { $a: CoreTimeUtils.instance.userDate(attempt.timefinish! * 1000) }, + { $a: CoreTimeUtils.userDate(attempt.timefinish! * 1000) }, ), ]; case AddonModQuizProvider.ATTEMPT_ABANDONED: - return [Translate.instance.instant('addon.mod_quiz.stateabandoned')]; + return [Translate.instant('addon.mod_quiz.stateabandoned')]; default: return []; @@ -364,16 +364,16 @@ export class AddonModQuizProvider { getAttemptReadableStateName(state: string): string { switch (state) { case AddonModQuizProvider.ATTEMPT_IN_PROGRESS: - return Translate.instance.instant('addon.mod_quiz.stateinprogress'); + return Translate.instant('addon.mod_quiz.stateinprogress'); case AddonModQuizProvider.ATTEMPT_OVERDUE: - return Translate.instance.instant('addon.mod_quiz.stateoverdue'); + return Translate.instant('addon.mod_quiz.stateoverdue'); case AddonModQuizProvider.ATTEMPT_FINISHED: - return Translate.instance.instant('addon.mod_quiz.statefinished'); + return Translate.instant('addon.mod_quiz.statefinished'); case AddonModQuizProvider.ATTEMPT_ABANDONED: - return Translate.instance.instant('addon.mod_quiz.stateabandoned'); + return Translate.instant('addon.mod_quiz.stateabandoned'); default: return ''; @@ -414,7 +414,7 @@ export class AddonModQuizProvider { ): Promise { const page = typeof options.page == 'undefined' ? -1 : options.page; - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params = { attemptid: attemptId, @@ -425,12 +425,12 @@ export class AddonModQuizProvider { cacheErrors: ['noreview'], component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const result = await site.read('mod_quiz_get_attempt_review', params, preSets); - result.questions = CoreQuestion.instance.parseQuestions(result.questions); + result.questions = CoreQuestion.parseQuestions(result.questions); return result; } @@ -459,11 +459,11 @@ export class AddonModQuizProvider { options: AddonModQuizGetAttemptSummaryOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetAttemptSummaryWSParams = { attemptid: attemptId, - preflightdata: CoreUtils.instance.objectToArrayOfObjects( + preflightdata: CoreUtils.objectToArrayOfObjects( preflightData, 'name', 'value', @@ -474,15 +474,15 @@ export class AddonModQuizProvider { cacheKey: this.getAttemptSummaryCacheKey(attemptId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read('mod_quiz_get_attempt_summary', params, preSets); - const questions = CoreQuestion.instance.parseQuestions(response.questions); + const questions = CoreQuestion.parseQuestions(response.questions); if (options.loadLocal) { - return AddonModQuizOffline.instance.loadQuestionsLocalStates(attemptId, questions, site.getId()); + return AddonModQuizOffline.loadQuestionsLocalStates(attemptId, questions, site.getId()); } return questions; @@ -520,7 +520,7 @@ export class AddonModQuizProvider { quizId: number, options: AddonModQuizUserOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const userId = options.userId || site.getUserId(); const params: AddonModQuizGetCombinedReviewOptionsWSParams = { @@ -531,7 +531,7 @@ export class AddonModQuizProvider { cacheKey: this.getCombinedReviewOptionsCacheKey(quizId, userId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read( @@ -542,8 +542,8 @@ export class AddonModQuizProvider { // Convert the arrays to objects with name -> value. return { - someoptions: > CoreUtils.instance.objectToKeyValueMap(response.someoptions, 'name', 'value'), - alloptions: > CoreUtils.instance.objectToKeyValueMap(response.alloptions, 'name', 'value'), + someoptions: > CoreUtils.objectToKeyValueMap(response.someoptions, 'name', 'value'), + alloptions: > CoreUtils.objectToKeyValueMap(response.alloptions, 'name', 'value'), warnings: response.warnings, }; } @@ -582,7 +582,7 @@ export class AddonModQuizProvider { grade: number, options: CoreCourseCommonModWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetQuizFeedbackForGradeWSParams = { quizid: quizId, @@ -593,7 +593,7 @@ export class AddonModQuizProvider { updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_quiz_get_quiz_feedback_for_grade', params, preSets); @@ -636,7 +636,7 @@ export class AddonModQuizProvider { userId?: number, ): Promise { - const items = await CoreGradesHelper.instance.getGradeModuleItems( + const items = await CoreGradesHelper.getGradeModuleItems( courseId, moduleId, userId, @@ -669,17 +669,17 @@ export class AddonModQuizProvider { const messages: string[] = []; questions.forEach((question) => { - if (question.type != 'random' && !CoreQuestionDelegate.instance.isQuestionSupported(question.type)) { + if (question.type != 'random' && !CoreQuestionDelegate.isQuestionSupported(question.type)) { // The question isn't supported. - messages.push(Translate.instance.instant('core.question.questionmessage', { + messages.push(Translate.instant('core.question.questionmessage', { $a: question.slot, - $b: Translate.instance.instant('core.question.errorquestionnotsupported', { $a: question.type }), + $b: Translate.instant('core.question.errorquestionnotsupported', { $a: question.type }), })); } else { - let message = CoreQuestionDelegate.instance.getPreventSubmitMessage(question); + let message = CoreQuestionDelegate.getPreventSubmitMessage(question); if (message) { - message = Translate.instance.instant(message); - messages.push(Translate.instance.instant('core.question.questionmessage', { $a: question.slot, $b: message })); + message = Translate.instant(message); + messages.push(Translate.instant('core.question.questionmessage', { $a: question.slot, $b: message })); } } }); @@ -713,7 +713,7 @@ export class AddonModQuizProvider { options: CoreSitesCommonWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetQuizzesByCoursesWSParams = { courseids: [courseId], @@ -722,7 +722,7 @@ export class AddonModQuizProvider { cacheKey: this.getQuizDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModQuizProvider.COMPONENT, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read( @@ -786,7 +786,7 @@ export class AddonModQuizProvider { quizId: number, options: CoreCourseCommonModWSOptions = {}, ): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetQuizAccessInformationWSParams = { quizid: quizId, @@ -795,7 +795,7 @@ export class AddonModQuizProvider { cacheKey: this.getQuizAccessInformationCacheKey(quizId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_quiz_get_quiz_access_information', params, preSets); @@ -818,13 +818,13 @@ export class AddonModQuizProvider { switch (method) { case AddonModQuizProvider.GRADEHIGHEST: - return Translate.instance.instant('addon.mod_quiz.gradehighest'); + return Translate.instant('addon.mod_quiz.gradehighest'); case AddonModQuizProvider.GRADEAVERAGE: - return Translate.instance.instant('addon.mod_quiz.gradeaverage'); + return Translate.instant('addon.mod_quiz.gradeaverage'); case AddonModQuizProvider.ATTEMPTFIRST: - return Translate.instance.instant('addon.mod_quiz.attemptfirst'); + return Translate.instant('addon.mod_quiz.attemptfirst'); case AddonModQuizProvider.ATTEMPTLAST: - return Translate.instance.instant('addon.mod_quiz.attemptlast'); + return Translate.instant('addon.mod_quiz.attemptlast'); default: return ''; } @@ -848,7 +848,7 @@ export class AddonModQuizProvider { * @return Promise resolved with the access information. */ async getQuizRequiredQtypes(quizId: number, options: CoreCourseCommonModWSOptions = {}): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetQuizRequiredQtypesWSParams = { quizid: quizId, @@ -858,7 +858,7 @@ export class AddonModQuizProvider { updateFrequency: CoreSite.FREQUENCY_SOMETIMES, component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read( @@ -946,7 +946,7 @@ export class AddonModQuizProvider { const notSupported: string[] = []; questionTypes.forEach((type) => { - if (type != 'random' && !CoreQuestionDelegate.instance.isQuestionSupported(type)) { + if (type != 'random' && !CoreQuestionDelegate.isQuestionSupported(type)) { notSupported.push(type); } }); @@ -964,7 +964,7 @@ export class AddonModQuizProvider { const notSupported: string[] = []; rulesNames.forEach((name) => { - if (!AddonModQuizAccessRuleDelegate.instance.isAccessRuleSupported(name)) { + if (!AddonModQuizAccessRuleDelegate.isAccessRuleSupported(name)) { notSupported.push(name); } }); @@ -1008,7 +1008,7 @@ export class AddonModQuizProvider { const status = options.status || 'all'; const includePreviews = typeof options.includePreviews == 'undefined' ? true : options.includePreviews; - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const userId = options.userId || site.getUserId(); const params: AddonModQuizGetUserAttemptsWSParams = { @@ -1022,7 +1022,7 @@ export class AddonModQuizProvider { updateFrequency: CoreSite.FREQUENCY_SOMETIMES, component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read('mod_quiz_get_user_attempts', params, preSets); @@ -1059,7 +1059,7 @@ export class AddonModQuizProvider { * @return Promise resolved with the best grade data. */ async getUserBestGrade(quizId: number, options: AddonModQuizUserOptions = {}): Promise { - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const userId = options.userId || site.getUserId(); const params: AddonModQuizGetUserBestGradeWSParams = { @@ -1070,7 +1070,7 @@ export class AddonModQuizProvider { cacheKey: this.getUserBestGradeCacheKey(quizId, userId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_quiz_get_user_best_grade', params, preSets); @@ -1093,7 +1093,7 @@ export class AddonModQuizProvider { siteId?: string, userId?: number, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const promises: Promise[] = []; @@ -1126,7 +1126,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAttemptAccessInformation(quizId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getAttemptAccessInformationCommonCacheKey(quizId)); } @@ -1140,7 +1140,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAttemptAccessInformationForAttempt(quizId: number, attemptId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAttemptAccessInformationCacheKey(quizId, attemptId)); } @@ -1153,7 +1153,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAttemptData(attemptId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getAttemptDataCommonCacheKey(attemptId)); } @@ -1167,7 +1167,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAttemptDataForPage(attemptId: number, page: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAttemptDataCacheKey(attemptId, page)); } @@ -1180,7 +1180,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAttemptReview(attemptId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getAttemptReviewCommonCacheKey(attemptId)); } @@ -1194,7 +1194,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAttemptReviewForPage(attemptId: number, page: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAttemptReviewCacheKey(attemptId, page)); } @@ -1207,7 +1207,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAttemptSummary(attemptId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAttemptSummaryCacheKey(attemptId)); } @@ -1220,7 +1220,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCombinedReviewOptions(quizId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getCombinedReviewOptionsCommonCacheKey(quizId)); } @@ -1234,7 +1234,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCombinedReviewOptionsForUser(quizId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.invalidateWsCacheForKey(this.getCombinedReviewOptionsCacheKey(quizId, userId || site.getUserId())); } @@ -1249,7 +1249,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Get required data to call the invalidate functions. const quiz = await this.getQuiz(courseId, moduleId, { @@ -1273,7 +1273,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateFeedback(quizId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getFeedbackForGradeCommonCacheKey(quizId)); } @@ -1287,7 +1287,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateFeedbackForGrade(quizId: number, grade: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getFeedbackForGradeCacheKey(quizId, grade)); } @@ -1299,8 +1299,8 @@ export class AddonModQuizProvider { * @return Promise resolved when the files are invalidated. */ async invalidateFiles(moduleId: number): Promise { - await CoreFilepool.instance.invalidateFilesByComponent( - CoreSites.instance.getCurrentSiteId(), + await CoreFilepool.invalidateFilesByComponent( + CoreSites.getCurrentSiteId(), AddonModQuizProvider.COMPONENT, moduleId, ); @@ -1315,9 +1315,9 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateGradeFromGradebook(courseId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - await CoreGradesHelper.instance.invalidateGradeModuleItems(courseId, userId || site.getUserId(), undefined, siteId); + await CoreGradesHelper.invalidateGradeModuleItems(courseId, userId || site.getUserId(), undefined, siteId); } /** @@ -1328,7 +1328,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateQuizAccessInformation(quizId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getQuizAccessInformationCacheKey(quizId)); } @@ -1341,7 +1341,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateQuizRequiredQtypes(quizId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getQuizRequiredQtypesCacheKey(quizId)); } @@ -1354,7 +1354,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserAttempts(quizId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUserAttemptsCommonCacheKey(quizId)); } @@ -1368,7 +1368,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserAttemptsForUser(quizId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserAttemptsCacheKey(quizId, userId || site.getUserId())); } @@ -1381,7 +1381,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserBestGrade(quizId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUserBestGradeCommonCacheKey(quizId)); } @@ -1395,7 +1395,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserBestGradeForUser(quizId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserBestGradeCacheKey(quizId, userId || site.getUserId())); } @@ -1408,7 +1408,7 @@ export class AddonModQuizProvider { * @return Promise resolved when the data is invalidated. */ async invalidateQuizData(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getQuizDataCacheKey(courseId)); } @@ -1432,7 +1432,7 @@ export class AddonModQuizProvider { */ async isAttemptFinishedOffline(attemptId: number, siteId?: string): Promise { try { - const attempt = await AddonModQuizOffline.instance.getAttemptById(attemptId, siteId); + const attempt = await AddonModQuizOffline.getAttemptById(attemptId, siteId); return !!attempt.finished; } catch { @@ -1476,7 +1476,7 @@ export class AddonModQuizProvider { */ async isLastAttemptOfflineUnfinished(quiz: AddonModQuizQuizWSData, siteId?: string, userId?: number): Promise { try { - const attempts = await AddonModQuizOffline.instance.getQuizAttempts(quiz.id, siteId, userId); + const attempts = await AddonModQuizOffline.getQuizAttempts(quiz.id, siteId, userId); const last = attempts.pop(); @@ -1503,7 +1503,7 @@ export class AddonModQuizProvider { * @return Whether it's blocked. */ isQuestionBlocked(question: CoreQuestionQuestionParsed): boolean { - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); return !!element.querySelector('.mod_quiz-blocked_question_warning'); } @@ -1516,7 +1516,7 @@ export class AddonModQuizProvider { */ isQuizOffline(quiz: AddonModQuizQuizWSData): boolean { // Don't allow downloading the quiz if offline is disabled to prevent wasting a lot of data when opening it. - return !!quiz.allowofflineattempts && !CoreSites.instance.getCurrentSite()?.isOfflineDisabled(); + return !!quiz.allowofflineattempts && !CoreSites.getCurrentSite()?.isOfflineDisabled(); } /** @@ -1538,12 +1538,12 @@ export class AddonModQuizProvider { quiz?: AddonModQuizQuizWSData, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModQuizViewAttemptWSParams = { attemptid: attemptId, page: page, - preflightdata: CoreUtils.instance.objectToArrayOfObjects( + preflightdata: CoreUtils.objectToArrayOfObjects( preflightData, 'name', 'value', @@ -1553,10 +1553,10 @@ export class AddonModQuizProvider { promises.push(site.write('mod_quiz_view_attempt', params)); if (offline) { - promises.push(AddonModQuizOffline.instance.setAttemptCurrentPage(attemptId, page, site.getId())); + promises.push(AddonModQuizOffline.setAttemptCurrentPage(attemptId, page, site.getId())); } if (quiz) { - CorePushNotifications.instance.logViewEvent( + CorePushNotifications.logViewEvent( quiz.id, quiz.name, 'quiz', @@ -1583,7 +1583,7 @@ export class AddonModQuizProvider { attemptid: attemptId, }; - return CoreCourseLogHelper.instance.logSingle( + return CoreCourseLogHelper.logSingle( 'mod_quiz_view_attempt_review', params, AddonModQuizProvider.COMPONENT, @@ -1614,14 +1614,14 @@ export class AddonModQuizProvider { ): Promise { const params: AddonModQuizViewAttemptSummaryWSParams = { attemptid: attemptId, - preflightdata: CoreUtils.instance.objectToArrayOfObjects( + preflightdata: CoreUtils.objectToArrayOfObjects( preflightData, 'name', 'value', ), }; - return CoreCourseLogHelper.instance.logSingle( + return CoreCourseLogHelper.logSingle( 'mod_quiz_view_attempt_summary', params, AddonModQuizProvider.COMPONENT, @@ -1646,7 +1646,7 @@ export class AddonModQuizProvider { quizid: id, }; - return CoreCourseLogHelper.instance.logSingle( + return CoreCourseLogHelper.logSingle( 'mod_quiz_view_quiz', params, AddonModQuizProvider.COMPONENT, @@ -1707,14 +1707,14 @@ export class AddonModQuizProvider { timeUp?: boolean, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModQuizProcessAttemptWSParams = { attemptid: attemptId, - data: CoreUtils.instance.objectToArrayOfObjects(data, 'name', 'value'), + data: CoreUtils.objectToArrayOfObjects(data, 'name', 'value'), finishattempt: !!finish, timeup: !!timeUp, - preflightdata: CoreUtils.instance.objectToArrayOfObjects( + preflightdata: CoreUtils.objectToArrayOfObjects( preflightData, 'name', 'value', @@ -1760,9 +1760,9 @@ export class AddonModQuizProvider { }); // Convert the question array to an object. - const questions = CoreUtils.instance.arrayToObject(questionsArray, 'slot'); + const questions = CoreUtils.arrayToObject(questionsArray, 'slot'); - return AddonModQuizOffline.instance.processAttempt(quiz, attempt, questions, data, finish, siteId); + return AddonModQuizOffline.processAttempt(quiz, attempt, questions, data, finish, siteId); } /** @@ -1861,12 +1861,12 @@ export class AddonModQuizProvider { preflightData: Record, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModQuizSaveAttemptWSParams = { attemptid: attemptId, - data: CoreUtils.instance.objectToArrayOfObjects(data, 'name', 'value'), - preflightdata: CoreUtils.instance.objectToArrayOfObjects( + data: CoreUtils.objectToArrayOfObjects(data, 'name', 'value'), + preflightdata: CoreUtils.objectToArrayOfObjects( preflightData, 'name', 'value', @@ -1893,13 +1893,13 @@ export class AddonModQuizProvider { * @return Whether time left should be displayed. */ shouldShowTimeLeft(rules: string[], attempt: AddonModQuizAttemptWSData, endTime: number): boolean { - const timeNow = CoreTimeUtils.instance.timestamp(); + const timeNow = CoreTimeUtils.timestamp(); if (attempt.state != AddonModQuizProvider.ATTEMPT_IN_PROGRESS) { return false; } - return AddonModQuizAccessRuleDelegate.instance.shouldShowTimeLeft(rules, attempt, endTime, timeNow); + return AddonModQuizAccessRuleDelegate.shouldShowTimeLeft(rules, attempt, endTime, timeNow); } /** @@ -1917,11 +1917,11 @@ export class AddonModQuizProvider { forceNew?: boolean, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: AddonModQuizStartAttemptWSParams = { quizid: quizId, - preflightdata: CoreUtils.instance.objectToArrayOfObjects( + preflightdata: CoreUtils.objectToArrayOfObjects( preflightData, 'name', 'value', @@ -1941,7 +1941,7 @@ export class AddonModQuizProvider { } -export class AddonModQuiz extends makeSingleton(AddonModQuizProvider) {} +export const AddonModQuiz = makeSingleton(AddonModQuizProvider); /** * Common options with user ID. diff --git a/src/addons/notifications/components/actions/actions.ts b/src/addons/notifications/components/actions/actions.ts index 8a4a4e58a..9ee3b221a 100644 --- a/src/addons/notifications/components/actions/actions.ts +++ b/src/addons/notifications/components/actions/actions.ts @@ -45,7 +45,7 @@ export class AddonNotificationsActionsComponent implements OnInit { // Treat appurl first if any. if (this.data?.appurl) { - actions = await CoreContentLinksDelegate.instance.getActionsFor( + actions = await CoreContentLinksDelegate.getActionsFor( this.data.appurl, this.courseId, undefined, @@ -55,7 +55,7 @@ export class AddonNotificationsActionsComponent implements OnInit { if (!actions.length && this.contextUrl) { // No appurl or cannot handle it. Try with contextUrl. - actions = await CoreContentLinksDelegate.instance.getActionsFor(this.contextUrl, this.courseId, undefined, this.data); + actions = await CoreContentLinksDelegate.getActionsFor(this.contextUrl, this.courseId, undefined, this.data); } if (!actions.length) { @@ -82,7 +82,7 @@ export class AddonNotificationsActionsComponent implements OnInit { return; } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); site.openInBrowserWithAutoLogin(url); } diff --git a/src/addons/notifications/notifications.module.ts b/src/addons/notifications/notifications.module.ts index 49d012e57..34217e31a 100644 --- a/src/addons/notifications/notifications.module.ts +++ b/src/addons/notifications/notifications.module.ts @@ -45,10 +45,10 @@ const routes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreMainMenuDelegate.instance.registerHandler(AddonNotificationsMainMenuHandler.instance); - CoreCronDelegate.instance.register(AddonNotificationsCronHandler.instance); - CorePushNotificationsDelegate.instance.registerClickHandler(AddonNotificationsPushClickHandler.instance); - CoreSettingsDelegate.instance.registerHandler(AddonNotificationsSettingsHandler.instance); + CoreMainMenuDelegate.registerHandler(AddonNotificationsMainMenuHandler.instance); + CoreCronDelegate.register(AddonNotificationsCronHandler.instance); + CorePushNotificationsDelegate.registerClickHandler(AddonNotificationsPushClickHandler.instance); + CoreSettingsDelegate.registerHandler(AddonNotificationsSettingsHandler.instance); }, }, ], diff --git a/src/addons/notifications/pages/list/list.ts b/src/addons/notifications/pages/list/list.ts index b1c7b03e7..f65a05e1e 100644 --- a/src/addons/notifications/pages/list/list.ts +++ b/src/addons/notifications/pages/list/list.ts @@ -60,9 +60,9 @@ export class AddonNotificationsListPage implements OnInit, OnDestroy { this.notificationsLoaded = false; this.refreshNotifications(); - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); - this.pushObserver = CorePushNotificationsDelegate.instance.on('receive').subscribe((notification) => { + this.pushObserver = CorePushNotificationsDelegate.on('receive').subscribe((notification) => { // New notification received. If it's from current site, refresh the data. if (!this.isCurrentView) { this.pendingRefresh = true; @@ -70,7 +70,7 @@ export class AddonNotificationsListPage implements OnInit, OnDestroy { return; } - if (!CoreUtils.instance.isTrueOrOne(notification.notif) || !CoreSites.instance.isCurrentSite(notification.site)) { + if (!CoreUtils.isTrueOrOne(notification.notif) || !CoreSites.isCurrentSite(notification.site)) { return; } @@ -89,7 +89,7 @@ export class AddonNotificationsListPage implements OnInit, OnDestroy { this.loadMoreError = false; try { - const result = await AddonNotificationsHelper.instance.getNotifications(refresh ? [] : this.notifications); + const result = await AddonNotificationsHelper.getNotifications(refresh ? [] : this.notifications); const notifications = result.notifications.map((notification) => this.formatText(notification)); @@ -102,7 +102,7 @@ export class AddonNotificationsListPage implements OnInit, OnDestroy { this.markNotificationsAsRead(notifications); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.notifications.errorgetnotifications', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.notifications.errorgetnotifications', true); this.loadMoreError = true; // Set to prevent infinite calls with infinite-loading. } finally { this.notificationsLoaded = true; @@ -117,9 +117,9 @@ export class AddonNotificationsListPage implements OnInit, OnDestroy { async markAllNotificationsAsRead(): Promise { this.loadingMarkAllNotificationsAsRead = true; - await CoreUtils.instance.ignoreErrors(AddonNotifications.instance.markAllNotificationsAsRead()); + await CoreUtils.ignoreErrors(AddonNotifications.markAllNotificationsAsRead()); - CoreEvents.trigger(AddonNotificationsProvider.READ_CHANGED_EVENT, {}, CoreSites.instance.getCurrentSiteId()); + CoreEvents.trigger(AddonNotificationsProvider.READ_CHANGED_EVENT, {}, CoreSites.getCurrentSiteId()); // All marked as read, refresh the list. this.notificationsLoaded = false; @@ -140,18 +140,18 @@ export class AddonNotificationsListPage implements OnInit, OnDestroy { return; } - await AddonNotifications.instance.markNotificationRead(notification.id); + await AddonNotifications.markNotificationRead(notification.id); }); - await CoreUtils.instance.ignoreErrors(Promise.all(promises)); + await CoreUtils.ignoreErrors(Promise.all(promises)); - await CoreUtils.instance.ignoreErrors(AddonNotifications.instance.invalidateNotificationsList()); + await CoreUtils.ignoreErrors(AddonNotifications.invalidateNotificationsList()); - CoreEvents.trigger(AddonNotificationsProvider.READ_CHANGED_EVENT, {}, CoreSites.instance.getCurrentSiteId()); + CoreEvents.trigger(AddonNotificationsProvider.READ_CHANGED_EVENT, {}, CoreSites.getCurrentSiteId()); } // Check if mark all notifications as read is enabled and there are some to read. - if (!AddonNotifications.instance.isMarkAllNotificationsAsReadEnabled()) { + if (!AddonNotifications.isMarkAllNotificationsAsReadEnabled()) { this.canMarkAllNotificationsAsRead = false; return; @@ -160,7 +160,7 @@ export class AddonNotificationsListPage implements OnInit, OnDestroy { try { this.loadingMarkAllNotificationsAsRead = true; - const unread = await AddonNotifications.instance.getUnreadNotificationsCount(); + const unread = await AddonNotifications.getUnreadNotificationsCount(); this.canMarkAllNotificationsAsRead = unread > 0; } finally { @@ -175,7 +175,7 @@ export class AddonNotificationsListPage implements OnInit, OnDestroy { * @return Promise Promise resolved when done. */ async refreshNotifications(refresher?: CustomEvent): Promise { - await CoreUtils.instance.ignoreErrors(AddonNotifications.instance.invalidateNotificationsList()); + await CoreUtils.ignoreErrors(AddonNotifications.invalidateNotificationsList()); try { await this.fetchNotifications(true); @@ -209,7 +209,7 @@ export class AddonNotificationsListPage implements OnInit, OnDestroy { formattedNotification.mobiletext = formattedNotification.displayfullhtml ? notification.fullmessagehtml : - CoreTextUtils.instance.replaceNewLines(formattedNotification.mobiletext!.replace(/-{4,}/ig, ''), '
'); + CoreTextUtils.replaceNewLines(formattedNotification.mobiletext!.replace(/-{4,}/ig, ''), '
'); return formattedNotification; } diff --git a/src/addons/notifications/pages/settings/settings.ts b/src/addons/notifications/pages/settings/settings.ts index f93df756a..12211e72c 100644 --- a/src/addons/notifications/pages/settings/settings.ts +++ b/src/addons/notifications/pages/settings/settings.ts @@ -62,8 +62,8 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { protected updateTimeout?: number; constructor() { // @todo @Optional() protected svComponent: CoreSplitViewComponent, - this.notifPrefsEnabled = AddonNotifications.instance.isNotificationPreferencesEnabled(); - this.canChangeSound = CoreLocalNotifications.instance.canDisableSound(); + this.notifPrefsEnabled = AddonNotifications.isNotificationPreferencesEnabled(); + this.canChangeSound = CoreLocalNotifications.canDisableSound(); } /** @@ -71,7 +71,7 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { */ async ngOnInit(): Promise { if (this.canChangeSound) { - this.notificationSound = await CoreConfig.instance.get(CoreConstants.SETTINGS_NOTIFICATION_SOUND, true); + this.notificationSound = await CoreConfig.get(CoreConstants.SETTINGS_NOTIFICATION_SOUND, true); } if (this.notifPrefsEnabled) { @@ -88,11 +88,11 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { */ protected async fetchPreferences(): Promise { try { - const preferences = await AddonNotifications.instance.getNotificationPreferences(); + const preferences = await AddonNotifications.getNotificationPreferences(); if (!this.currentProcessor) { // Initialize current processor. Load "Mobile" (airnotifier) if available. - this.currentProcessor = AddonNotificationsHelper.instance.getProcessor(preferences.processors, 'airnotifier'); + this.currentProcessor = AddonNotificationsHelper.getProcessor(preferences.processors, 'airnotifier'); } if (!this.currentProcessor) { @@ -101,11 +101,11 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { } preferences.enableall = !preferences.disableall; - this.preferences = AddonNotificationsHelper.instance.formatPreferences(preferences); + this.preferences = AddonNotificationsHelper.formatPreferences(preferences); this.loadProcessor(this.currentProcessor); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { this.preferencesLoaded = true; } @@ -123,7 +123,7 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { this.currentProcessor = processor; this.processorHandlers = []; - this.components = AddonNotificationsHelper.instance.getProcessorComponents( + this.components = AddonNotificationsHelper.getProcessorComponents( processor.name, this.preferences?.components || [], ); @@ -132,7 +132,7 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { return; } - const handlerData = AddonMessageOutputDelegate.instance.getDisplayData(processor); + const handlerData = AddonMessageOutputDelegate.getDisplayData(processor); if (handlerData) { this.processorHandlers.push(handlerData); } @@ -157,9 +157,9 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ protected async updatePreferences(): Promise { - await CoreUtils.instance.ignoreErrors(AddonNotifications.instance.invalidateNotificationPreferences()); + await CoreUtils.ignoreErrors(AddonNotifications.invalidateNotificationPreferences()); - await AddonNotifications.instance.getNotificationPreferences(); + await AddonNotifications.getNotificationPreferences(); } /** @@ -182,7 +182,7 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { */ async refreshPreferences(refresher?: CustomEvent): Promise { try { - await CoreUtils.instance.ignoreErrors(AddonNotifications.instance.invalidateNotificationPreferences()); + await CoreUtils.ignoreErrors(AddonNotifications.invalidateNotificationPreferences()); await this.fetchPreferences(); } finally { @@ -198,7 +198,7 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { openExtraPreferences(handlerData: AddonMessageOutputHandlerData): void { // Decide which navCtrl to use. If this page is inside a split view, use the split view's master nav. // @todo const navCtrl = this.svComponent ? this.svComponent.getMasterNav() : this.navCtrl; - CoreNavigator.instance.navigateToSitePath(handlerData.page, { params: handlerData.pageParams }); + CoreNavigator.navigateToSitePath(handlerData.page, { params: handlerData.pageParams }); } /** @@ -235,13 +235,13 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { processorState.updating = true; try { - await CoreUser.instance.updateUserPreference(preferenceName, value); + await CoreUser.updateUserPreference(preferenceName, value); // Update the preferences since they were modified. this.updatePreferencesAfterDelay(); } catch (error) { // Show error and revert change. - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); processor[state].checked = !processor[state].checked; } finally { processorState.updating = false; @@ -255,16 +255,16 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ async enableAll(enable?: boolean): Promise { - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - CoreUser.instance.updateUserPreferences([], !enable); + CoreUser.updateUserPreferences([], !enable); // Update the preferences since they were modified. this.updatePreferencesAfterDelay(); } catch (error) { // Show error and revert change. - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); this.preferences!.enableall = !this.preferences!.enableall; } finally { modal.dismiss(); @@ -277,11 +277,11 @@ export class AddonNotificationsSettingsPage implements OnInit, OnDestroy { * @param enabled True to enable the notification sound, false to disable it. */ async changeNotificationSound(enabled: boolean): Promise { - await CoreUtils.instance.ignoreErrors(CoreConfig.instance.set(CoreConstants.SETTINGS_NOTIFICATION_SOUND, enabled ? 1 : 0)); + await CoreUtils.ignoreErrors(CoreConfig.set(CoreConstants.SETTINGS_NOTIFICATION_SOUND, enabled ? 1 : 0)); - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); CoreEvents.trigger(CoreEvents.NOTIFICATION_SOUND_CHANGED, { enabled }, siteId); - CoreLocalNotifications.instance.rescheduleAll(); + CoreLocalNotifications.rescheduleAll(); } /** diff --git a/src/addons/notifications/services/handlers/cron.ts b/src/addons/notifications/services/handlers/cron.ts index 42831a38b..828a78fbc 100644 --- a/src/addons/notifications/services/handlers/cron.ts +++ b/src/addons/notifications/services/handlers/cron.ts @@ -35,7 +35,7 @@ export class AddonNotificationsCronHandlerService implements CoreCronHandler { * @return Time between consecutive executions (in ms). */ getInterval(): number { - return CoreApp.instance.isMobile() ? 600000 : 60000; // 1 or 10 minutes. + return CoreApp.isMobile() ? 600000 : 60000; // 1 or 10 minutes. } /** @@ -45,7 +45,7 @@ export class AddonNotificationsCronHandlerService implements CoreCronHandler { */ isSync(): boolean { // This is done to use only wifi if using the fallback function. - return !AddonNotifications.instance.isPreciseNotificationCountEnabled(); + return !AddonNotifications.isPreciseNotificationCountEnabled(); } /** @@ -68,13 +68,13 @@ export class AddonNotificationsCronHandlerService implements CoreCronHandler { */ // eslint-disable-next-line @typescript-eslint/no-unused-vars async execute(siteId?: string, force?: boolean): Promise { - if (!CoreSites.instance.isCurrentSite(siteId)) { + if (!CoreSites.isCurrentSite(siteId)) { return; } - CoreEvents.trigger(AddonNotificationsProvider.READ_CRON_EVENT, {}, CoreSites.instance.getCurrentSiteId()); + CoreEvents.trigger(AddonNotificationsProvider.READ_CRON_EVENT, {}, CoreSites.getCurrentSiteId()); } } -export class AddonNotificationsCronHandler extends makeSingleton(AddonNotificationsCronHandlerService) {} +export const AddonNotificationsCronHandler = makeSingleton(AddonNotificationsCronHandlerService); diff --git a/src/addons/notifications/services/handlers/mainmenu.ts b/src/addons/notifications/services/handlers/mainmenu.ts index 8ece315fe..c7312e305 100644 --- a/src/addons/notifications/services/handlers/mainmenu.ts +++ b/src/addons/notifications/services/handlers/mainmenu.ts @@ -64,15 +64,15 @@ export class AddonNotificationsMainMenuHandlerService implements CoreMainMenuHan }); // If a push notification is received, refresh the count. - CorePushNotificationsDelegate.instance.on('receive').subscribe((notification) => { + CorePushNotificationsDelegate.on('receive').subscribe((notification) => { // New notification received. If it's from current site, refresh the data. - if (CoreUtils.instance.isTrueOrOne(notification.notif) && CoreSites.instance.isCurrentSite(notification.site)) { + if (CoreUtils.isTrueOrOne(notification.notif) && CoreSites.isCurrentSite(notification.site)) { this.updateBadge(notification.site); } }); // Register Badge counter. - CorePushNotificationsDelegate.instance.registerCounterHandler('AddonNotifications'); + CorePushNotificationsDelegate.registerCounterHandler('AddonNotifications'); } /** @@ -104,16 +104,16 @@ export class AddonNotificationsMainMenuHandlerService implements CoreMainMenuHan * @return Promise resolved when done. */ protected async updateBadge(siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!siteId) { return; } try { - const unreadCount = await AddonNotifications.instance.getUnreadNotificationsCount(undefined, siteId); + const unreadCount = await AddonNotifications.getUnreadNotificationsCount(undefined, siteId); this.handlerData.badge = unreadCount > 0 ? String(unreadCount) : ''; - CorePushNotifications.instance.updateAddonCounter('AddonNotifications', unreadCount, siteId); + CorePushNotifications.updateAddonCounter('AddonNotifications', unreadCount, siteId); } catch { this.handlerData.badge = ''; } finally { @@ -123,4 +123,4 @@ export class AddonNotificationsMainMenuHandlerService implements CoreMainMenuHan } -export class AddonNotificationsMainMenuHandler extends makeSingleton(AddonNotificationsMainMenuHandlerService) {} +export const AddonNotificationsMainMenuHandler = makeSingleton(AddonNotificationsMainMenuHandlerService); diff --git a/src/addons/notifications/services/handlers/push-click.ts b/src/addons/notifications/services/handlers/push-click.ts index 32985b0b2..c9a467c0b 100644 --- a/src/addons/notifications/services/handlers/push-click.ts +++ b/src/addons/notifications/services/handlers/push-click.ts @@ -47,7 +47,7 @@ export class AddonNotificationsPushClickHandlerService implements CorePushNotifi return true; } - if (CoreUtils.instance.isTrueOrOne(notification.notif)) { + if (CoreUtils.isTrueOrOne(notification.notif)) { // Notification clicked, mark as read. Don't block for this. this.markAsRead(notification); @@ -70,7 +70,7 @@ export class AddonNotificationsPushClickHandlerService implements CorePushNotifi return; } - await CoreUtils.instance.ignoreErrors(AddonNotifications.instance.markNotificationRead(notifId, notification.site)); + await CoreUtils.ignoreErrors(AddonNotifications.markNotificationRead(notifId, notification.site)); CoreEvents.trigger(AddonNotificationsProvider.READ_CHANGED_EVENT, {}, notification.site); } @@ -85,7 +85,7 @@ export class AddonNotificationsPushClickHandlerService implements CorePushNotifi if (notification.customdata?.extendedtext) { // Display the text in a modal. - return CoreTextUtils.instance.viewText(notification.title || '', notification.customdata.extendedtext, { + return CoreTextUtils.viewText(notification.title || '', notification.customdata.extendedtext, { displayCopyButton: true, modalOptions: { cssClass: 'core-modal-fullscreen' }, }); @@ -97,15 +97,15 @@ export class AddonNotificationsPushClickHandlerService implements CorePushNotifi switch (notification.customdata.appurlopenin) { case 'inapp': - CoreUtils.instance.openInApp(url); + CoreUtils.openInApp(url); return; case 'browser': - return CoreUtils.instance.openInBrowser(url); + return CoreUtils.openInBrowser(url); default: - if (CoreContentLinksHelper.instance.handleLink(url, undefined, undefined, true)) { + if (CoreContentLinksHelper.handleLink(url, undefined, undefined, true)) { // Link treated, stop. return; } @@ -114,16 +114,16 @@ export class AddonNotificationsPushClickHandlerService implements CorePushNotifi // No appurl or cannot be handled by the app. Try to handle the contexturl now. if (notification.contexturl) { - if (CoreContentLinksHelper.instance.handleLink(notification.contexturl)) { + if (CoreContentLinksHelper.handleLink(notification.contexturl)) { // Link treated, stop. return; } } // No contexturl or cannot be handled by the app. Open the notifications page. - await CoreUtils.instance.ignoreErrors(AddonNotifications.instance.invalidateNotificationsList(notification.site)); + await CoreUtils.ignoreErrors(AddonNotifications.invalidateNotificationsList(notification.site)); - await CoreNavigator.instance.navigateToSitePath( + await CoreNavigator.navigateToSitePath( AddonNotificationsMainMenuHandlerService.PAGE_NAME, { siteId: notification.site }, ); @@ -131,7 +131,7 @@ export class AddonNotificationsPushClickHandlerService implements CorePushNotifi } -export class AddonNotificationsPushClickHandler extends makeSingleton(AddonNotificationsPushClickHandlerService) {} +export const AddonNotificationsPushClickHandler = makeSingleton(AddonNotificationsPushClickHandlerService); type AddonNotificationsNotificationData = CorePushNotificationsNotificationBasicData & { contexturl?: string; // URL related to the notification. diff --git a/src/addons/notifications/services/handlers/settings.ts b/src/addons/notifications/services/handlers/settings.ts index ff127ae90..6bea1480d 100644 --- a/src/addons/notifications/services/handlers/settings.ts +++ b/src/addons/notifications/services/handlers/settings.ts @@ -38,7 +38,7 @@ export class AddonNotificationsSettingsHandlerService implements CoreSettingsHan */ async isEnabled(): Promise { // Preferences or notification sound setting available. - return CoreLocalNotifications.instance.isAvailable() || AddonNotifications.instance.isNotificationPreferencesEnabled(); + return CoreLocalNotifications.isAvailable() || AddonNotifications.isNotificationPreferencesEnabled(); } /** @@ -57,4 +57,4 @@ export class AddonNotificationsSettingsHandlerService implements CoreSettingsHan } -export class AddonNotificationsSettingsHandler extends makeSingleton(AddonNotificationsSettingsHandlerService) {} +export const AddonNotificationsSettingsHandler = makeSingleton(AddonNotificationsSettingsHandlerService); diff --git a/src/addons/notifications/services/notifications-helper.ts b/src/addons/notifications/services/notifications-helper.ts index 9491b28a8..ebea4573a 100644 --- a/src/addons/notifications/services/notifications-helper.ts +++ b/src/addons/notifications/services/notifications-helper.ts @@ -46,12 +46,12 @@ export class AddonNotificationsHelperProvider { const formattedPreferences: AddonNotificationsPreferencesFormatted = preferences; formattedPreferences.processors.forEach((processor) => { - processor.supported = AddonMessageOutputDelegate.instance.hasHandler(processor.name, true); + processor.supported = AddonMessageOutputDelegate.hasHandler(processor.name, true); }); formattedPreferences.components.forEach((component) => { component.notifications.forEach((notification) => { - notification.processorsByName = CoreUtils.instance.arrayToObject(notification.processors, 'name'); + notification.processorsByName = CoreUtils.arrayToObject(notification.processors, 'name'); }); }); @@ -73,18 +73,18 @@ export class AddonNotificationsHelperProvider { notifications = notifications || []; options = options || {}; options.limit = options.limit || AddonNotificationsProvider.LIST_LIMIT; - options.siteId = options.siteId || CoreSites.instance.getCurrentSiteId(); + options.siteId = options.siteId || CoreSites.getCurrentSiteId(); - const available = await AddonNotifications.instance.isPopupAvailable(options.siteId); + const available = await AddonNotifications.isPopupAvailable(options.siteId); if (available) { - return AddonNotifications.instance.getPopupNotifications(notifications.length, options); + return AddonNotifications.getPopupNotifications(notifications.length, options); } // Fallback to get_messages. We need 2 calls, one for read and the other one for unread. const unreadFrom = notifications.reduce((total, current) => total + (current.read ? 0 : 1), 0); - const unread = await AddonNotifications.instance.getUnreadNotifications(unreadFrom, options); + const unread = await AddonNotifications.getUnreadNotifications(unreadFrom, options); let newNotifications = unread; @@ -95,7 +95,7 @@ export class AddonNotificationsHelperProvider { const readOptions = Object.assign({}, options, { limit: readLimit }); try { - const read = await AddonNotifications.instance.getReadNotifications(readFrom, readOptions); + const read = await AddonNotifications.getReadNotifications(readFrom, readOptions); newNotifications = unread.concat(read); } catch (error) { @@ -179,7 +179,7 @@ export class AddonNotificationsHelperProvider { } -export class AddonNotificationsHelper extends makeSingleton(AddonNotificationsHelperProvider) {} +export const AddonNotificationsHelper = makeSingleton(AddonNotificationsHelperProvider); /** * Preferences with some calculated data. diff --git a/src/addons/notifications/services/notifications.ts b/src/addons/notifications/services/notifications.ts index 7a942f73e..aa4cc92bb 100644 --- a/src/addons/notifications/services/notifications.ts +++ b/src/addons/notifications/services/notifications.ts @@ -81,7 +81,7 @@ export class AddonNotificationsProvider { } if (typeof notification.customdata == 'string') { - notification.customdata = CoreTextUtils.instance.parseJSON>(notification.customdata, {}); + notification.customdata = CoreTextUtils.parseJSON>(notification.customdata, {}); } // Try to set courseid the notification belongs to. @@ -97,7 +97,7 @@ export class AddonNotificationsProvider { if (notification.useridfrom > 0) { // Try to get the profile picture of the user. try { - const user = await CoreUser.instance.getProfile(notification.useridfrom, notification.courseid, true); + const user = await CoreUser.getProfile(notification.useridfrom, notification.courseid, true); notification.profileimageurlfrom = user.profileimageurl; notification.userfromfullname = user.fullname; @@ -130,7 +130,7 @@ export class AddonNotificationsProvider { async getNotificationPreferences(siteId?: string): Promise { this.logger.debug('Get notification preferences'); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { cacheKey: this.getNotificationPreferencesCacheKey(), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, @@ -172,7 +172,7 @@ export class AddonNotificationsProvider { this.logger.debug(`Get ${(read ? 'read' : 'unread')} notifications from ${offset}. Limit: ${options.limit}`); - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const data: AddonNotificationsGetMessagesWSParams = { useridto: site.getUserId(), useridfrom: 0, @@ -184,7 +184,7 @@ export class AddonNotificationsProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getNotificationsCacheKey(), - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; // Get unread notifications. @@ -212,7 +212,7 @@ export class AddonNotificationsProvider { this.logger.debug(`Get popup notifications from ${offset}. Limit: ${options.limit}`); - const site = await CoreSites.instance.getSite(options.siteId); + const site = await CoreSites.getSite(options.siteId); const data: AddonNotificationsPopupGetPopupNotificationsWSParams = { useridto: site.getUserId(), newestfirst: true, @@ -221,7 +221,7 @@ export class AddonNotificationsProvider { }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getNotificationsCacheKey(), - ...CoreSites.instance.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. + ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; // Get notifications. @@ -275,7 +275,7 @@ export class AddonNotificationsProvider { * @return Promise resolved with the message notifications count. */ async getUnreadNotificationsCount(userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // @since 3.2 if (site.wsAvailable('message_popup_get_unread_popup_notification_count')) { @@ -318,7 +318,7 @@ export class AddonNotificationsProvider { * @since 3.2 */ async isPopupAvailable(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.wsAvailable('message_popup_get_popup_notifications'); } @@ -330,10 +330,10 @@ export class AddonNotificationsProvider { * @since 3.2 */ async markAllNotificationsAsRead(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreMessageMarkAllNotificationsAsReadWSParams = { - useridto: CoreSites.instance.getCurrentSiteUserId(), + useridto: CoreSites.getCurrentSiteUserId(), }; return site.write('core_message_mark_all_notifications_as_read', params); @@ -352,18 +352,18 @@ export class AddonNotificationsProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (site.wsAvailable('core_message_mark_notification_read')) { const params: CoreMessageMarkNotificationReadWSParams = { notificationid: notificationId, - timeread: CoreTimeUtils.instance.timestamp(), + timeread: CoreTimeUtils.timestamp(), }; return site.write('core_message_mark_notification_read', params); } else { // Fallback for versions prior to 3.5. - return AddonMessages.instance.markMessageRead(notificationId, site.id); + return AddonMessages.markMessageRead(notificationId, site.id); } } @@ -374,7 +374,7 @@ export class AddonNotificationsProvider { * @return Promise resolved when data is invalidated. */ async invalidateNotificationPreferences(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getNotificationPreferencesCacheKey()); } @@ -386,7 +386,7 @@ export class AddonNotificationsProvider { * @return Promise resolved when the list is invalidated. */ async invalidateNotificationsList(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getNotificationsCacheKey()); } @@ -398,7 +398,7 @@ export class AddonNotificationsProvider { * @since 3.2 */ isMarkAllNotificationsAsReadEnabled(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('core_message_mark_all_notifications_as_read'); + return CoreSites.wsAvailableInCurrentSite('core_message_mark_all_notifications_as_read'); } /** @@ -408,7 +408,7 @@ export class AddonNotificationsProvider { * @since 3.2 */ isPreciseNotificationCountEnabled(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('message_popup_get_unread_popup_notification_count'); + return CoreSites.wsAvailableInCurrentSite('message_popup_get_unread_popup_notification_count'); } /** @@ -418,12 +418,12 @@ export class AddonNotificationsProvider { * @since 3.2 */ isNotificationPreferencesEnabled(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('core_message_get_user_notification_preferences'); + return CoreSites.wsAvailableInCurrentSite('core_message_get_user_notification_preferences'); } } -export class AddonNotifications extends makeSingleton(AddonNotificationsProvider) {} +export const AddonNotifications = makeSingleton(AddonNotificationsProvider); /** * Preferences returned by core_message_get_user_notification_preferences. diff --git a/src/addons/privatefiles/pages/index/index.ts b/src/addons/privatefiles/pages/index/index.ts index 3a0743bfa..c9498f8d6 100644 --- a/src/addons/privatefiles/pages/index/index.ts +++ b/src/addons/privatefiles/pages/index/index.ts @@ -62,32 +62,32 @@ export class AddonPrivateFilesIndexPage implements OnInit, OnDestroy { // Update visibility if current site info is updated. this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { this.setVisibility(); - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } /** * Component being initialized. */ ngOnInit(): void { - this.root = CoreNavigator.instance.getRouteParam('root'); - const contextId = CoreNavigator.instance.getRouteNumberParam('contextid'); + this.root = CoreNavigator.getRouteParam('root'); + const contextId = CoreNavigator.getRouteNumberParam('contextid'); if (contextId) { // Loading a certain folder. this.path = { contextid: contextId, - component: CoreNavigator.instance.getRouteParam('component')!, - filearea: CoreNavigator.instance.getRouteParam('filearea')!, - itemid: CoreNavigator.instance.getRouteNumberParam('itemid')!, - filepath: CoreNavigator.instance.getRouteParam('filepath')!, - filename: CoreNavigator.instance.getRouteParam('filename')!, + component: CoreNavigator.getRouteParam('component')!, + filearea: CoreNavigator.getRouteParam('filearea')!, + itemid: CoreNavigator.getRouteNumberParam('itemid')!, + filepath: CoreNavigator.getRouteParam('filepath')!, + filename: CoreNavigator.getRouteParam('filename')!, }; } - this.title = this.path?.filename || Translate.instance.instant('addon.privatefiles.files'); + this.title = this.path?.filename || Translate.instant('addon.privatefiles.files'); this.setVisibility(); - this.userQuota = CoreSites.instance.getCurrentSite()?.getInfo()?.userquota; + this.userQuota = CoreSites.getCurrentSite()?.getInfo()?.userquota; if (!this.root) { // Load private files by default. @@ -109,9 +109,9 @@ export class AddonPrivateFilesIndexPage implements OnInit, OnDestroy { * Set visibility of some items based on site data. */ protected setVisibility(): void { - this.showPrivateFiles = AddonPrivateFiles.instance.canViewPrivateFiles(); - this.showSiteFiles = AddonPrivateFiles.instance.canViewSiteFiles(); - this.showUpload = AddonPrivateFiles.instance.canUploadFiles(); + this.showPrivateFiles = AddonPrivateFiles.canViewPrivateFiles(); + this.showSiteFiles = AddonPrivateFiles.canViewSiteFiles(); + this.showUpload = AddonPrivateFiles.canUploadFiles(); } /** @@ -142,31 +142,31 @@ export class AddonPrivateFilesIndexPage implements OnInit, OnDestroy { * Upload a new file. */ async uploadFile(): Promise { - const canUpload = await AddonPrivateFiles.instance.versionCanUploadFiles(); + const canUpload = await AddonPrivateFiles.versionCanUploadFiles(); if (!canUpload) { - CoreDomUtils.instance.showAlertTranslated('core.notice', 'addon.privatefiles.erroruploadnotworking'); + CoreDomUtils.showAlertTranslated('core.notice', 'addon.privatefiles.erroruploadnotworking'); return; } - if (!CoreApp.instance.isOnline()) { - CoreDomUtils.instance.showErrorModal('core.fileuploader.errormustbeonlinetoupload', true); + if (!CoreApp.isOnline()) { + CoreDomUtils.showErrorModal('core.fileuploader.errormustbeonlinetoupload', true); return; } try { - await AddonPrivateFilesHelper.instance.uploadPrivateFile(this.filesInfo); + await AddonPrivateFilesHelper.uploadPrivateFile(this.filesInfo); // File uploaded, refresh the list. this.filesLoaded = false; - await CoreUtils.instance.ignoreErrors(this.refreshFiles()); + await CoreUtils.ignoreErrors(this.refreshFiles()); this.filesLoaded = true; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.fileuploader.errorwhileuploading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.fileuploader.errorwhileuploading', true); } } @@ -179,38 +179,38 @@ export class AddonPrivateFilesIndexPage implements OnInit, OnDestroy { try { if (this.path) { // Path is set, serve the files the user requested. - this.files = await AddonPrivateFiles.instance.getFiles(this.path); + this.files = await AddonPrivateFiles.getFiles(this.path); return; } // The path is unknown, the user must be requesting a root. if (this.root == 'site') { - this.title = Translate.instance.instant('addon.privatefiles.sitefiles'); + this.title = Translate.instant('addon.privatefiles.sitefiles'); - this.files = await AddonPrivateFiles.instance.getSiteFiles(); + this.files = await AddonPrivateFiles.getSiteFiles(); } else if (this.root == 'my') { - this.title = Translate.instance.instant('addon.privatefiles.files'); + this.title = Translate.instant('addon.privatefiles.files'); - this.files = await AddonPrivateFiles.instance.getPrivateFiles(); + this.files = await AddonPrivateFiles.getPrivateFiles(); - if (this.showUpload && AddonPrivateFiles.instance.canGetPrivateFilesInfo() && this.userQuota && + if (this.showUpload && AddonPrivateFiles.canGetPrivateFilesInfo() && this.userQuota && this.userQuota > 0) { // Get the info to calculate the available size. - this.filesInfo = await AddonPrivateFiles.instance.getPrivateFilesInfo(); + this.filesInfo = await AddonPrivateFiles.getPrivateFilesInfo(); - this.spaceUsed = CoreTextUtils.instance.bytesToSize(this.filesInfo.filesizewithoutreferences, 1); - this.userQuotaReadable = CoreTextUtils.instance.bytesToSize(this.userQuota, 1); + this.spaceUsed = CoreTextUtils.bytesToSize(this.filesInfo.filesizewithoutreferences, 1); + this.userQuotaReadable = CoreTextUtils.bytesToSize(this.userQuota, 1); } else { // User quota isn't useful, delete it. delete this.userQuota; } } else { // Unknown root. - CoreDomUtils.instance.showErrorModal('addon.privatefiles.couldnotloadfiles', true); + CoreDomUtils.showErrorModal('addon.privatefiles.couldnotloadfiles', true); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'addon.privatefiles.couldnotloadfiles', true); + CoreDomUtils.showErrorModalDefault(error, 'addon.privatefiles.couldnotloadfiles', true); } } @@ -222,8 +222,8 @@ export class AddonPrivateFilesIndexPage implements OnInit, OnDestroy { protected async refreshFiles(): Promise { try { await Promise.all([ - AddonPrivateFiles.instance.invalidateDirectory(this.root, this.path), - AddonPrivateFiles.instance.invalidatePrivateFilesInfoForUser(), + AddonPrivateFiles.invalidateDirectory(this.root, this.path), + AddonPrivateFiles.invalidatePrivateFilesInfoForUser(), ]); } finally { await this.fetchFiles(); @@ -252,7 +252,7 @@ export class AddonPrivateFilesIndexPage implements OnInit, OnDestroy { const hash = Md5.hashAsciiStr(JSON.stringify(params)); - CoreNavigator.instance.navigate(`../${hash}`, { params }); + CoreNavigator.navigate(`../${hash}`, { params }); } /** diff --git a/src/addons/privatefiles/privatefiles.module.ts b/src/addons/privatefiles/privatefiles.module.ts index 3ea3bf1a7..b329899ea 100644 --- a/src/addons/privatefiles/privatefiles.module.ts +++ b/src/addons/privatefiles/privatefiles.module.ts @@ -39,7 +39,7 @@ const routes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreMainMenuDelegate.instance.registerHandler(AddonPrivateFilesMainMenuHandler.instance); + CoreMainMenuDelegate.registerHandler(AddonPrivateFilesMainMenuHandler.instance); }, }, ], diff --git a/src/addons/privatefiles/services/handlers/mainmenu.ts b/src/addons/privatefiles/services/handlers/mainmenu.ts index 2adfe081c..5b8015217 100644 --- a/src/addons/privatefiles/services/handlers/mainmenu.ts +++ b/src/addons/privatefiles/services/handlers/mainmenu.ts @@ -35,7 +35,7 @@ export class AddonPrivateFilesMainMenuHandlerService implements CoreMainMenuHand * @return Whether or not the handler is enabled on a site level. */ async isEnabled(): Promise { - return AddonPrivateFiles.instance.isPluginEnabled(); + return AddonPrivateFiles.isPluginEnabled(); } /** @@ -55,4 +55,4 @@ export class AddonPrivateFilesMainMenuHandlerService implements CoreMainMenuHand } -export class AddonPrivateFilesMainMenuHandler extends makeSingleton(AddonPrivateFilesMainMenuHandlerService) {} +export const AddonPrivateFilesMainMenuHandler = makeSingleton(AddonPrivateFilesMainMenuHandlerService); diff --git a/src/addons/privatefiles/services/privatefiles-helper.ts b/src/addons/privatefiles/services/privatefiles-helper.ts index 096ae2e39..e4032e01a 100644 --- a/src/addons/privatefiles/services/privatefiles-helper.ts +++ b/src/addons/privatefiles/services/privatefiles-helper.ts @@ -35,7 +35,7 @@ export class AddonPrivateFilesHelperProvider { */ async uploadPrivateFile(info?: AddonPrivateFilesGetUserInfoWSResult): Promise { // Calculate the max size. - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); let maxSize = currentSite?.getInfo()?.usermaxuploadfilesize || -1; let userQuota = currentSite?.getInfo()?.userquota; @@ -52,19 +52,19 @@ export class AddonPrivateFilesHelperProvider { } // Select and upload the file. - const result = await CoreFileUploaderHelper.instance.selectAndUploadFile(maxSize); + const result = await CoreFileUploaderHelper.selectAndUploadFile(maxSize); if (!result) { - throw new CoreError(Translate.instance.instant('core.fileuploader.errorwhileuploading')); + throw new CoreError(Translate.instant('core.fileuploader.errorwhileuploading')); } // File uploaded. Move it to private files. - const modal = await CoreDomUtils.instance.showModalLoading('core.fileuploader.uploading', true); + const modal = await CoreDomUtils.showModalLoading('core.fileuploader.uploading', true); try { - await AddonPrivateFiles.instance.moveFromDraftToPrivate(result.itemid); + await AddonPrivateFiles.moveFromDraftToPrivate(result.itemid); - CoreDomUtils.instance.showToast('core.fileuploader.fileuploaded', true, undefined, 'core-toast-success'); + CoreDomUtils.showToast('core.fileuploader.fileuploaded', true, undefined, 'core-toast-success'); } finally { modal.dismiss(); } @@ -72,4 +72,4 @@ export class AddonPrivateFilesHelperProvider { } -export class AddonPrivateFilesHelper extends makeSingleton(AddonPrivateFilesHelperProvider) {} +export const AddonPrivateFilesHelper = makeSingleton(AddonPrivateFilesHelperProvider); diff --git a/src/addons/privatefiles/services/privatefiles.ts b/src/addons/privatefiles/services/privatefiles.ts index 04a0f27e9..0af06f08f 100644 --- a/src/addons/privatefiles/services/privatefiles.ts +++ b/src/addons/privatefiles/services/privatefiles.ts @@ -38,7 +38,7 @@ export class AddonPrivateFilesProvider { * @return Whether the WS is available, false otherwise. */ canGetPrivateFilesInfo(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('core_user_get_private_files_info'); + return CoreSites.wsAvailableInCurrentSite('core_user_get_private_files_info'); } /** @@ -47,7 +47,7 @@ export class AddonPrivateFilesProvider { * @return Whether the user can view his private files. */ canViewPrivateFiles(): boolean { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); if (!currentSite) { return false; } @@ -70,7 +70,7 @@ export class AddonPrivateFilesProvider { * @return Whether the user can upload private files. */ canUploadFiles(): boolean { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); if (!currentSite) { return false; } @@ -87,7 +87,7 @@ export class AddonPrivateFilesProvider { */ async getFiles(params: AddonPrivateFilesGetFilesWSParams, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets = { cacheKey: this.getFilesListCacheKey(params), @@ -104,9 +104,9 @@ export class AddonPrivateFilesProvider { entry.fileurl = entry.url; if (entry.isdir) { - entry.imgPath = CoreMimetypeUtils.instance.getFolderIcon(); + entry.imgPath = CoreMimetypeUtils.getFolderIcon(); } else { - entry.imgPath = CoreMimetypeUtils.instance.getFileIcon(entry.filename); + entry.imgPath = CoreMimetypeUtils.getFileIcon(entry.filename); } return entry; @@ -146,7 +146,7 @@ export class AddonPrivateFilesProvider { component: 'user', filearea: 'private', contextlevel: 'user', - instanceid: CoreSites.instance.getCurrentSite()?.getUserId(), + instanceid: CoreSites.getCurrentSite()?.getUserId(), itemid: 0, filepath: '', filename: '', @@ -161,7 +161,7 @@ export class AddonPrivateFilesProvider { * @return Promise resolved with the info. */ async getPrivateFilesInfo(userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -241,7 +241,7 @@ export class AddonPrivateFilesProvider { } } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getFilesListCacheKey(params)); } @@ -253,7 +253,7 @@ export class AddonPrivateFilesProvider { * @return Promise resolved when the data is invalidated. */ async invalidatePrivateFilesInfo(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getPrivateFilesInfoCommonCacheKey()); } @@ -266,7 +266,7 @@ export class AddonPrivateFilesProvider { * @return Promise resolved when the data is invalidated. */ async invalidatePrivateFilesInfoForUser(userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getPrivateFilesInfoCacheKey(userId || site.getUserId())); } @@ -278,7 +278,7 @@ export class AddonPrivateFilesProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isDisabledInSite(site); } @@ -290,7 +290,7 @@ export class AddonPrivateFilesProvider { * @return Whether it's disabled. */ isDisabledInSite(site: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return site.isFeatureDisabled('CoreMainMenuDelegate_AddonPrivateFiles'); } @@ -311,7 +311,7 @@ export class AddonPrivateFilesProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isPrivateFilesDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isPrivateFilesDisabledInSite(site); } @@ -323,7 +323,7 @@ export class AddonPrivateFilesProvider { * @return Whether it's disabled. */ isPrivateFilesDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site && site.isFeatureDisabled('AddonPrivateFilesPrivateFiles'); } @@ -335,7 +335,7 @@ export class AddonPrivateFilesProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isSiteFilesDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isSiteFilesDisabledInSite(site); } @@ -347,7 +347,7 @@ export class AddonPrivateFilesProvider { * @return Whether it's disabled. */ isSiteFilesDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site && site.isFeatureDisabled('AddonPrivateFilesSiteFiles'); } @@ -359,7 +359,7 @@ export class AddonPrivateFilesProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isUploadDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isUploadDisabledInSite(site); } @@ -371,7 +371,7 @@ export class AddonPrivateFilesProvider { * @return Whether it's disabled. */ isUploadDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site && site.isFeatureDisabled('AddonPrivateFilesUpload'); } @@ -391,7 +391,7 @@ export class AddonPrivateFilesProvider { responseExpected: false, }; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.write('core_user_add_user_private_files', params, preSets); } @@ -403,7 +403,7 @@ export class AddonPrivateFilesProvider { * @return Promise resolved with true if WS is working, false otherwise. */ async versionCanUploadFiles(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Upload private files doesn't work for Moodle 3.1.0 due to a bug. return site.isVersionGreaterEqualThan('3.1.1'); @@ -411,7 +411,7 @@ export class AddonPrivateFilesProvider { } -export class AddonPrivateFiles extends makeSingleton(AddonPrivateFilesProvider) {} +export const AddonPrivateFiles = makeSingleton(AddonPrivateFilesProvider); /** * File data returned by core_files_get_files. diff --git a/src/addons/qbehaviour/adaptive/adaptive.module.ts b/src/addons/qbehaviour/adaptive/adaptive.module.ts index 7858d6057..f0d6b50b8 100644 --- a/src/addons/qbehaviour/adaptive/adaptive.module.ts +++ b/src/addons/qbehaviour/adaptive/adaptive.module.ts @@ -25,7 +25,7 @@ import { AddonQbehaviourAdaptiveHandler } from './services/handlers/adaptive'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourAdaptiveHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourAdaptiveHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/adaptive/services/handlers/adaptive.ts b/src/addons/qbehaviour/adaptive/services/handlers/adaptive.ts index 4c10c6023..9829fb062 100644 --- a/src/addons/qbehaviour/adaptive/services/handlers/adaptive.ts +++ b/src/addons/qbehaviour/adaptive/services/handlers/adaptive.ts @@ -39,7 +39,7 @@ export class AddonQbehaviourAdaptiveHandlerService implements CoreQuestionBehavi */ handleQuestion(question: CoreQuestionQuestionParsed): void { // Just extract the button, it doesn't need any specific component. - CoreQuestionHelper.instance.extractQbehaviourButtons(question); + CoreQuestionHelper.extractQbehaviourButtons(question); } /** @@ -53,4 +53,4 @@ export class AddonQbehaviourAdaptiveHandlerService implements CoreQuestionBehavi } -export class AddonQbehaviourAdaptiveHandler extends makeSingleton(AddonQbehaviourAdaptiveHandlerService) {} +export const AddonQbehaviourAdaptiveHandler = makeSingleton(AddonQbehaviourAdaptiveHandlerService); diff --git a/src/addons/qbehaviour/adaptivenopenalty/adaptivenopenalty.module.ts b/src/addons/qbehaviour/adaptivenopenalty/adaptivenopenalty.module.ts index c8de10ff7..521c2139f 100644 --- a/src/addons/qbehaviour/adaptivenopenalty/adaptivenopenalty.module.ts +++ b/src/addons/qbehaviour/adaptivenopenalty/adaptivenopenalty.module.ts @@ -26,7 +26,7 @@ import { AddonQbehaviourAdaptiveNoPenaltyHandler } from './services/handlers/ada multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourAdaptiveNoPenaltyHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourAdaptiveNoPenaltyHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/adaptivenopenalty/services/handlers/adaptivenopenalty.ts b/src/addons/qbehaviour/adaptivenopenalty/services/handlers/adaptivenopenalty.ts index 85af22bb1..9c9abc641 100644 --- a/src/addons/qbehaviour/adaptivenopenalty/services/handlers/adaptivenopenalty.ts +++ b/src/addons/qbehaviour/adaptivenopenalty/services/handlers/adaptivenopenalty.ts @@ -39,7 +39,7 @@ export class AddonQbehaviourAdaptiveNoPenaltyHandlerService implements CoreQuest */ handleQuestion(question: CoreQuestionQuestionParsed): void { // Just extract the button, it doesn't need any specific component. - CoreQuestionHelper.instance.extractQbehaviourButtons(question); + CoreQuestionHelper.extractQbehaviourButtons(question); } /** @@ -53,4 +53,4 @@ export class AddonQbehaviourAdaptiveNoPenaltyHandlerService implements CoreQuest } -export class AddonQbehaviourAdaptiveNoPenaltyHandler extends makeSingleton(AddonQbehaviourAdaptiveNoPenaltyHandlerService) {} +export const AddonQbehaviourAdaptiveNoPenaltyHandler = makeSingleton(AddonQbehaviourAdaptiveNoPenaltyHandlerService); diff --git a/src/addons/qbehaviour/deferredcbm/deferredcbm.module.ts b/src/addons/qbehaviour/deferredcbm/deferredcbm.module.ts index 112c32e42..94e8e2c1c 100644 --- a/src/addons/qbehaviour/deferredcbm/deferredcbm.module.ts +++ b/src/addons/qbehaviour/deferredcbm/deferredcbm.module.ts @@ -32,7 +32,7 @@ import { AddonQbehaviourDeferredCBMHandler } from './services/handlers/deferredc multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourDeferredCBMHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourDeferredCBMHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/deferredcbm/services/handlers/deferredcbm.ts b/src/addons/qbehaviour/deferredcbm/services/handlers/deferredcbm.ts index a2a2c0bb9..c4af00249 100644 --- a/src/addons/qbehaviour/deferredcbm/services/handlers/deferredcbm.ts +++ b/src/addons/qbehaviour/deferredcbm/services/handlers/deferredcbm.ts @@ -49,7 +49,7 @@ export class AddonQbehaviourDeferredCBMHandlerService implements CoreQuestionBeh siteId?: string, ): CoreQuestionState | Promise { // Depends on deferredfeedback. - return AddonQbehaviourDeferredFeedbackHandler.instance.determineNewStateDeferred( + return AddonQbehaviourDeferredFeedbackHandler.determineNewStateDeferred( component, attemptId, question, @@ -70,7 +70,7 @@ export class AddonQbehaviourDeferredCBMHandlerService implements CoreQuestionBeh * (e.g. certainty options). Don't return anything if no extra data is required. */ handleQuestion(question: CoreQuestionQuestionParsed): void | Type[] { - if (CoreQuestionHelper.instance.extractQbehaviourCBM(question)) { + if (CoreQuestionHelper.extractQbehaviourCBM(question)) { return [AddonQbehaviourDeferredCBMComponent]; } } @@ -91,7 +91,7 @@ export class AddonQbehaviourDeferredCBMHandlerService implements CoreQuestionBeh componentId: string | number, ): number { // First check if the question answer is complete. - const complete = CoreQuestionDelegate.instance.isCompleteResponse(question, answers, component, componentId); + const complete = CoreQuestionDelegate.isCompleteResponse(question, answers, component, componentId); if (complete > 0) { // Answer is complete, check the user answered CBM too. return answers['-certainty'] ? 1 : 0; @@ -131,7 +131,7 @@ export class AddonQbehaviourDeferredCBMHandlerService implements CoreQuestionBeh componentId: string | number, ): boolean { // First check if the question answer is the same. - const sameResponse = CoreQuestionDelegate.instance.isSameResponse( + const sameResponse = CoreQuestionDelegate.isSameResponse( question, prevBasicAnswers, newBasicAnswers, @@ -149,4 +149,4 @@ export class AddonQbehaviourDeferredCBMHandlerService implements CoreQuestionBeh } -export class AddonQbehaviourDeferredCBMHandler extends makeSingleton(AddonQbehaviourDeferredCBMHandlerService) {} +export const AddonQbehaviourDeferredCBMHandler = makeSingleton(AddonQbehaviourDeferredCBMHandlerService); diff --git a/src/addons/qbehaviour/deferredfeedback/deferredfeedback.module.ts b/src/addons/qbehaviour/deferredfeedback/deferredfeedback.module.ts index 811f8dd00..8ec75de4a 100644 --- a/src/addons/qbehaviour/deferredfeedback/deferredfeedback.module.ts +++ b/src/addons/qbehaviour/deferredfeedback/deferredfeedback.module.ts @@ -25,7 +25,7 @@ import { AddonQbehaviourDeferredFeedbackHandler } from './services/handlers/defe multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourDeferredFeedbackHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourDeferredFeedbackHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/deferredfeedback/services/handlers/deferredfeedback.ts b/src/addons/qbehaviour/deferredfeedback/services/handlers/deferredfeedback.ts index 6f536532a..3d92e0396 100644 --- a/src/addons/qbehaviour/deferredfeedback/services/handlers/deferredfeedback.ts +++ b/src/addons/qbehaviour/deferredfeedback/services/handlers/deferredfeedback.ts @@ -79,31 +79,31 @@ export class AddonQbehaviourDeferredFeedbackHandlerService implements CoreQuesti // Check if we have local data for the question. let dbQuestion: CoreQuestionDBRecord | CoreQuestionQuestionWithAnswers = question; try { - dbQuestion = await CoreQuestion.instance.getQuestion(component, attemptId, question.slot, siteId); + dbQuestion = await CoreQuestion.getQuestion(component, attemptId, question.slot, siteId); } catch (error) { // No entry found, use the original data. } - const state = CoreQuestion.instance.getState(dbQuestion.state); + const state = CoreQuestion.getState(dbQuestion.state); if (state.finished || !state.active) { // Question is finished, it cannot change. return state; } - const newBasicAnswers = CoreQuestion.instance.getBasicAnswers(question.answers || {}); + const newBasicAnswers = CoreQuestion.getBasicAnswers(question.answers || {}); if (dbQuestion.state) { // Question already has a state stored. Check if answer has changed. - const prevAnswersList = await CoreQuestion.instance.getQuestionAnswers( + const prevAnswersList = await CoreQuestion.getQuestionAnswers( component, attemptId, question.slot, false, siteId, ); - const prevAnswers = CoreQuestion.instance.convertAnswersArrayToObject(prevAnswersList, true); - const prevBasicAnswers = CoreQuestion.instance.getBasicAnswers(prevAnswers); + const prevAnswers = CoreQuestion.convertAnswersArrayToObject(prevAnswersList, true); + const prevBasicAnswers = CoreQuestion.getBasicAnswers(prevAnswers); // If answers haven't changed the state is the same. let sameResponse = false; @@ -119,7 +119,7 @@ export class AddonQbehaviourDeferredFeedbackHandlerService implements CoreQuesti componentId, ); } else { - sameResponse = CoreQuestionDelegate.instance.isSameResponse( + sameResponse = CoreQuestionDelegate.isSameResponse( question, prevBasicAnswers, newBasicAnswers, @@ -142,7 +142,7 @@ export class AddonQbehaviourDeferredFeedbackHandlerService implements CoreQuesti complete = isCompleteFn(question, question.answers || {}, component, componentId); } else { // Only pass the basic answers since questions should be independent of extra data. - complete = CoreQuestionDelegate.instance.isCompleteResponse(question, newBasicAnswers, component, componentId); + complete = CoreQuestionDelegate.isCompleteResponse(question, newBasicAnswers, component, componentId); } if (complete < 0) { @@ -150,7 +150,7 @@ export class AddonQbehaviourDeferredFeedbackHandlerService implements CoreQuesti } else if (complete > 0) { newState = 'complete'; } else { - const gradable = CoreQuestionDelegate.instance.isGradableResponse(question, newBasicAnswers, component, componentId); + const gradable = CoreQuestionDelegate.isGradableResponse(question, newBasicAnswers, component, componentId); if (gradable < 0) { newState = 'cannotdeterminestatus'; } else if (gradable > 0) { @@ -160,7 +160,7 @@ export class AddonQbehaviourDeferredFeedbackHandlerService implements CoreQuesti } } - return CoreQuestion.instance.getState(newState); + return CoreQuestion.getState(newState); } /** @@ -174,7 +174,7 @@ export class AddonQbehaviourDeferredFeedbackHandlerService implements CoreQuesti } -export class AddonQbehaviourDeferredFeedbackHandler extends makeSingleton(AddonQbehaviourDeferredFeedbackHandlerService) {} +export const AddonQbehaviourDeferredFeedbackHandler = makeSingleton(AddonQbehaviourDeferredFeedbackHandlerService); /** diff --git a/src/addons/qbehaviour/immediatecbm/immediatecbm.module.ts b/src/addons/qbehaviour/immediatecbm/immediatecbm.module.ts index adcc19d47..c5bc7d5a9 100644 --- a/src/addons/qbehaviour/immediatecbm/immediatecbm.module.ts +++ b/src/addons/qbehaviour/immediatecbm/immediatecbm.module.ts @@ -26,7 +26,7 @@ import { AddonQbehaviourImmediateCBMHandler } from './services/handlers/immediat multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourImmediateCBMHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourImmediateCBMHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/immediatecbm/services/handlers/immediatecbm.ts b/src/addons/qbehaviour/immediatecbm/services/handlers/immediatecbm.ts index 243e2c42c..6037d96d7 100644 --- a/src/addons/qbehaviour/immediatecbm/services/handlers/immediatecbm.ts +++ b/src/addons/qbehaviour/immediatecbm/services/handlers/immediatecbm.ts @@ -39,9 +39,9 @@ export class AddonQbehaviourImmediateCBMHandlerService implements CoreQuestionBe * (e.g. certainty options). Don't return anything if no extra data is required. */ handleQuestion(question: CoreQuestionQuestionParsed): void | Type[] { - CoreQuestionHelper.instance.extractQbehaviourButtons(question); + CoreQuestionHelper.extractQbehaviourButtons(question); - if (CoreQuestionHelper.instance.extractQbehaviourCBM(question)) { + if (CoreQuestionHelper.extractQbehaviourCBM(question)) { // Depends on deferredcbm. return [AddonQbehaviourDeferredCBMComponent]; } @@ -58,4 +58,4 @@ export class AddonQbehaviourImmediateCBMHandlerService implements CoreQuestionBe } -export class AddonQbehaviourImmediateCBMHandler extends makeSingleton(AddonQbehaviourImmediateCBMHandlerService) {} +export const AddonQbehaviourImmediateCBMHandler = makeSingleton(AddonQbehaviourImmediateCBMHandlerService); diff --git a/src/addons/qbehaviour/immediatefeedback/immediatefeedback.module.ts b/src/addons/qbehaviour/immediatefeedback/immediatefeedback.module.ts index 617fd6b1c..99e137d95 100644 --- a/src/addons/qbehaviour/immediatefeedback/immediatefeedback.module.ts +++ b/src/addons/qbehaviour/immediatefeedback/immediatefeedback.module.ts @@ -26,7 +26,7 @@ import { AddonQbehaviourImmediateFeedbackHandler } from './services/handlers/imm multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourImmediateFeedbackHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourImmediateFeedbackHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/immediatefeedback/services/handlers/immediatefeedback.ts b/src/addons/qbehaviour/immediatefeedback/services/handlers/immediatefeedback.ts index c3d542c48..5e1f6b638 100644 --- a/src/addons/qbehaviour/immediatefeedback/services/handlers/immediatefeedback.ts +++ b/src/addons/qbehaviour/immediatefeedback/services/handlers/immediatefeedback.ts @@ -39,7 +39,7 @@ export class AddonQbehaviourImmediateFeedbackHandlerService implements CoreQuest */ handleQuestion(question: CoreQuestionQuestionParsed): void { // Just extract the button, it doesn't need any specific component. - CoreQuestionHelper.instance.extractQbehaviourButtons(question); + CoreQuestionHelper.extractQbehaviourButtons(question); return; } @@ -55,4 +55,4 @@ export class AddonQbehaviourImmediateFeedbackHandlerService implements CoreQuest } -export class AddonQbehaviourImmediateFeedbackHandler extends makeSingleton(AddonQbehaviourImmediateFeedbackHandlerService) {} +export const AddonQbehaviourImmediateFeedbackHandler = makeSingleton(AddonQbehaviourImmediateFeedbackHandlerService); diff --git a/src/addons/qbehaviour/informationitem/informationitem.module.ts b/src/addons/qbehaviour/informationitem/informationitem.module.ts index eab461bc9..c72b94676 100644 --- a/src/addons/qbehaviour/informationitem/informationitem.module.ts +++ b/src/addons/qbehaviour/informationitem/informationitem.module.ts @@ -32,7 +32,7 @@ import { AddonQbehaviourInformationItemHandler } from './services/handlers/infor multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourInformationItemHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourInformationItemHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/informationitem/services/handlers/informationitem.ts b/src/addons/qbehaviour/informationitem/services/handlers/informationitem.ts index 6ae1aabc8..a6e2b61aa 100644 --- a/src/addons/qbehaviour/informationitem/services/handlers/informationitem.ts +++ b/src/addons/qbehaviour/informationitem/services/handlers/informationitem.ts @@ -45,10 +45,10 @@ export class AddonQbehaviourInformationItemHandlerService implements CoreQuestio question: CoreQuestionQuestionWithAnswers, ): CoreQuestionState | Promise { if (question.answers?.['-seen']) { - return CoreQuestion.instance.getState('complete'); + return CoreQuestion.getState('complete'); } - return CoreQuestion.instance.getState(question.state || 'todo'); + return CoreQuestion.getState(question.state || 'todo'); } /** @@ -61,7 +61,7 @@ export class AddonQbehaviourInformationItemHandlerService implements CoreQuestio * (e.g. certainty options). Don't return anything if no extra data is required. */ handleQuestion(question: CoreQuestionQuestionParsed): void | Type[] { - if (CoreQuestionHelper.instance.extractQbehaviourSeenInput(question)) { + if (CoreQuestionHelper.extractQbehaviourSeenInput(question)) { return [AddonQbehaviourInformationItemComponent]; } } @@ -77,4 +77,4 @@ export class AddonQbehaviourInformationItemHandlerService implements CoreQuestio } -export class AddonQbehaviourInformationItemHandler extends makeSingleton(AddonQbehaviourInformationItemHandlerService) {} +export const AddonQbehaviourInformationItemHandler = makeSingleton(AddonQbehaviourInformationItemHandlerService); diff --git a/src/addons/qbehaviour/interactive/interactive.module.ts b/src/addons/qbehaviour/interactive/interactive.module.ts index 4f79ea766..421f6ab4e 100644 --- a/src/addons/qbehaviour/interactive/interactive.module.ts +++ b/src/addons/qbehaviour/interactive/interactive.module.ts @@ -26,7 +26,7 @@ import { AddonQbehaviourInteractiveHandler } from './services/handlers/interacti multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourInteractiveHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourInteractiveHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/interactive/services/handlers/interactive.ts b/src/addons/qbehaviour/interactive/services/handlers/interactive.ts index aa934d7b5..410144893 100644 --- a/src/addons/qbehaviour/interactive/services/handlers/interactive.ts +++ b/src/addons/qbehaviour/interactive/services/handlers/interactive.ts @@ -39,7 +39,7 @@ export class AddonQbehaviourInteractiveHandlerService implements CoreQuestionBeh */ handleQuestion(question: CoreQuestionQuestionParsed): void { // Just extract the button, it doesn't need any specific component. - CoreQuestionHelper.instance.extractQbehaviourButtons(question); + CoreQuestionHelper.extractQbehaviourButtons(question); } /** @@ -53,4 +53,4 @@ export class AddonQbehaviourInteractiveHandlerService implements CoreQuestionBeh } -export class AddonQbehaviourInteractiveHandler extends makeSingleton(AddonQbehaviourInteractiveHandlerService) {} +export const AddonQbehaviourInteractiveHandler = makeSingleton(AddonQbehaviourInteractiveHandlerService); diff --git a/src/addons/qbehaviour/interactivecountback/interactivecountback.module.ts b/src/addons/qbehaviour/interactivecountback/interactivecountback.module.ts index 1b74410ff..161b1c5a1 100644 --- a/src/addons/qbehaviour/interactivecountback/interactivecountback.module.ts +++ b/src/addons/qbehaviour/interactivecountback/interactivecountback.module.ts @@ -26,7 +26,7 @@ import { AddonQbehaviourInteractiveCountbackHandler } from './services/handlers/ multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourInteractiveCountbackHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourInteractiveCountbackHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/interactivecountback/services/handlers/interactivecountback.ts b/src/addons/qbehaviour/interactivecountback/services/handlers/interactivecountback.ts index 9baebd181..5edc89f41 100644 --- a/src/addons/qbehaviour/interactivecountback/services/handlers/interactivecountback.ts +++ b/src/addons/qbehaviour/interactivecountback/services/handlers/interactivecountback.ts @@ -39,7 +39,7 @@ export class AddonQbehaviourInteractiveCountbackHandlerService implements CoreQu */ handleQuestion(question: CoreQuestionQuestionParsed): void { // Just extract the button, it doesn't need any specific component. - CoreQuestionHelper.instance.extractQbehaviourButtons(question); + CoreQuestionHelper.extractQbehaviourButtons(question); } /** @@ -53,4 +53,4 @@ export class AddonQbehaviourInteractiveCountbackHandlerService implements CoreQu } -export class AddonQbehaviourInteractiveCountbackHandler extends makeSingleton(AddonQbehaviourInteractiveCountbackHandlerService) {} +export const AddonQbehaviourInteractiveCountbackHandler = makeSingleton(AddonQbehaviourInteractiveCountbackHandlerService); diff --git a/src/addons/qbehaviour/manualgraded/manualgraded.module.ts b/src/addons/qbehaviour/manualgraded/manualgraded.module.ts index a1a2e5deb..45582465f 100644 --- a/src/addons/qbehaviour/manualgraded/manualgraded.module.ts +++ b/src/addons/qbehaviour/manualgraded/manualgraded.module.ts @@ -26,7 +26,7 @@ import { AddonQbehaviourManualGradedHandler } from './services/handlers/manualgr multi: true, deps: [], useFactory: () => () => { - CoreQuestionBehaviourDelegate.instance.registerHandler(AddonQbehaviourManualGradedHandler.instance); + CoreQuestionBehaviourDelegate.registerHandler(AddonQbehaviourManualGradedHandler.instance); }, }, ], diff --git a/src/addons/qbehaviour/manualgraded/services/handlers/manualgraded.ts b/src/addons/qbehaviour/manualgraded/services/handlers/manualgraded.ts index 44ec70460..59ec623f5 100644 --- a/src/addons/qbehaviour/manualgraded/services/handlers/manualgraded.ts +++ b/src/addons/qbehaviour/manualgraded/services/handlers/manualgraded.ts @@ -46,7 +46,7 @@ export class AddonQbehaviourManualGradedHandlerService implements CoreQuestionBe siteId?: string, ): CoreQuestionState | Promise { // Same implementation as the deferred feedback. Use that function instead of replicating it. - return AddonQbehaviourDeferredFeedbackHandler.instance.determineNewStateDeferred( + return AddonQbehaviourDeferredFeedbackHandler.determineNewStateDeferred( component, attemptId, question, @@ -66,4 +66,4 @@ export class AddonQbehaviourManualGradedHandlerService implements CoreQuestionBe } -export class AddonQbehaviourManualGradedHandler extends makeSingleton(AddonQbehaviourManualGradedHandlerService) {} +export const AddonQbehaviourManualGradedHandler = makeSingleton(AddonQbehaviourManualGradedHandlerService); diff --git a/src/addons/qtype/calculated/calculated.module.ts b/src/addons/qtype/calculated/calculated.module.ts index ce8213b38..d140819ab 100644 --- a/src/addons/qtype/calculated/calculated.module.ts +++ b/src/addons/qtype/calculated/calculated.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeCalculatedHandler } from './services/handlers/calculated'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeCalculatedHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeCalculatedHandler.instance); }, }, ], diff --git a/src/addons/qtype/calculated/services/handlers/calculated.ts b/src/addons/qtype/calculated/services/handlers/calculated.ts index 6115b425f..cac9c191d 100644 --- a/src/addons/qtype/calculated/services/handlers/calculated.ts +++ b/src/addons/qtype/calculated/services/handlers/calculated.ts @@ -57,7 +57,7 @@ export class AddonQtypeCalculatedHandlerService implements CoreQuestionHandler { */ hasSeparateUnitField(question: CoreQuestionQuestionParsed): boolean { if (!question.parsedSettings) { - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); return !!(element.querySelector('select[name*=unit]') || element.querySelector('input[type="radio"]')); } @@ -164,8 +164,8 @@ export class AddonQtypeCalculatedHandlerService implements CoreQuestionHandler { component: string, // eslint-disable-line @typescript-eslint/no-unused-vars componentId: string | number, // eslint-disable-line @typescript-eslint/no-unused-vars ): boolean { - return CoreUtils.instance.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer') && - CoreUtils.instance.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'unit'); + return CoreUtils.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer') && + CoreUtils.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'unit'); } /** @@ -234,4 +234,4 @@ export class AddonQtypeCalculatedHandlerService implements CoreQuestionHandler { } -export class AddonQtypeCalculatedHandler extends makeSingleton(AddonQtypeCalculatedHandlerService) {} +export const AddonQtypeCalculatedHandler = makeSingleton(AddonQtypeCalculatedHandlerService); diff --git a/src/addons/qtype/calculatedmulti/calculatedmulti.module.ts b/src/addons/qtype/calculatedmulti/calculatedmulti.module.ts index 3ae73755f..cbe7d1829 100644 --- a/src/addons/qtype/calculatedmulti/calculatedmulti.module.ts +++ b/src/addons/qtype/calculatedmulti/calculatedmulti.module.ts @@ -26,7 +26,7 @@ import { AddonQtypeCalculatedMultiHandler } from './services/handlers/calculated multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeCalculatedMultiHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeCalculatedMultiHandler.instance); }, }, ], diff --git a/src/addons/qtype/calculatedmulti/services/handlers/calculatedmulti.ts b/src/addons/qtype/calculatedmulti/services/handlers/calculatedmulti.ts index 832271cde..100beb0f7 100644 --- a/src/addons/qtype/calculatedmulti/services/handlers/calculatedmulti.ts +++ b/src/addons/qtype/calculatedmulti/services/handlers/calculatedmulti.ts @@ -55,7 +55,7 @@ export class AddonQtypeCalculatedMultiHandlerService implements CoreQuestionHand answers: CoreQuestionsAnswers, ): number { // This question type depends on multichoice. - return AddonQtypeMultichoiceHandler.instance.isCompleteResponseSingle(answers); + return AddonQtypeMultichoiceHandler.isCompleteResponseSingle(answers); } /** @@ -82,7 +82,7 @@ export class AddonQtypeCalculatedMultiHandlerService implements CoreQuestionHand answers: CoreQuestionsAnswers, ): number { // This question type depends on multichoice. - return AddonQtypeMultichoiceHandler.instance.isGradableResponseSingle(answers); + return AddonQtypeMultichoiceHandler.isGradableResponseSingle(answers); } /** @@ -101,9 +101,9 @@ export class AddonQtypeCalculatedMultiHandlerService implements CoreQuestionHand newAnswers: CoreQuestionsAnswers, ): boolean { // This question type depends on multichoice. - return AddonQtypeMultichoiceHandler.instance.isSameResponseSingle(prevAnswers, newAnswers); + return AddonQtypeMultichoiceHandler.isSameResponseSingle(prevAnswers, newAnswers); } } -export class AddonQtypeCalculatedMultiHandler extends makeSingleton(AddonQtypeCalculatedMultiHandlerService) {} +export const AddonQtypeCalculatedMultiHandler = makeSingleton(AddonQtypeCalculatedMultiHandlerService); diff --git a/src/addons/qtype/calculatedsimple/calculatedsimple.module.ts b/src/addons/qtype/calculatedsimple/calculatedsimple.module.ts index c467476d9..9a7b52b18 100644 --- a/src/addons/qtype/calculatedsimple/calculatedsimple.module.ts +++ b/src/addons/qtype/calculatedsimple/calculatedsimple.module.ts @@ -26,7 +26,7 @@ import { AddonQtypeCalculatedSimpleHandler } from './services/handlers/calculate multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeCalculatedSimpleHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeCalculatedSimpleHandler.instance); }, }, ], diff --git a/src/addons/qtype/calculatedsimple/services/handlers/calculatedsimple.ts b/src/addons/qtype/calculatedsimple/services/handlers/calculatedsimple.ts index ddc86597e..2488af0d7 100644 --- a/src/addons/qtype/calculatedsimple/services/handlers/calculatedsimple.ts +++ b/src/addons/qtype/calculatedsimple/services/handlers/calculatedsimple.ts @@ -57,7 +57,7 @@ export class AddonQtypeCalculatedSimpleHandlerService implements CoreQuestionHan componentId: string | number, ): number { // This question type depends on calculated. - return AddonQtypeCalculatedHandler.instance.isCompleteResponse(question, answers, component, componentId); + return AddonQtypeCalculatedHandler.isCompleteResponse(question, answers, component, componentId); } /** @@ -86,7 +86,7 @@ export class AddonQtypeCalculatedSimpleHandlerService implements CoreQuestionHan componentId: string | number, ): number { // This question type depends on calculated. - return AddonQtypeCalculatedHandler.instance.isGradableResponse(question, answers, component, componentId); + return AddonQtypeCalculatedHandler.isGradableResponse(question, answers, component, componentId); } /** @@ -107,9 +107,9 @@ export class AddonQtypeCalculatedSimpleHandlerService implements CoreQuestionHan componentId: string | number, ): boolean { // This question type depends on calculated. - return AddonQtypeCalculatedHandler.instance.isSameResponse(question, prevAnswers, newAnswers, component, componentId); + return AddonQtypeCalculatedHandler.isSameResponse(question, prevAnswers, newAnswers, component, componentId); } } -export class AddonQtypeCalculatedSimpleHandler extends makeSingleton(AddonQtypeCalculatedSimpleHandlerService) {} +export const AddonQtypeCalculatedSimpleHandler = makeSingleton(AddonQtypeCalculatedSimpleHandlerService); diff --git a/src/addons/qtype/ddimageortext/classes/ddimageortext.ts b/src/addons/qtype/ddimageortext/classes/ddimageortext.ts index 2f829f107..506d44b3b 100644 --- a/src/addons/qtype/ddimageortext/classes/ddimageortext.ts +++ b/src/addons/qtype/ddimageortext/classes/ddimageortext.ts @@ -77,7 +77,7 @@ export class AddonQtypeDdImageOrTextQuestion { return bgImgXY; } - const position = CoreDomUtils.instance.getElementXY(bgImg, undefined, 'ddarea'); + const position = CoreDomUtils.getElementXY(bgImg, undefined, 'ddarea'); // Render the position related to the current image dimensions. bgImgXY[0] *= this.proportion; @@ -142,7 +142,7 @@ export class AddonQtypeDdImageOrTextQuestion { } } - await CoreUtils.instance.nextTick(); + await CoreUtils.nextTick(); // All drag items have been created, position them. this.repositionDragsForQuestion(); @@ -409,7 +409,7 @@ export class AddonQtypeDdImageOrTextQuestion { } // Now position the draggable and set it to the input. - const position = CoreDomUtils.instance.getElementXY(drop, undefined, 'ddarea'); + const position = CoreDomUtils.getElementXY(drop, undefined, 'ddarea'); const choice = drag.getAttribute('choice'); drag.style.left = position[0] - 1 + 'px'; drag.style.top = position[1] - 1 + 'px'; @@ -462,7 +462,7 @@ export class AddonQtypeDdImageOrTextQuestion { return; } - const position = CoreDomUtils.instance.getElementXY(dragItemHome, undefined, 'ddarea'); + const position = CoreDomUtils.getElementXY(dragItemHome, undefined, 'ddarea'); drag.style.left = position[0] + 'px'; drag.style.top = position[1] + 'px'; drag.classList.remove('placed'); diff --git a/src/addons/qtype/ddimageortext/component/ddimageortext.ts b/src/addons/qtype/ddimageortext/component/ddimageortext.ts index 72a69ea38..113a500d4 100644 --- a/src/addons/qtype/ddimageortext/component/ddimageortext.ts +++ b/src/addons/qtype/ddimageortext/component/ddimageortext.ts @@ -48,21 +48,21 @@ export class AddonQtypeDdImageOrTextComponent extends CoreQuestionBaseComponent if (!this.question) { this.logger.warn('Aborting because of no question received.'); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } this.ddQuestion = this.question; - const element = CoreDomUtils.instance.convertToElement(this.ddQuestion.html); + const element = CoreDomUtils.convertToElement(this.ddQuestion.html); // Get D&D area and question text. const ddArea = element.querySelector('.ddarea'); - this.ddQuestion.text = CoreDomUtils.instance.getContentsOfElement(element, '.qtext'); + this.ddQuestion.text = CoreDomUtils.getContentsOfElement(element, '.qtext'); if (!ddArea || typeof this.ddQuestion.text == 'undefined') { this.logger.warn('Aborting because of an error parsing question.', this.ddQuestion.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } // Set the D&D area HTML. diff --git a/src/addons/qtype/ddimageortext/ddimageortext.module.ts b/src/addons/qtype/ddimageortext/ddimageortext.module.ts index 77562e67d..68ad009b1 100644 --- a/src/addons/qtype/ddimageortext/ddimageortext.module.ts +++ b/src/addons/qtype/ddimageortext/ddimageortext.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeDdImageOrTextHandler } from './services/handlers/ddimageortex multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeDdImageOrTextHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeDdImageOrTextHandler.instance); }, }, ], diff --git a/src/addons/qtype/ddimageortext/services/handlers/ddimageortext.ts b/src/addons/qtype/ddimageortext/services/handlers/ddimageortext.ts index cceff37ce..02a0b418a 100644 --- a/src/addons/qtype/ddimageortext/services/handlers/ddimageortext.ts +++ b/src/addons/qtype/ddimageortext/services/handlers/ddimageortext.ts @@ -128,9 +128,9 @@ export class AddonQtypeDdImageOrTextHandlerService implements CoreQuestionHandle prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, ): boolean { - return CoreQuestion.instance.compareAllAnswers(prevAnswers, newAnswers); + return CoreQuestion.compareAllAnswers(prevAnswers, newAnswers); } } -export class AddonQtypeDdImageOrTextHandler extends makeSingleton(AddonQtypeDdImageOrTextHandlerService) {} +export const AddonQtypeDdImageOrTextHandler = makeSingleton(AddonQtypeDdImageOrTextHandlerService); diff --git a/src/addons/qtype/ddmarker/classes/ddmarker.ts b/src/addons/qtype/ddmarker/classes/ddmarker.ts index 88d2ebafb..12036b060 100644 --- a/src/addons/qtype/ddmarker/classes/ddmarker.ts +++ b/src/addons/qtype/ddmarker/classes/ddmarker.ts @@ -122,7 +122,7 @@ export class AddonQtypeDdMarkerQuestion { return []; } - const position = CoreDomUtils.instance.getElementXY(bgImg, undefined, 'ddarea'); + const position = CoreDomUtils.getElementXY(bgImg, undefined, 'ddarea'); let coordsNumbers = this.parsePoint(bgImgXY); coordsNumbers = this.makePointProportional(coordsNumbers); @@ -178,13 +178,13 @@ export class AddonQtypeDdMarkerQuestion { const dragging = this.selected; if (dragging && !drag.classList.contains('unplaced')) { - const position = CoreDomUtils.instance.getElementXY(drag, undefined, 'ddarea'); + const position = CoreDomUtils.getElementXY(drag, undefined, 'ddarea'); const bgImg = this.doc.bgImg(); if (!bgImg) { return; } - const bgImgPos = CoreDomUtils.instance.getElementXY(bgImg, undefined, 'ddarea'); + const bgImgPos = CoreDomUtils.getElementXY(bgImg, undefined, 'ddarea'); position[0] = position[0] - bgImgPos[0] + e.offsetX; position[1] = position[1] - bgImgPos[1] + e.offsetY; @@ -218,7 +218,7 @@ export class AddonQtypeDdMarkerQuestion { return []; } - const position = CoreDomUtils.instance.getElementXY(dragItemHome, undefined, 'ddarea'); + const position = CoreDomUtils.getElementXY(dragItemHome, undefined, 'ddarea'); return [position[0], position[1]]; } @@ -256,7 +256,7 @@ export class AddonQtypeDdMarkerQuestion { } // Check that a function to draw this shape exists. - const drawFunc = 'drawShape' + CoreTextUtils.instance.ucFirst(shape); + const drawFunc = 'drawShape' + CoreTextUtils.ucFirst(shape); if (!(this[drawFunc] instanceof Function)) { return; } @@ -273,8 +273,8 @@ export class AddonQtypeDdMarkerQuestion { return; } - const width = CoreDomUtils.instance.getElementMeasure(markerSpan, true, true, false, true); - const height = CoreDomUtils.instance.getElementMeasure(markerSpan, false, true, false, true); + const width = CoreDomUtils.getElementMeasure(markerSpan, true, true, false, true); + const height = CoreDomUtils.getElementMeasure(markerSpan, false, true, false, true); markerSpan.style.opacity = '0.6'; markerSpan.style.left = (xyForText.x - (width / 2)) + 'px'; markerSpan.style.top = (xyForText.y - (height / 2)) + 'px'; @@ -533,10 +533,10 @@ export class AddonQtypeDdMarkerQuestion { * @return Coordinates. */ getDragXY(dragItem: HTMLElement): number[] { - const position = CoreDomUtils.instance.getElementXY(dragItem, undefined, 'ddarea'); + const position = CoreDomUtils.getElementXY(dragItem, undefined, 'ddarea'); const bgImg = this.doc.bgImg(); if (bgImg) { - const bgImgXY = CoreDomUtils.instance.getElementXY(bgImg, undefined, 'ddarea'); + const bgImgXY = CoreDomUtils.getElementXY(bgImg, undefined, 'ddarea'); position[0] -= bgImgXY[0]; position[1] -= bgImgXY[1]; @@ -746,8 +746,8 @@ export class AddonQtypeDdMarkerQuestion { dragItem.classList.add('placed'); const computedStyle = getComputedStyle(dragItem); - const left = coords[i][0] - CoreDomUtils.instance.getComputedStyleMeasure(computedStyle, 'marginLeft'); - const top = coords[i][1] - CoreDomUtils.instance.getComputedStyleMeasure(computedStyle, 'marginTop'); + const left = coords[i][0] - CoreDomUtils.getComputedStyleMeasure(computedStyle, 'marginLeft'); + const top = coords[i][1] - CoreDomUtils.getComputedStyleMeasure(computedStyle, 'marginTop'); dragItem.style.left = left + 'px'; dragItem.style.top = top + 'px'; diff --git a/src/addons/qtype/ddmarker/classes/graphics_api.ts b/src/addons/qtype/ddmarker/classes/graphics_api.ts index 4d69d0108..8ab982905 100644 --- a/src/addons/qtype/ddmarker/classes/graphics_api.ts +++ b/src/addons/qtype/ddmarker/classes/graphics_api.ts @@ -65,7 +65,7 @@ export class AddonQtypeDdMarkerGraphicsApi { return; } - const position = CoreDomUtils.instance.getElementXY(bgImg, undefined, 'ddarea'); + const position = CoreDomUtils.getElementXY(bgImg, undefined, 'ddarea'); dropZones.style.left = position[0] + 'px'; dropZones.style.top = position[1] + 'px'; diff --git a/src/addons/qtype/ddmarker/component/ddmarker.ts b/src/addons/qtype/ddmarker/component/ddmarker.ts index cb61f6d1a..8d4942e8f 100644 --- a/src/addons/qtype/ddmarker/component/ddmarker.ts +++ b/src/addons/qtype/ddmarker/component/ddmarker.ts @@ -54,21 +54,21 @@ export class AddonQtypeDdMarkerComponent extends CoreQuestionBaseComponent imple if (!this.question) { this.logger.warn('Aborting because of no question received.'); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } this.ddQuestion = this.question; - const element = CoreDomUtils.instance.convertToElement(this.question.html); + const element = CoreDomUtils.convertToElement(this.question.html); // Get D&D area, form and question text. const ddArea = element.querySelector('.ddarea'); const ddForm = element.querySelector('.ddform'); - this.ddQuestion.text = CoreDomUtils.instance.getContentsOfElement(element, '.qtext'); + this.ddQuestion.text = CoreDomUtils.getContentsOfElement(element, '.qtext'); if (!ddArea || !ddForm || typeof this.ddQuestion.text == 'undefined') { this.logger.warn('Aborting because of an error parsing question.', this.ddQuestion.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } // Build the D&D area HTML. @@ -140,10 +140,10 @@ export class AddonQtypeDdMarkerComponent extends CoreQuestionBaseComponent imple } // Download background image (3.6+ sites). let imgSrc = this.imgSrc; - const site = CoreSites.instance.getCurrentSite(); + const site = CoreSites.getCurrentSite(); - if (this.imgSrc && site?.canDownloadFiles() && CoreUrlUtils.instance.isPluginFileUrl(this.imgSrc)) { - imgSrc = await CoreFilepool.instance.getSrcByUrl( + if (this.imgSrc && site?.canDownloadFiles() && CoreUrlUtils.isPluginFileUrl(this.imgSrc)) { + imgSrc = await CoreFilepool.getSrcByUrl( site.id!, this.imgSrc, this.component, @@ -155,7 +155,7 @@ export class AddonQtypeDdMarkerComponent extends CoreQuestionBaseComponent imple } if (this.questionTextEl) { - await CoreDomUtils.instance.waitForImages(this.questionTextEl.nativeElement); + await CoreDomUtils.waitForImages(this.questionTextEl.nativeElement); } // Create the instance. diff --git a/src/addons/qtype/ddmarker/ddmarker.module.ts b/src/addons/qtype/ddmarker/ddmarker.module.ts index fed857dfd..6ec64137e 100644 --- a/src/addons/qtype/ddmarker/ddmarker.module.ts +++ b/src/addons/qtype/ddmarker/ddmarker.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeDdMarkerHandler } from './services/handlers/ddmarker'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeDdMarkerHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeDdMarkerHandler.instance); }, }, ], diff --git a/src/addons/qtype/ddmarker/services/handlers/ddmarker.ts b/src/addons/qtype/ddmarker/services/handlers/ddmarker.ts index b602dc2c2..1bcdbed82 100644 --- a/src/addons/qtype/ddmarker/services/handlers/ddmarker.ts +++ b/src/addons/qtype/ddmarker/services/handlers/ddmarker.ts @@ -125,7 +125,7 @@ export class AddonQtypeDdMarkerHandlerService implements CoreQuestionHandler { prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, ): boolean { - return CoreQuestion.instance.compareAllAnswers(prevAnswers, newAnswers); + return CoreQuestion.compareAllAnswers(prevAnswers, newAnswers); } /** @@ -138,7 +138,7 @@ export class AddonQtypeDdMarkerHandlerService implements CoreQuestionHandler { getAdditionalDownloadableFiles(question: CoreQuestionQuestionParsed, usageId?: number): CoreWSExternalFile[] { const treatedQuestion: CoreQuestionQuestion = question; - CoreQuestionHelper.instance.extractQuestionScripts(treatedQuestion, usageId); + CoreQuestionHelper.extractQuestionScripts(treatedQuestion, usageId); if (treatedQuestion.amdArgs && typeof treatedQuestion.amdArgs[1] == 'string') { // Moodle 3.6+. @@ -152,4 +152,4 @@ export class AddonQtypeDdMarkerHandlerService implements CoreQuestionHandler { } -export class AddonQtypeDdMarkerHandler extends makeSingleton(AddonQtypeDdMarkerHandlerService) {} +export const AddonQtypeDdMarkerHandler = makeSingleton(AddonQtypeDdMarkerHandlerService); diff --git a/src/addons/qtype/ddwtos/classes/ddwtos.ts b/src/addons/qtype/ddwtos/classes/ddwtos.ts index 93ffb9d5d..ccc06cff2 100644 --- a/src/addons/qtype/ddwtos/classes/ddwtos.ts +++ b/src/addons/qtype/ddwtos/classes/ddwtos.ts @@ -389,7 +389,7 @@ export class AddonQtypeDdwtosQuestion { const groupNo = this.getGroup(drag) ?? -1; const choiceNo = this.getChoice(drag) ?? -1; - position = CoreDomUtils.instance.getElementXY( + position = CoreDomUtils.getElementXY( this.container, this.selectors.dragHome(groupNo, choiceNo), 'answercontainer', @@ -397,7 +397,7 @@ export class AddonQtypeDdwtosQuestion { drag.classList.add('unplaced'); } else { // Get the drop zone position. - position = CoreDomUtils.instance.getElementXY( + position = CoreDomUtils.getElementXY( this.container, this.selectors.dropForPlace(placeNo), 'addon-qtype-ddwtos-container', @@ -434,7 +434,7 @@ export class AddonQtypeDdwtosQuestion { return; } - const deferred = CoreUtils.instance.promiseDefer(); + const deferred = CoreUtils.promiseDefer(); setTimeout(async () => { try { @@ -498,7 +498,7 @@ export class AddonQtypeDdwtosQuestion { // Find max height and width. groupItems.forEach((item) => { - item.innerHTML = CoreTextUtils.instance.decodeHTML(item.innerHTML); + item.innerHTML = CoreTextUtils.decodeHTML(item.innerHTML); maxWidth = Math.max(maxWidth, Math.ceil(item.offsetWidth)); maxHeight = Math.max(maxHeight, Math.ceil(item.offsetHeight)); }); diff --git a/src/addons/qtype/ddwtos/component/ddwtos.ts b/src/addons/qtype/ddwtos/component/ddwtos.ts index 3d6f8b3a4..bbafd79cc 100644 --- a/src/addons/qtype/ddwtos/component/ddwtos.ts +++ b/src/addons/qtype/ddwtos/component/ddwtos.ts @@ -50,34 +50,34 @@ export class AddonQtypeDdwtosComponent extends CoreQuestionBaseComponent impleme if (!this.question) { this.logger.warn('Aborting because of no question received.'); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } this.ddQuestion = this.question; - const element = CoreDomUtils.instance.convertToElement(this.ddQuestion.html); + const element = CoreDomUtils.convertToElement(this.ddQuestion.html); // Replace Moodle's correct/incorrect and feedback classes with our own. - CoreQuestionHelper.instance.replaceCorrectnessClasses(element); - CoreQuestionHelper.instance.replaceFeedbackClasses(element); + CoreQuestionHelper.replaceCorrectnessClasses(element); + CoreQuestionHelper.replaceFeedbackClasses(element); // Treat the correct/incorrect icons. - CoreQuestionHelper.instance.treatCorrectnessIcons(element); + CoreQuestionHelper.treatCorrectnessIcons(element); const answerContainer = element.querySelector('.answercontainer'); if (!answerContainer) { this.logger.warn('Aborting because of an error parsing question.', this.ddQuestion.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } this.ddQuestion.readOnly = answerContainer.classList.contains('readonly'); this.ddQuestion.answers = answerContainer.outerHTML; - this.ddQuestion.text = CoreDomUtils.instance.getContentsOfElement(element, '.qtext'); + this.ddQuestion.text = CoreDomUtils.getContentsOfElement(element, '.qtext'); if (typeof this.ddQuestion.text == 'undefined') { this.logger.warn('Aborting because of an error parsing question.', this.ddQuestion.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } // Get the inputs where the answers will be stored and add them to the question text. @@ -123,7 +123,7 @@ export class AddonQtypeDdwtosComponent extends CoreQuestionBaseComponent impleme } if (this.questionTextEl) { - await CoreDomUtils.instance.waitForImages(this.questionTextEl.nativeElement); + await CoreDomUtils.waitForImages(this.questionTextEl.nativeElement); } // Create the instance. @@ -134,7 +134,7 @@ export class AddonQtypeDdwtosComponent extends CoreQuestionBaseComponent impleme this.inputIds, ); - CoreQuestionHelper.instance.treatCorrectnessIconsClicks( + CoreQuestionHelper.treatCorrectnessIconsClicks( this.hostElement, this.component, this.componentId, diff --git a/src/addons/qtype/ddwtos/ddwtos.module.ts b/src/addons/qtype/ddwtos/ddwtos.module.ts index 2aeddc069..33563da45 100644 --- a/src/addons/qtype/ddwtos/ddwtos.module.ts +++ b/src/addons/qtype/ddwtos/ddwtos.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeDdwtosHandler } from './services/handlers/ddwtos'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeDdwtosHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeDdwtosHandler.instance); }, }, ], diff --git a/src/addons/qtype/ddwtos/services/handlers/ddwtos.ts b/src/addons/qtype/ddwtos/services/handlers/ddwtos.ts index 20999b302..6dc78c078 100644 --- a/src/addons/qtype/ddwtos/services/handlers/ddwtos.ts +++ b/src/addons/qtype/ddwtos/services/handlers/ddwtos.ts @@ -126,9 +126,9 @@ export class AddonQtypeDdwtosHandlerService implements CoreQuestionHandler { prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, ): boolean { - return CoreQuestion.instance.compareAllAnswers(prevAnswers, newAnswers); + return CoreQuestion.compareAllAnswers(prevAnswers, newAnswers); } } -export class AddonQtypeDdwtosHandler extends makeSingleton(AddonQtypeDdwtosHandlerService) {} +export const AddonQtypeDdwtosHandler = makeSingleton(AddonQtypeDdwtosHandlerService); diff --git a/src/addons/qtype/description/description.module.ts b/src/addons/qtype/description/description.module.ts index f03cf74c8..198e4f89e 100644 --- a/src/addons/qtype/description/description.module.ts +++ b/src/addons/qtype/description/description.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeDescriptionHandler } from './services/handlers/description'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeDescriptionHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeDescriptionHandler.instance); }, }, ], diff --git a/src/addons/qtype/description/services/handlers/description.ts b/src/addons/qtype/description/services/handlers/description.ts index 52b359f24..f8ebaeed7 100644 --- a/src/addons/qtype/description/services/handlers/description.ts +++ b/src/addons/qtype/description/services/handlers/description.ts @@ -74,4 +74,4 @@ export class AddonQtypeDescriptionHandlerService implements CoreQuestionHandler } -export class AddonQtypeDescriptionHandler extends makeSingleton(AddonQtypeDescriptionHandlerService) {} +export const AddonQtypeDescriptionHandler = makeSingleton(AddonQtypeDescriptionHandlerService); diff --git a/src/addons/qtype/essay/component/essay.ts b/src/addons/qtype/essay/component/essay.ts index a3c0d3b4d..44da3e59b 100644 --- a/src/addons/qtype/essay/component/essay.ts +++ b/src/addons/qtype/essay/component/essay.ts @@ -64,7 +64,7 @@ export class AddonQtypeEssayComponent extends CoreQuestionBaseComponent implemen async loadAttachments(): Promise { if (this.offlineEnabled && this.essayQuestion?.localAnswers?.attachments_offline) { - const attachmentsData: CoreFileUploaderStoreFilesResult = CoreTextUtils.instance.parseJSON( + const attachmentsData: CoreFileUploaderStoreFilesResult = CoreTextUtils.parseJSON( this.essayQuestion.localAnswers.attachments_offline, { online: [], @@ -74,7 +74,7 @@ export class AddonQtypeEssayComponent extends CoreQuestionBaseComponent implemen let offlineFiles: FileEntry[] = []; if (attachmentsData.offline) { - offlineFiles = await CoreQuestionHelper.instance.getStoredQuestionFiles( + offlineFiles = await CoreQuestionHelper.getStoredQuestionFiles( this.essayQuestion, this.component || '', this.componentId || -1, @@ -83,12 +83,12 @@ export class AddonQtypeEssayComponent extends CoreQuestionBaseComponent implemen this.attachments = [...attachmentsData.online, ...offlineFiles]; } else { - this.attachments = Array.from(CoreQuestionHelper.instance.getResponseFileAreaFiles(this.question!, 'attachments')); + this.attachments = Array.from(CoreQuestionHelper.getResponseFileAreaFiles(this.question!, 'attachments')); } - CoreFileSession.instance.setFiles( + CoreFileSession.setFiles( this.component || '', - CoreQuestion.instance.getQuestionComponentId(this.question!, this.componentId || -1), + CoreQuestion.getQuestionComponentId(this.question!, this.componentId || -1), this.attachments, ); } diff --git a/src/addons/qtype/essay/essay.module.ts b/src/addons/qtype/essay/essay.module.ts index 7e394279f..3d18fb67b 100644 --- a/src/addons/qtype/essay/essay.module.ts +++ b/src/addons/qtype/essay/essay.module.ts @@ -34,7 +34,7 @@ import { AddonQtypeEssayComponent } from './component/essay'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeEssayHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeEssayHandler.instance); }, }, ], diff --git a/src/addons/qtype/essay/services/handlers/essay.ts b/src/addons/qtype/essay/services/handlers/essay.ts index bc333e5bd..053e7d1eb 100644 --- a/src/addons/qtype/essay/services/handlers/essay.ts +++ b/src/addons/qtype/essay/services/handlers/essay.ts @@ -46,14 +46,14 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { * @param componentId Component ID. */ clearTmpData(question: CoreQuestionQuestionParsed, component: string, componentId: string | number): void { - const questionComponentId = CoreQuestion.instance.getQuestionComponentId(question, componentId); - const files = CoreFileSession.instance.getFiles(component, questionComponentId); + const questionComponentId = CoreQuestion.getQuestionComponentId(question, componentId); + const files = CoreFileSession.getFiles(component, questionComponentId); // Clear the files in session for this question. - CoreFileSession.instance.clearFiles(component, questionComponentId); + CoreFileSession.clearFiles(component, questionComponentId); // Now delete the local files from the tmp folder. - CoreFileUploader.instance.clearTmpFiles(files); + CoreFileUploader.clearTmpFiles(files); } /** @@ -71,7 +71,7 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { componentId: string | number, siteId?: string, ): Promise { - return CoreQuestionHelper.instance.deleteStoredQuestionFiles(question, component, componentId, siteId); + return CoreQuestionHelper.deleteStoredQuestionFiles(question, component, componentId, siteId); } /** @@ -103,7 +103,7 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { }; } - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); return { text: !!element.querySelector('textarea[name*=_answer]'), @@ -142,7 +142,7 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { * @return Prevent submit message. Undefined or empty if can be submitted. */ getPreventSubmitMessage(question: CoreQuestionQuestionParsed): string | undefined { - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); const uploadFilesSupported = typeof question.responsefileareas != 'undefined'; if (!uploadFilesSupported && element.querySelector('div[id*=filemanager]')) { @@ -150,7 +150,7 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { return 'core.question.errorattachmentsnotsupportedinsite'; } - if (!uploadFilesSupported && CoreQuestionHelper.instance.hasDraftFileUrls(element.innerHTML)) { + if (!uploadFilesSupported && CoreQuestionHelper.hasDraftFileUrls(element.innerHTML)) { return 'core.question.errorembeddedfilesnotsupportedinsite'; } } @@ -184,8 +184,8 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { return -1; } - const questionComponentId = CoreQuestion.instance.getQuestionComponentId(question, componentId); - const attachments = CoreFileSession.instance.getFiles(component, questionComponentId); + const questionComponentId = CoreQuestion.getQuestionComponentId(question, componentId); + const attachments = CoreFileSession.getFiles(component, questionComponentId); if (!allowedOptions.text) { return attachments && attachments.length >= Number(question.parsedSettings.attachmentsrequired) ? 1 : 0; @@ -224,8 +224,8 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { return -1; } - const questionComponentId = CoreQuestion.instance.getQuestionComponentId(question, componentId); - const attachments = CoreFileSession.instance.getFiles(component, questionComponentId); + const questionComponentId = CoreQuestion.getQuestionComponentId(question, componentId); + const attachments = CoreFileSession.getFiles(component, questionComponentId); // Determine if the given response has online text or attachments. return (answers.answer && answers.answer !== '') || (attachments && attachments.length > 0) ? 1 : 0; @@ -253,7 +253,7 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { // First check the inline text. const answerIsEqual = allowedOptions.text ? - CoreUtils.instance.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer') : true; + CoreUtils.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer') : true; if (!allowedOptions.attachments || !uploadFilesSupported || !answerIsEqual) { // No need to check attachments. @@ -261,11 +261,11 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { } // Check attachments now. - const questionComponentId = CoreQuestion.instance.getQuestionComponentId(question, componentId); - const attachments = CoreFileSession.instance.getFiles(component, questionComponentId); - const originalAttachments = CoreQuestionHelper.instance.getResponseFileAreaFiles(question, 'attachments'); + const questionComponentId = CoreQuestion.getQuestionComponentId(question, componentId); + const attachments = CoreFileSession.getFiles(component, questionComponentId); + const originalAttachments = CoreQuestionHelper.getResponseFileAreaFiles(question, 'attachments'); - return !CoreFileUploader.instance.areFileListDifferent(attachments, originalAttachments); + return !CoreFileUploader.areFileListDifferent(attachments, originalAttachments); } /** @@ -288,7 +288,7 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { siteId?: string, ): Promise { - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); const attachmentsInput = element.querySelector('.attachments input[name*=_attachments]'); // Search the textarea to get its name. @@ -326,29 +326,29 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { ): Promise { // Treat attachments if any. - const questionComponentId = CoreQuestion.instance.getQuestionComponentId(question, componentId); - const attachments = CoreFileSession.instance.getFiles(component, questionComponentId); + const questionComponentId = CoreQuestion.getQuestionComponentId(question, componentId); + const attachments = CoreFileSession.getFiles(component, questionComponentId); const draftId = Number(attachmentsInput.value); if (offline) { // Get the folder where to store the files. - const folderPath = CoreQuestion.instance.getQuestionFolder(question.type, component, questionComponentId, siteId); + const folderPath = CoreQuestion.getQuestionFolder(question.type, component, questionComponentId, siteId); - const result = await CoreFileUploader.instance.storeFilesToUpload(folderPath, attachments); + const result = await CoreFileUploader.storeFilesToUpload(folderPath, attachments); // Store the files in the answers. answers[attachmentsInput.name + '_offline'] = JSON.stringify(result); } else { // Check if any attachment was deleted. - const originalAttachments = CoreQuestionHelper.instance.getResponseFileAreaFiles(question, 'attachments'); - const filesToDelete = CoreFileUploader.instance.getFilesToDelete(originalAttachments, attachments); + const originalAttachments = CoreQuestionHelper.getResponseFileAreaFiles(question, 'attachments'); + const filesToDelete = CoreFileUploader.getFilesToDelete(originalAttachments, attachments); if (filesToDelete.length > 0) { // Delete files. - await CoreFileUploader.instance.deleteDraftFiles(draftId, filesToDelete, siteId); + await CoreFileUploader.deleteDraftFiles(draftId, filesToDelete, siteId); } - await CoreFileUploader.instance.uploadFiles(draftId, attachments, siteId); + await CoreFileUploader.uploadFiles(draftId, attachments, siteId); } } @@ -370,7 +370,7 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { siteId?: string, ): Promise { - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); const attachmentsInput = element.querySelector('.attachments input[name*=_attachments]'); if (attachmentsInput) { @@ -382,7 +382,7 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { return; } - const attachmentsData: CoreFileUploaderStoreFilesResult = CoreTextUtils.instance.parseJSON( + const attachmentsData: CoreFileUploaderStoreFilesResult = CoreTextUtils.parseJSON( answers.attachments_offline, { online: [], @@ -392,12 +392,12 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { delete answers.attachments_offline; // Check if any attachment was deleted. - const originalAttachments = CoreQuestionHelper.instance.getResponseFileAreaFiles(question, 'attachments'); - const filesToDelete = CoreFileUploader.instance.getFilesToDelete(originalAttachments, attachmentsData.online); + const originalAttachments = CoreQuestionHelper.getResponseFileAreaFiles(question, 'attachments'); + const filesToDelete = CoreFileUploader.getFilesToDelete(originalAttachments, attachmentsData.online); if (filesToDelete.length > 0) { // Delete files. - await CoreFileUploader.instance.deleteDraftFiles(Number(answers.attachments), filesToDelete, siteId); + await CoreFileUploader.deleteDraftFiles(Number(answers.attachments), filesToDelete, siteId); } if (!attachmentsData.offline) { @@ -406,9 +406,9 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { // Upload the offline files. const offlineFiles = - await CoreQuestionHelper.instance.getStoredQuestionFiles(question, component, componentId, siteId); + await CoreQuestionHelper.getStoredQuestionFiles(question, component, componentId, siteId); - await CoreFileUploader.instance.uploadFiles( + await CoreFileUploader.uploadFiles( Number(answers.attachments), [...attachmentsData.online, ...offlineFiles], siteId, @@ -430,15 +430,15 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { textarea: HTMLTextAreaElement, siteId?: string, ): Promise { - if (CoreQuestionHelper.instance.hasDraftFileUrls(question.html) && question.responsefileareas) { + if (CoreQuestionHelper.hasDraftFileUrls(question.html) && question.responsefileareas) { // Restore draftfile URLs. - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - answers[textarea.name] = CoreTextUtils.instance.restoreDraftfileUrls( + answers[textarea.name] = CoreTextUtils.restoreDraftfileUrls( site.getURL(), answers[textarea.name], question.html, - CoreQuestionHelper.instance.getResponseFileAreaFiles(question, 'answer'), + CoreQuestionHelper.getResponseFileAreaFiles(question, 'answer'), ); } @@ -449,16 +449,16 @@ export class AddonQtypeEssayHandlerService implements CoreQuestionHandler { isPlainText = question.parsedSettings.responseformat == 'monospaced' || question.parsedSettings.responseformat == 'plain'; } else { - const questionEl = CoreDomUtils.instance.convertToElement(question.html); + const questionEl = CoreDomUtils.convertToElement(question.html); isPlainText = !!questionEl.querySelector('.qtype_essay_monospaced') || !!questionEl.querySelector('.qtype_essay_plain'); } if (!isPlainText) { // Add some HTML to the text if needed. - answers[textarea.name] = CoreTextUtils.instance.formatHtmlLines( answers[textarea.name]); + answers[textarea.name] = CoreTextUtils.formatHtmlLines( answers[textarea.name]); } } } -export class AddonQtypeEssayHandler extends makeSingleton(AddonQtypeEssayHandlerService) {} +export const AddonQtypeEssayHandler = makeSingleton(AddonQtypeEssayHandlerService); diff --git a/src/addons/qtype/gapselect/component/gapselect.ts b/src/addons/qtype/gapselect/component/gapselect.ts index 8c1872bae..2f38213f8 100644 --- a/src/addons/qtype/gapselect/component/gapselect.ts +++ b/src/addons/qtype/gapselect/component/gapselect.ts @@ -42,7 +42,7 @@ export class AddonQtypeGapSelectComponent extends CoreQuestionBaseComponent impl * The question has been rendered. */ questionRendered(): void { - CoreQuestionHelper.instance.treatCorrectnessIconsClicks( + CoreQuestionHelper.treatCorrectnessIconsClicks( this.hostElement, this.component, this.componentId, diff --git a/src/addons/qtype/gapselect/gapselect.module.ts b/src/addons/qtype/gapselect/gapselect.module.ts index 1dd6c49ca..15f730e4f 100644 --- a/src/addons/qtype/gapselect/gapselect.module.ts +++ b/src/addons/qtype/gapselect/gapselect.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeGapSelectHandler } from './services/handlers/gapselect'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeGapSelectHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeGapSelectHandler.instance); }, }, ], diff --git a/src/addons/qtype/gapselect/services/handlers/gapselect.ts b/src/addons/qtype/gapselect/services/handlers/gapselect.ts index a817375d8..f8e2392ee 100644 --- a/src/addons/qtype/gapselect/services/handlers/gapselect.ts +++ b/src/addons/qtype/gapselect/services/handlers/gapselect.ts @@ -128,9 +128,9 @@ export class AddonQtypeGapSelectHandlerService implements CoreQuestionHandler { prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, ): boolean { - return CoreQuestion.instance.compareAllAnswers(prevAnswers, newAnswers); + return CoreQuestion.compareAllAnswers(prevAnswers, newAnswers); } } -export class AddonQtypeGapSelectHandler extends makeSingleton(AddonQtypeGapSelectHandlerService) {} +export const AddonQtypeGapSelectHandler = makeSingleton(AddonQtypeGapSelectHandlerService); diff --git a/src/addons/qtype/match/match.module.ts b/src/addons/qtype/match/match.module.ts index 543968a91..b52672cc2 100644 --- a/src/addons/qtype/match/match.module.ts +++ b/src/addons/qtype/match/match.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeMatchHandler } from './services/handlers/match'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeMatchHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeMatchHandler.instance); }, }, ], diff --git a/src/addons/qtype/match/services/handlers/match.ts b/src/addons/qtype/match/services/handlers/match.ts index 69ad099f1..f982e859b 100644 --- a/src/addons/qtype/match/services/handlers/match.ts +++ b/src/addons/qtype/match/services/handlers/match.ts @@ -128,9 +128,9 @@ export class AddonQtypeMatchHandlerService implements CoreQuestionHandler { prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, ): boolean { - return CoreQuestion.instance.compareAllAnswers(prevAnswers, newAnswers); + return CoreQuestion.compareAllAnswers(prevAnswers, newAnswers); } } -export class AddonQtypeMatchHandler extends makeSingleton(AddonQtypeMatchHandlerService) {} +export const AddonQtypeMatchHandler = makeSingleton(AddonQtypeMatchHandlerService); diff --git a/src/addons/qtype/multianswer/component/multianswer.ts b/src/addons/qtype/multianswer/component/multianswer.ts index 19e7e567b..4ea34b164 100644 --- a/src/addons/qtype/multianswer/component/multianswer.ts +++ b/src/addons/qtype/multianswer/component/multianswer.ts @@ -41,7 +41,7 @@ export class AddonQtypeMultiAnswerComponent extends CoreQuestionBaseComponent im * The question has been rendered. */ questionRendered(): void { - CoreQuestionHelper.instance.treatCorrectnessIconsClicks( + CoreQuestionHelper.treatCorrectnessIconsClicks( this.hostElement, this.component, this.componentId, diff --git a/src/addons/qtype/multianswer/multianswer.module.ts b/src/addons/qtype/multianswer/multianswer.module.ts index b66445d56..e5840b65b 100644 --- a/src/addons/qtype/multianswer/multianswer.module.ts +++ b/src/addons/qtype/multianswer/multianswer.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeMultiAnswerHandler } from './services/handlers/multianswer'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeMultiAnswerHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeMultiAnswerHandler.instance); }, }, ], diff --git a/src/addons/qtype/multianswer/services/handlers/multianswer.ts b/src/addons/qtype/multianswer/services/handlers/multianswer.ts index 0c0fd3271..b00857b24 100644 --- a/src/addons/qtype/multianswer/services/handlers/multianswer.ts +++ b/src/addons/qtype/multianswer/services/handlers/multianswer.ts @@ -70,8 +70,8 @@ export class AddonQtypeMultiAnswerHandlerService implements CoreQuestionHandler answers: CoreQuestionsAnswers, ): number { // Get all the inputs in the question to check if they've all been answered. - const names = CoreQuestion.instance.getBasicAnswers( - CoreQuestionHelper.instance.getAllInputNamesFromHtml(question.html || ''), + const names = CoreQuestion.getBasicAnswers( + CoreQuestionHelper.getAllInputNamesFromHtml(question.html || ''), ); for (const name in names) { const value = answers[name]; @@ -132,7 +132,7 @@ export class AddonQtypeMultiAnswerHandlerService implements CoreQuestionHandler prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, ): boolean { - return CoreQuestion.instance.compareAllAnswers(prevAnswers, newAnswers); + return CoreQuestion.compareAllAnswers(prevAnswers, newAnswers); } /** @@ -159,4 +159,4 @@ export class AddonQtypeMultiAnswerHandlerService implements CoreQuestionHandler } -export class AddonQtypeMultiAnswerHandler extends makeSingleton(AddonQtypeMultiAnswerHandlerService) {} +export const AddonQtypeMultiAnswerHandler = makeSingleton(AddonQtypeMultiAnswerHandlerService); diff --git a/src/addons/qtype/multichoice/multichoice.module.ts b/src/addons/qtype/multichoice/multichoice.module.ts index e04a66ae1..43ee32d66 100644 --- a/src/addons/qtype/multichoice/multichoice.module.ts +++ b/src/addons/qtype/multichoice/multichoice.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeMultichoiceHandler } from './services/handlers/multichoice'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeMultichoiceHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeMultichoiceHandler.instance); }, }, ], diff --git a/src/addons/qtype/multichoice/services/handlers/multichoice.ts b/src/addons/qtype/multichoice/services/handlers/multichoice.ts index c185959c7..55dadcb8d 100644 --- a/src/addons/qtype/multichoice/services/handlers/multichoice.ts +++ b/src/addons/qtype/multichoice/services/handlers/multichoice.ts @@ -149,7 +149,7 @@ export class AddonQtypeMultichoiceHandlerService implements CoreQuestionHandler for (const name in newAnswers) { if (name.indexOf('choice') != -1) { isSingle = false; - if (!CoreUtils.instance.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, name)) { + if (!CoreUtils.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, name)) { isMultiSame = false; break; } @@ -171,7 +171,7 @@ export class AddonQtypeMultichoiceHandlerService implements CoreQuestionHandler * @return Whether they're the same. */ isSameResponseSingle(prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers): boolean { - return CoreUtils.instance.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer'); + return CoreUtils.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer'); } /** @@ -198,4 +198,4 @@ export class AddonQtypeMultichoiceHandlerService implements CoreQuestionHandler } -export class AddonQtypeMultichoiceHandler extends makeSingleton(AddonQtypeMultichoiceHandlerService) {} +export const AddonQtypeMultichoiceHandler = makeSingleton(AddonQtypeMultichoiceHandlerService); diff --git a/src/addons/qtype/numerical/numerical.module.ts b/src/addons/qtype/numerical/numerical.module.ts index 6099c867e..a07fd0df6 100644 --- a/src/addons/qtype/numerical/numerical.module.ts +++ b/src/addons/qtype/numerical/numerical.module.ts @@ -27,7 +27,7 @@ import { AddonQtypeNumericalHandler } from './services/handlers/numerical'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeNumericalHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeNumericalHandler.instance); }, }, ], diff --git a/src/addons/qtype/numerical/services/handlers/numerical.ts b/src/addons/qtype/numerical/services/handlers/numerical.ts index de5c79477..122d4db9d 100644 --- a/src/addons/qtype/numerical/services/handlers/numerical.ts +++ b/src/addons/qtype/numerical/services/handlers/numerical.ts @@ -29,4 +29,4 @@ export class AddonQtypeNumericalHandlerService extends AddonQtypeCalculatedHandl } -export class AddonQtypeNumericalHandler extends makeSingleton(AddonQtypeNumericalHandlerService) {} +export const AddonQtypeNumericalHandler = makeSingleton(AddonQtypeNumericalHandlerService); diff --git a/src/addons/qtype/randomsamatch/randomsamatch.module.ts b/src/addons/qtype/randomsamatch/randomsamatch.module.ts index 004d8b82a..59063e97a 100644 --- a/src/addons/qtype/randomsamatch/randomsamatch.module.ts +++ b/src/addons/qtype/randomsamatch/randomsamatch.module.ts @@ -26,7 +26,7 @@ import { AddonQtypeRandomSaMatchHandler } from './services/handlers/randomsamatc multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeRandomSaMatchHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeRandomSaMatchHandler.instance); }, }, ], diff --git a/src/addons/qtype/randomsamatch/services/handlers/randomsamatch.ts b/src/addons/qtype/randomsamatch/services/handlers/randomsamatch.ts index 18470962d..ae71f61c1 100644 --- a/src/addons/qtype/randomsamatch/services/handlers/randomsamatch.ts +++ b/src/addons/qtype/randomsamatch/services/handlers/randomsamatch.ts @@ -28,4 +28,4 @@ export class AddonQtypeRandomSaMatchHandlerService extends AddonQtypeMatchHandle } -export class AddonQtypeRandomSaMatchHandler extends makeSingleton(AddonQtypeRandomSaMatchHandlerService) {} +export const AddonQtypeRandomSaMatchHandler = makeSingleton(AddonQtypeRandomSaMatchHandlerService); diff --git a/src/addons/qtype/shortanswer/services/handlers/shortanswer.ts b/src/addons/qtype/shortanswer/services/handlers/shortanswer.ts index 5cc0398f5..6e241cee1 100644 --- a/src/addons/qtype/shortanswer/services/handlers/shortanswer.ts +++ b/src/addons/qtype/shortanswer/services/handlers/shortanswer.ts @@ -101,9 +101,9 @@ export class AddonQtypeShortAnswerHandlerService implements CoreQuestionHandler prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, ): boolean { - return CoreUtils.instance.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer'); + return CoreUtils.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer'); } } -export class AddonQtypeShortAnswerHandler extends makeSingleton(AddonQtypeShortAnswerHandlerService) {} +export const AddonQtypeShortAnswerHandler = makeSingleton(AddonQtypeShortAnswerHandlerService); diff --git a/src/addons/qtype/shortanswer/shortanswer.module.ts b/src/addons/qtype/shortanswer/shortanswer.module.ts index 8faf8f6aa..363c237c5 100644 --- a/src/addons/qtype/shortanswer/shortanswer.module.ts +++ b/src/addons/qtype/shortanswer/shortanswer.module.ts @@ -32,7 +32,7 @@ import { AddonQtypeShortAnswerHandler } from './services/handlers/shortanswer'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeShortAnswerHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeShortAnswerHandler.instance); }, }, ], diff --git a/src/addons/qtype/truefalse/services/handlers/truefalse.ts b/src/addons/qtype/truefalse/services/handlers/truefalse.ts index 33a00db9d..aaceeb122 100644 --- a/src/addons/qtype/truefalse/services/handlers/truefalse.ts +++ b/src/addons/qtype/truefalse/services/handlers/truefalse.ts @@ -103,7 +103,7 @@ export class AddonQtypeTrueFalseHandlerService implements CoreQuestionHandler { prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, ): boolean { - return CoreUtils.instance.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer'); + return CoreUtils.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, 'answer'); } /** @@ -129,4 +129,4 @@ export class AddonQtypeTrueFalseHandlerService implements CoreQuestionHandler { } -export class AddonQtypeTrueFalseHandler extends makeSingleton(AddonQtypeTrueFalseHandlerService) {} +export const AddonQtypeTrueFalseHandler = makeSingleton(AddonQtypeTrueFalseHandlerService); diff --git a/src/addons/qtype/truefalse/truefalse.module.ts b/src/addons/qtype/truefalse/truefalse.module.ts index 2599299c0..129857221 100644 --- a/src/addons/qtype/truefalse/truefalse.module.ts +++ b/src/addons/qtype/truefalse/truefalse.module.ts @@ -26,7 +26,7 @@ import { AddonQtypeTrueFalseHandler } from './services/handlers/truefalse'; multi: true, deps: [], useFactory: () => () => { - CoreQuestionDelegate.instance.registerHandler(AddonQtypeTrueFalseHandler.instance); + CoreQuestionDelegate.registerHandler(AddonQtypeTrueFalseHandler.instance); }, }, ], diff --git a/src/addons/userprofilefield/checkbox/checkbox.module.ts b/src/addons/userprofilefield/checkbox/checkbox.module.ts index 8163a783a..a4aaa572e 100644 --- a/src/addons/userprofilefield/checkbox/checkbox.module.ts +++ b/src/addons/userprofilefield/checkbox/checkbox.module.ts @@ -32,7 +32,7 @@ import { CoreSharedModule } from '@/core/shared.module'; multi: true, deps: [], useFactory: () => () => - CoreUserProfileFieldDelegate.instance.registerHandler(AddonUserProfileFieldCheckboxHandler.instance), + CoreUserProfileFieldDelegate.registerHandler(AddonUserProfileFieldCheckboxHandler.instance), }, ], exports: [ diff --git a/src/addons/userprofilefield/checkbox/component/checkbox.ts b/src/addons/userprofilefield/checkbox/component/checkbox.ts index 672307930..96dc9b922 100644 --- a/src/addons/userprofilefield/checkbox/component/checkbox.ts +++ b/src/addons/userprofilefield/checkbox/component/checkbox.ts @@ -35,7 +35,7 @@ export class AddonUserProfileFieldCheckboxComponent extends CoreUserProfileField */ protected createFormControl(field: AuthEmailSignupProfileField): FormControl { const formData = { - value: CoreUtils.instance.isTrueOrOne(field.defaultdata), + value: CoreUtils.isTrueOrOne(field.defaultdata), disabled: this.disabled, }; diff --git a/src/addons/userprofilefield/checkbox/services/handlers/checkbox.ts b/src/addons/userprofilefield/checkbox/services/handlers/checkbox.ts index f085e2f3b..3611f612b 100644 --- a/src/addons/userprofilefield/checkbox/services/handlers/checkbox.ts +++ b/src/addons/userprofilefield/checkbox/services/handlers/checkbox.ts @@ -76,4 +76,4 @@ export class AddonUserProfileFieldCheckboxHandlerService implements CoreUserProf } -export class AddonUserProfileFieldCheckboxHandler extends makeSingleton(AddonUserProfileFieldCheckboxHandlerService) {} +export const AddonUserProfileFieldCheckboxHandler = makeSingleton(AddonUserProfileFieldCheckboxHandlerService); diff --git a/src/addons/userprofilefield/datetime/component/datetime.ts b/src/addons/userprofilefield/datetime/component/datetime.ts index 3deb698d2..b1c581be2 100644 --- a/src/addons/userprofilefield/datetime/component/datetime.ts +++ b/src/addons/userprofilefield/datetime/component/datetime.ts @@ -54,11 +54,11 @@ export class AddonUserProfileFieldDatetimeComponent extends CoreUserProfileField super.initForEdit(field); // Check if it's only date or it has time too. - const hasTime = CoreUtils.instance.isTrueOrOne(field.param3); + const hasTime = CoreUtils.isTrueOrOne(field.param3); // Calculate format to use. - this.format = CoreTimeUtils.instance.fixFormatForDatetime(CoreTimeUtils.instance.convertPHPToMoment( - Translate.instance.instant('core.' + (hasTime ? 'strftimedatetime' : 'strftimedate')), + this.format = CoreTimeUtils.fixFormatForDatetime(CoreTimeUtils.convertPHPToMoment( + Translate.instant('core.' + (hasTime ? 'strftimedatetime' : 'strftimedate')), )); // Check min value. diff --git a/src/addons/userprofilefield/datetime/datetime.module.ts b/src/addons/userprofilefield/datetime/datetime.module.ts index 43172b26a..a47a1cac1 100644 --- a/src/addons/userprofilefield/datetime/datetime.module.ts +++ b/src/addons/userprofilefield/datetime/datetime.module.ts @@ -32,7 +32,7 @@ import { CoreSharedModule } from '@/core/shared.module'; multi: true, deps: [], useFactory: () => () => - CoreUserProfileFieldDelegate.instance.registerHandler(AddonUserProfileFieldDatetimeHandler.instance), + CoreUserProfileFieldDelegate.registerHandler(AddonUserProfileFieldDatetimeHandler.instance), }, ], exports: [ diff --git a/src/addons/userprofilefield/datetime/services/handlers/datetime.ts b/src/addons/userprofilefield/datetime/services/handlers/datetime.ts index cc16bc6ea..ba0bd7d67 100644 --- a/src/addons/userprofilefield/datetime/services/handlers/datetime.ts +++ b/src/addons/userprofilefield/datetime/services/handlers/datetime.ts @@ -60,7 +60,7 @@ export class AddonUserProfileFieldDatetimeHandlerService implements CoreUserProf return { type: 'datetime', name: 'profile_field_' + field.shortname, - value: CoreTimeUtils.instance.convertToTimestamp( formValues[name]), + value: CoreTimeUtils.convertToTimestamp( formValues[name]), }; } } @@ -77,4 +77,4 @@ export class AddonUserProfileFieldDatetimeHandlerService implements CoreUserProf } -export class AddonUserProfileFieldDatetimeHandler extends makeSingleton(AddonUserProfileFieldDatetimeHandlerService) {} +export const AddonUserProfileFieldDatetimeHandler = makeSingleton(AddonUserProfileFieldDatetimeHandlerService); diff --git a/src/addons/userprofilefield/menu/menu.module.ts b/src/addons/userprofilefield/menu/menu.module.ts index 694c80c64..0672fa29d 100644 --- a/src/addons/userprofilefield/menu/menu.module.ts +++ b/src/addons/userprofilefield/menu/menu.module.ts @@ -32,7 +32,7 @@ import { CoreSharedModule } from '@/core/shared.module'; multi: true, deps: [], useFactory: () => () => - CoreUserProfileFieldDelegate.instance.registerHandler(AddonUserProfileFieldMenuHandler.instance), + CoreUserProfileFieldDelegate.registerHandler(AddonUserProfileFieldMenuHandler.instance), }, ], exports: [ diff --git a/src/addons/userprofilefield/menu/services/handlers/menu.ts b/src/addons/userprofilefield/menu/services/handlers/menu.ts index 7a9396aed..9379b1b2f 100644 --- a/src/addons/userprofilefield/menu/services/handlers/menu.ts +++ b/src/addons/userprofilefield/menu/services/handlers/menu.ts @@ -76,4 +76,4 @@ export class AddonUserProfileFieldMenuHandlerService implements CoreUserProfileF } -export class AddonUserProfileFieldMenuHandler extends makeSingleton(AddonUserProfileFieldMenuHandlerService) {} +export const AddonUserProfileFieldMenuHandler = makeSingleton(AddonUserProfileFieldMenuHandlerService); diff --git a/src/addons/userprofilefield/text/component/text.ts b/src/addons/userprofilefield/text/component/text.ts index 3b7f42030..00b8c487c 100644 --- a/src/addons/userprofilefield/text/component/text.ts +++ b/src/addons/userprofilefield/text/component/text.ts @@ -44,7 +44,7 @@ export class AddonUserProfileFieldTextComponent extends CoreUserProfileFieldBase } // Check if it's a password or text. - this.inputType = CoreUtils.instance.isTrueOrOne(field.param3) ? 'password' : 'text'; + this.inputType = CoreUtils.isTrueOrOne(field.param3) ? 'password' : 'text'; } } diff --git a/src/addons/userprofilefield/text/services/handlers/text.ts b/src/addons/userprofilefield/text/services/handlers/text.ts index 630872d5e..28335b0d2 100644 --- a/src/addons/userprofilefield/text/services/handlers/text.ts +++ b/src/addons/userprofilefield/text/services/handlers/text.ts @@ -59,7 +59,7 @@ export class AddonUserProfileFieldTextHandlerService implements CoreUserProfileF return { type: 'text', name: name, - value: CoreTextUtils.instance.cleanTags( formValues[name]), + value: CoreTextUtils.cleanTags( formValues[name]), }; } @@ -75,4 +75,4 @@ export class AddonUserProfileFieldTextHandlerService implements CoreUserProfileF } -export class AddonUserProfileFieldTextHandler extends makeSingleton(AddonUserProfileFieldTextHandlerService) {} +export const AddonUserProfileFieldTextHandler = makeSingleton(AddonUserProfileFieldTextHandlerService); diff --git a/src/addons/userprofilefield/text/text.module.ts b/src/addons/userprofilefield/text/text.module.ts index 30d0541ed..019457b98 100644 --- a/src/addons/userprofilefield/text/text.module.ts +++ b/src/addons/userprofilefield/text/text.module.ts @@ -32,7 +32,7 @@ import { CoreSharedModule } from '@/core/shared.module'; multi: true, deps: [], useFactory: () => () => - CoreUserProfileFieldDelegate.instance.registerHandler(AddonUserProfileFieldTextHandler.instance), + CoreUserProfileFieldDelegate.registerHandler(AddonUserProfileFieldTextHandler.instance), }, ], exports: [ diff --git a/src/addons/userprofilefield/textarea/services/handlers/textarea.ts b/src/addons/userprofilefield/textarea/services/handlers/textarea.ts index 6ad1ba8bb..a3aff7885 100644 --- a/src/addons/userprofilefield/textarea/services/handlers/textarea.ts +++ b/src/addons/userprofilefield/textarea/services/handlers/textarea.ts @@ -59,7 +59,7 @@ export class AddonUserProfileFieldTextareaHandlerService implements CoreUserProf if (formValues[name]) { let text = formValues[name] || ''; // Add some HTML to the message in case the user edited with textarea. - text = CoreTextUtils.instance.formatHtmlLines(text); + text = CoreTextUtils.formatHtmlLines(text); return { type: 'textarea', @@ -84,4 +84,4 @@ export class AddonUserProfileFieldTextareaHandlerService implements CoreUserProf } -export class AddonUserProfileFieldTextareaHandler extends makeSingleton(AddonUserProfileFieldTextareaHandlerService) {} +export const AddonUserProfileFieldTextareaHandler = makeSingleton(AddonUserProfileFieldTextareaHandlerService); diff --git a/src/addons/userprofilefield/textarea/textarea.module.ts b/src/addons/userprofilefield/textarea/textarea.module.ts index f4d7004c5..b208dfc98 100644 --- a/src/addons/userprofilefield/textarea/textarea.module.ts +++ b/src/addons/userprofilefield/textarea/textarea.module.ts @@ -34,7 +34,7 @@ import { CoreEditorComponentsModule } from '@features/editor/components/componen multi: true, deps: [], useFactory: () => () => - CoreUserProfileFieldDelegate.instance.registerHandler(AddonUserProfileFieldTextareaHandler.instance), + CoreUserProfileFieldDelegate.registerHandler(AddonUserProfileFieldTextareaHandler.instance), }, ], exports: [ diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 937985104..5d6154614 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -53,10 +53,10 @@ export class AppComponent implements OnInit, AfterViewInit { ngOnInit(): void { CoreEvents.on(CoreEvents.LOGOUT, () => { // Go to sites page when user is logged out. - CoreNavigator.instance.navigate('/login/sites', { reset: true }); + CoreNavigator.navigate('/login/sites', { reset: true }); // Unload lang custom strings. - CoreLang.instance.clearCustomStrings(); + CoreLang.clearCustomStrings(); // Remove version classes from body. this.removeVersionClass(); @@ -64,30 +64,30 @@ export class AppComponent implements OnInit, AfterViewInit { // Listen for session expired events. CoreEvents.on(CoreEvents.SESSION_EXPIRED, (data: CoreEventSessionExpiredData) => { - CoreLoginHelper.instance.sessionExpired(data); + CoreLoginHelper.sessionExpired(data); }); // Listen for passwordchange and usernotfullysetup events to open InAppBrowser. CoreEvents.on(CoreEvents.PASSWORD_CHANGE_FORCED, (data: CoreEventSiteData) => { - CoreLoginHelper.instance.passwordChangeForced(data.siteId!); + CoreLoginHelper.passwordChangeForced(data.siteId!); }); CoreEvents.on(CoreEvents.USER_NOT_FULLY_SETUP, (data: CoreEventSiteData) => { - CoreLoginHelper.instance.openInAppForEdit(data.siteId!, '/user/edit.php', 'core.usernotfullysetup'); + CoreLoginHelper.openInAppForEdit(data.siteId!, '/user/edit.php', 'core.usernotfullysetup'); }); // Listen for sitepolicynotagreed event to accept the site policy. CoreEvents.on(CoreEvents.SITE_POLICY_NOT_AGREED, (data: CoreEventSiteData) => { - CoreLoginHelper.instance.sitePolicyNotAgreed(data.siteId); + CoreLoginHelper.sitePolicyNotAgreed(data.siteId); }); CoreEvents.on(CoreEvents.LOGIN, async (data: CoreEventSiteData) => { if (data.siteId) { - const site = await CoreSites.instance.getSite(data.siteId); + const site = await CoreSites.getSite(data.siteId); const info = site.getInfo(); if (info) { // Add version classes to body. this.removeVersionClass(); - this.addVersionClass(CoreSites.instance.getReleaseNumber(info.release || '')); + this.addVersionClass(CoreSites.getReleaseNumber(info.release || '')); } } @@ -95,22 +95,22 @@ export class AppComponent implements OnInit, AfterViewInit { }); CoreEvents.on(CoreEvents.SITE_UPDATED, (data: CoreEventSiteUpdatedData) => { - if (data.siteId == CoreSites.instance.getCurrentSiteId()) { + if (data.siteId == CoreSites.getCurrentSiteId()) { this.loadCustomStrings(); // Add version classes to body. this.removeVersionClass(); - this.addVersionClass(CoreSites.instance.getReleaseNumber(data.release || '')); + this.addVersionClass(CoreSites.getReleaseNumber(data.release || '')); } }); CoreEvents.on(CoreEvents.SITE_ADDED, (data: CoreEventSiteAddedData) => { - if (data.siteId == CoreSites.instance.getCurrentSiteId()) { + if (data.siteId == CoreSites.getCurrentSiteId()) { this.loadCustomStrings(); // Add version classes to body. this.removeVersionClass(); - this.addVersionClass(CoreSites.instance.getReleaseNumber(data.release || '')); + this.addVersionClass(CoreSites.getReleaseNumber(data.release || '')); } }); @@ -125,20 +125,20 @@ export class AppComponent implements OnInit, AfterViewInit { return; } - CoreSubscriptions.once(this.outlet.activateEvents, () => SplashScreen.instance.hide()); + CoreSubscriptions.once(this.outlet.activateEvents, () => SplashScreen.hide()); } /** * Async init function on platform ready. */ protected async onPlatformReady(): Promise { - await Platform.instance.ready(); + await Platform.ready(); // Refresh online status when changes. - Network.instance.onChange().subscribe(() => { + Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { - const isOnline = CoreApp.instance.isOnline(); + NgZone.run(() => { + const isOnline = CoreApp.isOnline(); const hadOfflineMessage = document.body.classList.contains('core-offline'); document.body.classList.toggle('core-offline', !isOnline); @@ -156,17 +156,17 @@ export class AppComponent implements OnInit, AfterViewInit { }); // Set StatusBar properties. - CoreApp.instance.setStatusBarColor(); + CoreApp.setStatusBarColor(); } /** * Load custom lang strings. This cannot be done inside the lang provider because it causes circular dependencies. */ protected loadCustomStrings(): void { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); if (currentSite) { - CoreLang.instance.loadCustomStringsFromSite(currentSite); + CoreLang.loadCustomStringsFromSite(currentSite); } } diff --git a/src/core/classes/base-sync.ts b/src/core/classes/base-sync.ts index 1eef32e85..7146f1504 100644 --- a/src/core/classes/base-sync.ts +++ b/src/core/classes/base-sync.ts @@ -63,7 +63,7 @@ export class CoreSyncBaseProvider { * @param error Specific error message. */ protected addOfflineDataDeletedWarning(warnings: string[], component: string, name: string, error: string): void { - const warning = Translate.instance.instant('core.warningofflinedatadeleted', { + const warning = Translate.instant('core.warningofflinedatadeleted', { component: component, name: name, error: error, @@ -83,7 +83,7 @@ export class CoreSyncBaseProvider { * @return The sync promise. */ async addOngoingSync(id: string | number, promise: Promise, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!siteId) { throw new CoreError('CoreSyncBaseProvider: Site ID not supplied'); @@ -112,7 +112,7 @@ export class CoreSyncBaseProvider { * @return Promise of the current sync or undefined if there isn't any. */ getOngoingSync(id: string | number, siteId?: string): Promise | undefined { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!this.isSyncing(id, siteId)) { return; @@ -145,9 +145,9 @@ export class CoreSyncBaseProvider { */ getReadableTimeFromTimestamp(timestamp: number): string { if (!timestamp) { - return Translate.instance.instant('core.never'); + return Translate.instant('core.never'); } else { - return CoreTimeUtils.instance.userDate(timestamp); + return CoreTimeUtils.userDate(timestamp); } } @@ -160,7 +160,7 @@ export class CoreSyncBaseProvider { */ async getSyncTime(id: string | number, siteId?: string): Promise { try { - const entry = await CoreSync.instance.getSyncRecord(this.component, id, siteId); + const entry = await CoreSync.getSyncRecord(this.component, id, siteId); return entry.time; } catch { @@ -177,9 +177,9 @@ export class CoreSyncBaseProvider { */ async getSyncWarnings(id: string | number, siteId?: string): Promise { try { - const entry = await CoreSync.instance.getSyncRecord(this.component, id, siteId); + const entry = await CoreSync.getSyncRecord(this.component, id, siteId); - return CoreTextUtils.instance.parseJSON(entry.warnings, []); + return CoreTextUtils.parseJSON(entry.warnings, []); } catch { return []; } @@ -203,7 +203,7 @@ export class CoreSyncBaseProvider { * @return Whether it's synchronizing. */ isSyncing(id: string | number, siteId?: string): boolean { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const uniqueId = this.getUniqueSyncId(id); @@ -234,7 +234,7 @@ export class CoreSyncBaseProvider { async setSyncTime(id: string | number, siteId?: string, time?: number): Promise { time = typeof time != 'undefined' ? time : Date.now(); - await CoreSync.instance.insertOrUpdateSyncRecord(this.component, id, { time: time }, siteId); + await CoreSync.insertOrUpdateSyncRecord(this.component, id, { time: time }, siteId); } /** @@ -248,7 +248,7 @@ export class CoreSyncBaseProvider { async setSyncWarnings(id: string | number, warnings: string[], siteId?: string): Promise { const warningsText = JSON.stringify(warnings || []); - await CoreSync.instance.insertOrUpdateSyncRecord(this.component, id, { warnings: warningsText }, siteId); + await CoreSync.insertOrUpdateSyncRecord(this.component, id, { warnings: warningsText }, siteId); } /** @@ -260,7 +260,7 @@ export class CoreSyncBaseProvider { * @return Resolved with siteIds selected. Rejected if offline. */ async syncOnSites(syncFunctionLog: string, syncFunction: (siteId: string) => void, siteId?: string): Promise { - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { const message = `Cannot sync '${syncFunctionLog}' because device is offline.`; this.logger.debug(message); @@ -272,7 +272,7 @@ export class CoreSyncBaseProvider { if (!siteId) { // No site ID defined, sync all sites. this.logger.debug(`Try to sync '${syncFunctionLog}' in all sites.`); - siteIds = await CoreSites.instance.getLoggedInSitesIds(); + siteIds = await CoreSites.getLoggedInSitesIds(); } else { this.logger.debug(`Try to sync '${syncFunctionLog}' in site '${siteId}'.`); siteIds = [siteId]; diff --git a/src/core/classes/delegate.ts b/src/core/classes/delegate.ts index 41aac25c5..f57b133f9 100644 --- a/src/core/classes/delegate.ts +++ b/src/core/classes/delegate.ts @@ -241,8 +241,8 @@ export class CoreDelegate { * @return Resolved when done. */ protected updateHandler(handler: HandlerType): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); - const currentSite = CoreSites.instance.getCurrentSite(); + const siteId = CoreSites.getCurrentSiteId(); + const currentSite = CoreSites.getCurrentSite(); let promise: Promise; if (this.updatePromises[siteId] && this.updatePromises[siteId][handler.name]) { @@ -252,7 +252,7 @@ export class CoreDelegate { this.updatePromises[siteId] = {}; } - if (!CoreSites.instance.isLoggedIn() || this.isFeatureDisabled(handler, currentSite!)) { + if (!CoreSites.isLoggedIn() || this.isFeatureDisabled(handler, currentSite!)) { promise = Promise.resolve(false); } else { promise = Promise.resolve(handler.isEnabled()).catch(() => false); @@ -261,7 +261,7 @@ export class CoreDelegate { // Checks if the handler is enabled. this.updatePromises[siteId][handler.name] = promise.then((enabled: boolean) => { // Check that site hasn't changed since the check started. - if (CoreSites.instance.getCurrentSiteId() === siteId) { + if (CoreSites.getCurrentSiteId() === siteId) { const key = handler[this.handlerNameProperty] || handler.name; if (enabled) { diff --git a/src/core/classes/errors/network-error.ts b/src/core/classes/errors/network-error.ts index c59c21045..c5f0e0d04 100644 --- a/src/core/classes/errors/network-error.ts +++ b/src/core/classes/errors/network-error.ts @@ -20,7 +20,7 @@ import { Translate } from '@singletons'; export class CoreNetworkError extends Error { constructor(message?: string) { - super(message || Translate.instance.instant('core.networkerrormsg')); + super(message || Translate.instant('core.networkerrormsg')); } } diff --git a/src/core/classes/ion-loading.ts b/src/core/classes/ion-loading.ts index 5f4dc9e2a..3ec3327f5 100644 --- a/src/core/classes/ion-loading.ts +++ b/src/core/classes/ion-loading.ts @@ -43,7 +43,7 @@ export class CoreIonLoadingElement { */ async present(): Promise { // Wait a bit before presenting the modal, to prevent it being displayed if dismiss is called fast. - await CoreUtils.instance.wait(40); + await CoreUtils.wait(40); if (!this.isDismissed) { this.isPresented = true; diff --git a/src/core/classes/page-items-list-manager.ts b/src/core/classes/page-items-list-manager.ts index c72a0257e..defd9ca3d 100644 --- a/src/core/classes/page-items-list-manager.ts +++ b/src/core/classes/page-items-list-manager.ts @@ -62,13 +62,13 @@ export abstract class CorePageItemsListManager { this.watchSplitViewOutlet(splitView); // Calculate current selected item. - const route = CoreNavigator.instance.getCurrentRoute({ pageComponent: this.pageComponent }); + const route = CoreNavigator.getCurrentRoute({ pageComponent: this.pageComponent }); if (route !== null && route.firstChild) { this.updateSelectedItem(route.firstChild.snapshot); } // Select default item if none is selected on a non-mobile layout. - if (!CoreScreen.instance.isMobile && this.selectedItem === null) { + if (!CoreScreen.isMobile && this.selectedItem === null) { const defaultItem = this.getDefaultItem(); if (defaultItem) { @@ -77,7 +77,7 @@ export abstract class CorePageItemsListManager { } // Log activity. - await CoreUtils.instance.ignoreErrors(this.logActivity()); + await CoreUtils.ignoreErrors(this.logActivity()); } /** @@ -128,7 +128,7 @@ export abstract class CorePageItemsListManager { */ async select(item: Item): Promise { // Get current route in the page. - const route = CoreNavigator.instance.getCurrentRoute({ pageComponent: this.pageComponent }); + const route = CoreNavigator.getCurrentRoute({ pageComponent: this.pageComponent }); if (route === null) { return; @@ -147,9 +147,9 @@ export abstract class CorePageItemsListManager { const params = this.getItemQueryParams(item); const pathPrefix = selectedItemPath ? selectedItemPath.split('/').fill('../').join('') : ''; - await CoreNavigator.instance.navigate(pathPrefix + itemPath, { + await CoreNavigator.navigate(pathPrefix + itemPath, { params, - reset: CoreScreen.instance.isTablet, + reset: CoreScreen.isTablet, }); } diff --git a/src/core/classes/queue-runner.ts b/src/core/classes/queue-runner.ts index fb70f70b9..5d9f97731 100644 --- a/src/core/classes/queue-runner.ts +++ b/src/core/classes/queue-runner.ts @@ -132,7 +132,7 @@ export class CoreQueueRunner { const item = { id, fn, - deferred: CoreUtils.instance.promiseDefer(), + deferred: CoreUtils.promiseDefer(), }; this.queue[id] = item; diff --git a/src/core/classes/site.ts b/src/core/classes/site.ts index 2548ccda4..daec4b9e6 100644 --- a/src/core/classes/site.ts +++ b/src/core/classes/site.ts @@ -136,7 +136,7 @@ export class CoreSite { * Initialize the database. */ initDB(): void { - this.db = CoreDB.instance.getDB('Site-' + this.id); + this.db = CoreDB.getDB('Site-' + this.id); } /** @@ -315,7 +315,7 @@ export class CoreSite { */ setConfig(config: CoreSiteConfig): void { if (config) { - config.tool_mobile_disabledfeatures = CoreTextUtils.instance.treatDisabledFeatures(config.tool_mobile_disabledfeatures); + config.tool_mobile_disabledfeatures = CoreTextUtils.treatDisabledFeatures(config.tool_mobile_disabledfeatures); } this.config = config; @@ -496,8 +496,8 @@ export class CoreSite { const initialToken = this.token || ''; data = data || {}; - if (!CoreApp.instance.isOnline() && this.offlineDisabled) { - throw new CoreError(Translate.instance.instant('core.errorofflinedisabled')); + if (!CoreApp.isOnline() && this.offlineDisabled) { + throw new CoreError(Translate.instant('core.errorofflinedisabled')); } // Check if the method is available, use a prefixed version if possible. @@ -510,7 +510,7 @@ export class CoreSite { } else { this.logger.error(`WS function '${method}' is not available, even in compatibility mode.`); - throw new CoreError(Translate.instance.instant('core.wsfunctionnotavailable')); + throw new CoreError(Translate.instant('core.wsfunctionnotavailable')); } } @@ -523,9 +523,9 @@ export class CoreSite { splitRequest: preSets.splitRequest, }; - if (wsPreSets.cleanUnicode && CoreTextUtils.instance.hasUnicodeData(data)) { + if (wsPreSets.cleanUnicode && CoreTextUtils.hasUnicodeData(data)) { // Data will be cleaned, notify the user. - CoreDomUtils.instance.showToast('core.unicodenotsupported', true, 3000); + CoreDomUtils.showToast('core.unicodenotsupported', true, 3000); } else { // No need to clean data in this call. wsPreSets.cleanUnicode = false; @@ -543,10 +543,10 @@ export class CoreSite { data.moodlewssettingfileurl = preSets.rewriteurls === false ? false : true; // Convert arguments to strings before starting the cache process. - data = CoreWS.instance.convertValuesToString(data, wsPreSets.cleanUnicode); + data = CoreWS.convertValuesToString(data, wsPreSets.cleanUnicode); if (data == null) { // Empty cleaned text found. - throw new CoreError(Translate.instance.instant('core.unicodenotsupportedcleanerror')); + throw new CoreError(Translate.instant('core.unicodenotsupportedcleanerror')); } const cacheId = this.getCacheId(method, data); @@ -556,14 +556,14 @@ export class CoreSite { const response = await this.ongoingRequests[cacheId]; // Clone the data, this may prevent errors if in the callback the object is modified. - return CoreUtils.instance.clone(response); + return CoreUtils.clone(response); } const promise = this.getFromCache(method, data, preSets, false).catch(() => { if (preSets.forceOffline) { // Don't call the WS, just fail. throw new CoreError( - Translate.instance.instant('core.cannotconnect', { $a: CoreSite.MINIMUM_MOODLE_VERSION }), + Translate.instant('core.cannotconnect', { $a: CoreSite.MINIMUM_MOODLE_VERSION }), ); } @@ -582,36 +582,36 @@ export class CoreSite { preSets.getFromCache = false; // Don't check cache now. Also, it will skip ongoingRequests. return this.request(method, data, preSets, true); - } else if (CoreApp.instance.isSSOAuthenticationOngoing()) { + } else if (CoreApp.isSSOAuthenticationOngoing()) { // There's an SSO authentication ongoing, wait for it to finish and try again. - return CoreApp.instance.waitForSSOAuthentication().then(() => this.request(method, data, preSets, true)); + return CoreApp.waitForSSOAuthentication().then(() => this.request(method, data, preSets, true)); } // Session expired, trigger event. CoreEvents.trigger(CoreEvents.SESSION_EXPIRED, {}, this.id); // 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.instant('core.lostconnection'); } else if (error.errorcode === 'userdeleted') { // User deleted, trigger event. CoreEvents.trigger(CoreEvents.USER_DELETED, { params: data }, this.id); - error.message = Translate.instance.instant('core.userdeleted'); + error.message = Translate.instant('core.userdeleted'); throw new CoreWSError(error); } else if (error.errorcode === 'forcepasswordchangenotice') { // Password Change Forced, trigger event. Try to get data from cache, the event will handle the error. CoreEvents.trigger(CoreEvents.PASSWORD_CHANGE_FORCED, {}, this.id); - error.message = Translate.instance.instant('core.forcepasswordchangenotice'); + error.message = Translate.instant('core.forcepasswordchangenotice'); } else if (error.errorcode === 'usernotfullysetup') { // User not fully setup, trigger event. Try to get data from cache, the event will handle the error. CoreEvents.trigger(CoreEvents.USER_NOT_FULLY_SETUP, {}, this.id); - error.message = Translate.instance.instant('core.usernotfullysetup'); + error.message = Translate.instant('core.usernotfullysetup'); } else if (error.errorcode === 'sitepolicynotagreed') { // Site policy not agreed, trigger event. CoreEvents.trigger(CoreEvents.SITE_POLICY_NOT_AGREED, {}, this.id); - error.message = Translate.instance.instant('core.login.sitepolicynotagreederror'); + error.message = Translate.instant('core.login.sitepolicynotagreederror'); throw new CoreWSError(error); - } else if (error.errorcode === 'dmlwriteexception' && CoreTextUtils.instance.hasUnicodeData(data)) { + } else if (error.errorcode === 'dmlwriteexception' && CoreTextUtils.hasUnicodeData(data)) { if (!this.cleanUnicode) { // Try again cleaning unicode. this.cleanUnicode = true; @@ -619,16 +619,16 @@ export class CoreSite { return this.request(method, data, preSets); } // This should not happen. - error.message = Translate.instance.instant('core.unicodenotsupported'); + error.message = Translate.instant('core.unicodenotsupported'); throw new CoreWSError(error); } else if (error.exception === 'required_capability_exception' || error.errorcode === 'nopermission' || error.errorcode === 'notingroup') { // Translate error messages with missing strings. if (error.message === 'error/nopermission') { - error.message = Translate.instance.instant('core.nopermissionerror'); + error.message = Translate.instant('core.nopermissionerror'); } else if (error.message === 'error/notingroup') { - error.message = Translate.instance.instant('core.notingroup'); + error.message = Translate.instant('core.notingroup'); } // Save the error instead of deleting the cache entry so the same content is displayed in offline. @@ -646,7 +646,7 @@ export class CoreSite { throw new CoreWSError(error); } - if (preSets.deleteCacheIfWSError && CoreUtils.instance.isWebServiceError(error)) { + if (preSets.deleteCacheIfWSError && CoreUtils.isWebServiceError(error)) { // Delete the cache entry and return the entry. Don't block the user with the delete. this.deleteFromCache(method, data, preSets).catch(() => { // Ignore errors. @@ -678,7 +678,7 @@ export class CoreSite { const response = await promise; // We pass back a clone of the original object, this may prevent errors if in the callback the object is modified. - return CoreUtils.instance.clone(response); + return CoreUtils.clone(response); } finally { // Make sure we don't clear the promise of a newer request that ignores the cache. if (this.ongoingRequests[cacheId] === promise) { @@ -703,7 +703,7 @@ export class CoreSite { wsPreSets: CoreWSPreSets, ): Promise { if (preSets.skipQueue || !this.wsAvailable('tool_mobile_call_external_functions')) { - return CoreWS.instance.call(method, data, wsPreSets); + return CoreWS.call(method, data, wsPreSets); } const cacheId = this.getCacheId(method, data); @@ -722,7 +722,7 @@ export class CoreSite { data, preSets, wsPreSets, - deferred: CoreUtils.instance.promiseDefer(), + deferred: CoreUtils.promiseDefer(), }; return this.enqueueRequest(request); @@ -765,7 +765,7 @@ export class CoreSite { if (requests.length == 1 && !CoreSite.REQUEST_QUEUE_FORCE_WS) { // Only one request, do a regular web service call. try { - const data = await CoreWS.instance.call(requests[0].method, requests[0].data, requests[0].wsPreSets); + const data = await CoreWS.call(requests[0].method, requests[0].data, requests[0].wsPreSets); requests[0].deferred.resolve(data); } catch (error) { @@ -809,14 +809,14 @@ export class CoreSite { }; try { - const data = await CoreWS.instance.call( + const data = await CoreWS.call( 'tool_mobile_call_external_functions', requestsData, wsPresets, ); if (!data || !data.responses) { - throw new CoreError(Translate.instance.instant('core.errorinvalidresponse')); + throw new CoreError(Translate.instant('core.errorinvalidresponse')); } requests.forEach((request, i) => { @@ -826,9 +826,9 @@ export class CoreSite { // Request not executed, enqueue again. this.enqueueRequest(request); } else if (response.error) { - request.deferred.reject(CoreTextUtils.instance.parseJSON(response.exception || '')); + request.deferred.reject(CoreTextUtils.parseJSON(response.exception || '')); } else { - let responseData = response.data ? CoreTextUtils.instance.parseJSON(response.data) : {}; + let responseData = response.data ? CoreTextUtils.parseJSON(response.data) : {}; // Match the behaviour of CoreWSProvider.call when no response is expected. const responseExpected = typeof wsPresets.responseExpected == 'undefined' || wsPresets.responseExpected; if (!responseExpected && (responseData == null || responseData === '')) { @@ -878,7 +878,7 @@ export class CoreSite { */ // eslint-disable-next-line @typescript-eslint/no-explicit-any protected getCacheId(method: string, data: any): string { - return Md5.hashAsciiStr(method + ':' + CoreUtils.instance.sortAndStringify(data)); + return Md5.hashAsciiStr(method + ':' + CoreUtils.sortAndStringify(data)); } /** @@ -931,7 +931,7 @@ export class CoreSite { const now = Date.now(); let expirationTime: number | undefined; - preSets.omitExpires = preSets.omitExpires || preSets.forceOffline || !CoreApp.instance.isOnline(); + preSets.omitExpires = preSets.omitExpires || preSets.forceOffline || !CoreApp.isOnline(); if (!preSets.omitExpires) { expirationTime = entry.expirationTime + this.getExpirationDelay(preSets.updateFrequency); @@ -951,7 +951,7 @@ export class CoreSite { this.logger.info(`Cached element found, id: ${id}. Expires in expires in ${expires} seconds`); } - return CoreTextUtils.instance.parseJSON(entry.data, {}); + return CoreTextUtils.parseJSON(entry.data, {}); } throw new CoreError('Cache entry not valid.'); @@ -997,7 +997,7 @@ export class CoreSite { if (preSets.uniqueCacheKey) { // Cache key must be unique, delete all entries with same cache key. - await CoreUtils.instance.ignoreErrors(this.deleteFromCache(method, data, preSets, true)); + await CoreUtils.ignoreErrors(this.deleteFromCache(method, data, preSets, true)); } // Since 3.7, the expiration time contains the time the entry is modified instead of the expiration time. @@ -1091,7 +1091,7 @@ export class CoreSite { options.fileArea = 'draft'; } - return CoreWS.instance.uploadFile(filePath, options, { + return CoreWS.uploadFile(filePath, options, { siteUrl: this.siteUrl, wsToken: this.token || '', }, onProgress); @@ -1195,7 +1195,7 @@ export class CoreSite { const accessKey = this.tokenPluginFileWorks || typeof this.tokenPluginFileWorks == 'undefined' ? this.infos && this.infos.userprivateaccesskey : undefined; - return CoreUrlUtils.instance.fixPluginfileURL(url, this.token || '', this.siteUrl, accessKey); + return CoreUrlUtils.fixPluginfileURL(url, this.token || '', this.siteUrl, accessKey); } /** @@ -1204,7 +1204,7 @@ export class CoreSite { * @return Promise to be resolved when the DB is deleted. */ async deleteDB(): Promise { - await CoreDB.instance.deleteDB('Site-' + this.id); + await CoreDB.deleteDB('Site-' + this.id); } /** @@ -1213,14 +1213,14 @@ export class CoreSite { * @return Promise to be resolved when the DB is deleted. */ async deleteFolder(): Promise { - if (!CoreFile.instance.isAvailable() || !this.id) { + if (!CoreFile.isAvailable() || !this.id) { return; } - const siteFolder = CoreFile.instance.getSiteFolder(this.id); + const siteFolder = CoreFile.getSiteFolder(this.id); // Ignore any errors, removeDir fails if folder doesn't exists. - await CoreUtils.instance.ignoreErrors(CoreFile.instance.removeDir(siteFolder)); + await CoreUtils.ignoreErrors(CoreFile.removeDir(siteFolder)); } /** @@ -1229,10 +1229,10 @@ export class CoreSite { * @return Promise resolved with the site space usage (size). */ getSpaceUsage(): Promise { - if (CoreFile.instance.isAvailable() && this.id) { - const siteFolderPath = CoreFile.instance.getSiteFolder(this.id); + if (CoreFile.isAvailable() && this.id) { + const siteFolderPath = CoreFile.getSiteFolder(this.id); - return CoreFile.instance.getDirectorySize(siteFolderPath).catch(() => 0); + return CoreFile.getDirectorySize(siteFolderPath).catch(() => 0); } else { return Promise.resolve(0); } @@ -1272,7 +1272,7 @@ export class CoreSite { getDocsUrl(page?: string): Promise { const release = this.infos?.release ? this.infos.release : undefined; - return CoreUrlUtils.instance.getDocsUrl(release, page); + return CoreUrlUtils.getDocsUrl(release, page); } /** @@ -1284,7 +1284,7 @@ export class CoreSite { * @return URL with params. */ createSiteUrl(path: string, params?: CoreUrlParams, anchor?: string): string { - return CoreUrlUtils.instance.addParamsToUrl(this.siteUrl + path, params, anchor); + return CoreUrlUtils.addParamsToUrl(this.siteUrl + path, params, anchor); } /** @@ -1305,7 +1305,7 @@ export class CoreSite { let data; try { - const response = await CoreWS.instance.sendHTTPRequest(checkUrl, { + const response = await CoreWS.sendHTTPRequest(checkUrl, { method: 'post', data: { service }, }); @@ -1322,7 +1322,7 @@ export class CoreSite { if (typeof data != 'undefined' && data.errorcode === 'requirecorrectaccess') { if (!retrying) { - this.siteUrl = CoreUrlUtils.instance.addOrRemoveWWW(this.siteUrl); + this.siteUrl = CoreUrlUtils.addOrRemoveWWW(this.siteUrl); return this.checkLocalMobilePlugin(true); } else { @@ -1338,18 +1338,18 @@ export class CoreSite { switch (code) { case 1: // Site in maintenance mode. - throw new CoreError(Translate.instance.instant('core.login.siteinmaintenance')); + throw new CoreError(Translate.instant('core.login.siteinmaintenance')); case 2: // Web services not enabled. - throw new CoreError(Translate.instance.instant('core.login.webservicesnotenabled')); + throw new CoreError(Translate.instant('core.login.webservicesnotenabled')); case 3: // Extended service not enabled, but the official is enabled. return { code: 0 }; case 4: // Neither extended or official services enabled. - throw new CoreError(Translate.instance.instant('core.login.mobileservicesnotenabled')); + throw new CoreError(Translate.instant('core.login.mobileservicesnotenabled')); default: - throw new CoreError(Translate.instance.instant('core.unexpectederror')); + throw new CoreError(Translate.instant('core.unexpectederror')); } } else { return { code, service, coreSupported: !!data.coresupported }; @@ -1409,8 +1409,8 @@ export class CoreSite { return false; } - const siteUrl = CoreTextUtils.instance.addEndingSlash(CoreUrlUtils.instance.removeProtocolAndWWW(this.siteUrl)); - url = CoreTextUtils.instance.addEndingSlash(CoreUrlUtils.instance.removeProtocolAndWWW(url)); + const siteUrl = CoreTextUtils.addEndingSlash(CoreUrlUtils.removeProtocolAndWWW(this.siteUrl)); + url = CoreTextUtils.addEndingSlash(CoreUrlUtils.removeProtocolAndWWW(url)); return url.indexOf(siteUrl) == 0; } @@ -1428,7 +1428,7 @@ export class CoreSite { let config: CoreSitePublicConfigResponse | undefined; try { - config = await CoreWS.instance.callAjax('tool_mobile_get_public_config', {}, preSets); + config = await CoreWS.callAjax('tool_mobile_get_public_config', {}, preSets); } catch (error) { if ((!this.getInfo() || this.isVersionGreaterEqualThan('3.8')) && error && error.errorcode == 'codingerror') { // This error probably means that there is a redirect in the site. Try to use a GET request. @@ -1436,7 +1436,7 @@ export class CoreSite { preSets.useGet = true; try { - config = await CoreWS.instance.callAjax('tool_mobile_get_public_config', {}, preSets); + config = await CoreWS.callAjax('tool_mobile_get_public_config', {}, preSets); } catch (error2) { if (this.getInfo() && this.isVersionGreaterEqualThan('3.8')) { // GET is supported, return the second error. @@ -1533,8 +1533,8 @@ export class CoreSite { if (alertMessage) { // Show an alert first. - const alert = await CoreDomUtils.instance.showAlert( - Translate.instance.instant('core.notice'), + const alert = await CoreDomUtils.showAlert( + Translate.instant('core.notice'), alertMessage, undefined, 3000, @@ -1545,9 +1545,9 @@ export class CoreSite { // Open the URL. if (inApp) { - return CoreUtils.instance.openInApp(url, options); + return CoreUtils.openInApp(url, options); } else { - return CoreUtils.instance.openInBrowser(url); + return CoreUtils.openInBrowser(url); } } @@ -1570,9 +1570,9 @@ export class CoreSite { return this.openWithAutoLogin(inApp, url, options, alertMessage); } else { if (inApp) { - return Promise.resolve(CoreUtils.instance.openInApp(url, options)); + return Promise.resolve(CoreUtils.openInApp(url, options)); } else { - CoreUtils.instance.openInBrowser(url); + CoreUtils.openInBrowser(url); } } } @@ -1669,7 +1669,7 @@ export class CoreSite { return false; } - const regEx = new RegExp('(,|^)' + CoreTextUtils.instance.escapeForRegex(name) + '(,|$)', 'g'); + const regEx = new RegExp('(,|^)' + CoreTextUtils.escapeForRegex(name) + '(,|$)', 'g'); return !!disabledFeatures.match(regEx); } @@ -1754,7 +1754,7 @@ export class CoreSite { */ async getAutoLoginUrl(url: string, showModal: boolean = true): Promise { if (!this.privateToken || !this.wsAvailable('tool_mobile_get_autologin_key') || (this.lastAutoLogin && - CoreTimeUtils.instance.timestamp() - this.lastAutoLogin < CoreConstants.SECONDS_MINUTE * 6)) { + CoreTimeUtils.timestamp() - this.lastAutoLogin < CoreConstants.SECONDS_MINUTE * 6)) { // No private token, WS not available or last auto-login was less than 6 minutes ago. Don't change the URL. return url; } @@ -1766,7 +1766,7 @@ export class CoreSite { let modal: CoreIonLoadingElement | undefined; if (showModal) { - modal = await CoreDomUtils.instance.showModalLoading(); + modal = await CoreDomUtils.showModalLoading(); } try { @@ -1778,7 +1778,7 @@ export class CoreSite { return url; } - this.lastAutoLogin = CoreTimeUtils.instance.timestamp(); + this.lastAutoLogin = CoreTimeUtils.timestamp(); return data.autologinurl + '?userid=' + userId + '&key=' + data.key + '&urltogo=' + encodeURIComponent(url); } catch (error) { @@ -1908,7 +1908,7 @@ export class CoreSite { updateFrequency = updateFrequency || CoreSite.FREQUENCY_USUALLY; let expirationDelay = this.UPDATE_FREQUENCIES[updateFrequency] || this.UPDATE_FREQUENCIES[CoreSite.FREQUENCY_USUALLY]; - if (CoreApp.instance.isNetworkAccessLimited()) { + if (CoreApp.isNetworkAccessLimited()) { // Not WiFi, increase the expiration delay a 50% to decrease the data usage in this case. expirationDelay *= 1.5; } @@ -1923,7 +1923,7 @@ export class CoreSite { * @return Promise resolved with boolean: whether it works or not. */ checkTokenPluginFile(url: string): Promise { - if (!CoreUrlUtils.instance.canUseTokenPluginFile(url, this.siteUrl, this.infos && this.infos.userprivateaccesskey)) { + if (!CoreUrlUtils.canUseTokenPluginFile(url, this.siteUrl, this.infos && this.infos.userprivateaccesskey)) { // Cannot use tokenpluginfile. return Promise.resolve(false); } else if (typeof this.tokenPluginFileWorks != 'undefined') { @@ -1932,14 +1932,14 @@ export class CoreSite { } else if (this.tokenPluginFileWorksPromise) { // Check ongoing, use the same promise. return this.tokenPluginFileWorksPromise; - } else if (!CoreApp.instance.isOnline()) { + } else if (!CoreApp.isOnline()) { // Not online, cannot check it. Assume it's working, but don't save the result. return Promise.resolve(true); } url = this.fixPluginfileURL(url); - this.tokenPluginFileWorksPromise = CoreWS.instance.urlWorks(url).then((result) => { + this.tokenPluginFileWorksPromise = CoreWS.urlWorks(url).then((result) => { this.tokenPluginFileWorks = result; return result; diff --git a/src/core/classes/sqlitedb.ts b/src/core/classes/sqlitedb.ts index dda138da6..4aa39378c 100644 --- a/src/core/classes/sqlitedb.ts +++ b/src/core/classes/sqlitedb.ts @@ -787,8 +787,8 @@ export class SQLiteDB { * Initialize the database. */ init(): void { - this.promise = Platform.instance.ready() - .then(() => SQLite.instance.create({ + this.promise = Platform.ready() + .then(() => SQLite.create({ name: this.name, location: 'default', })) diff --git a/src/core/classes/tabs.ts b/src/core/classes/tabs.ts index f48fae07b..ea2395b39 100644 --- a/src/core/classes/tabs.ts +++ b/src/core/classes/tabs.ts @@ -98,12 +98,12 @@ export class CoreTabsBaseComponent implements OnInit, Aft * Component being initialized. */ ngOnInit(): void { - this.direction = Platform.instance.isRTL ? 'rtl' : 'ltr'; + this.direction = Platform.isRTL ? 'rtl' : 'ltr'; // Change the side when the language changes. - this.languageChangedSubscription = Translate.instance.onLangChange.subscribe(() => { + this.languageChangedSubscription = Translate.onLangChange.subscribe(() => { setTimeout(() => { - this.direction = Platform.instance.isRTL ? 'rtl' : 'ltr'; + this.direction = Platform.isRTL ? 'rtl' : 'ltr'; }); }); } @@ -179,7 +179,7 @@ export class CoreTabsBaseComponent implements OnInit, Aft * Register back button action. */ protected registerBackButtonAction(): void { - this.unregisterBackButtonAction = CoreApp.instance.registerBackButtonAction(() => { + this.unregisterBackButtonAction = CoreApp.registerBackButtonAction(() => { // The previous page in history is not the last one, we need the previous one. if (this.selectHistory.length > 1) { const tabIndex = this.selectHistory[this.selectHistory.length - 2]; @@ -373,7 +373,7 @@ export class CoreTabsBaseComponent implements OnInit, Aft return; } - const fontSize = await CoreConfig.instance.get(CoreConstants.SETTINGS_FONT_SIZE, CoreConstants.CONFIG.font_sizes[0]); + const fontSize = await CoreConfig.get(CoreConstants.SETTINGS_FONT_SIZE, CoreConstants.CONFIG.font_sizes[0]); this.maxSlides = Math.floor(width / (fontSize / CoreConstants.CONFIG.font_sizes[0] * CoreTabsBaseComponent.MIN_TAB_WIDTH)); } diff --git a/src/core/components/attachments/attachments.ts b/src/core/components/attachments/attachments.ts index 6bcfd8666..41d62f071 100644 --- a/src/core/components/attachments/attachments.ts +++ b/src/core/components/attachments/attachments.ts @@ -65,26 +65,26 @@ export class CoreAttachmentsComponent implements OnInit { this.maxSize = this.maxSize !== null ? Number(this.maxSize) : NaN; if (this.maxSize === 0) { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); const siteInfo = currentSite?.getInfo(); if (siteInfo?.usermaxuploadfilesize) { this.maxSize = siteInfo.usermaxuploadfilesize; - this.maxSizeReadable = CoreTextUtils.instance.bytesToSize(this.maxSize, 2); + this.maxSizeReadable = CoreTextUtils.bytesToSize(this.maxSize, 2); } else { - this.maxSizeReadable = Translate.instance.instant('core.unknown'); + this.maxSizeReadable = Translate.instant('core.unknown'); } } else if (this.maxSize > 0) { - this.maxSizeReadable = CoreTextUtils.instance.bytesToSize(this.maxSize, 2); + this.maxSizeReadable = CoreTextUtils.bytesToSize(this.maxSize, 2); } else if (this.maxSize === -1) { - this.maxSizeReadable = Translate.instance.instant('core.unlimited'); + this.maxSizeReadable = Translate.instant('core.unlimited'); } else { - this.maxSizeReadable = Translate.instance.instant('core.unknown'); + this.maxSizeReadable = Translate.instant('core.unknown'); } if (this.maxSubmissions === undefined || this.maxSubmissions < 0) { this.maxSubmissionsReadable = this.maxSubmissions === undefined ? - Translate.instance.instant('core.unknown') : undefined; + Translate.instant('core.unknown') : undefined; this.unlimitedFiles = true; } else { this.maxSubmissionsReadable = String(this.maxSubmissions); @@ -93,7 +93,7 @@ export class CoreAttachmentsComponent implements OnInit { this.acceptedTypes = this.acceptedTypes?.trim(); if (this.acceptedTypes && this.acceptedTypes != '*') { - this.fileTypes = CoreFileUploader.instance.prepareFiletypeList(this.acceptedTypes); + this.fileTypes = CoreFileUploader.prepareFiletypeList(this.acceptedTypes); } } @@ -103,8 +103,8 @@ export class CoreAttachmentsComponent implements OnInit { async add(): Promise { const allowOffline = !!this.allowOffline && this.allowOffline !== 'false'; - if (!allowOffline && !CoreApp.instance.isOnline()) { - CoreDomUtils.instance.showErrorModal('core.fileuploader.errormustbeonlinetoupload', true); + if (!allowOffline && !CoreApp.isOnline()) { + CoreDomUtils.showErrorModal('core.fileuploader.errormustbeonlinetoupload', true); return; } @@ -112,11 +112,11 @@ export class CoreAttachmentsComponent implements OnInit { const mimetypes = this.fileTypes && this.fileTypes.mimetypes; try { - const result = await CoreFileUploaderHelper.instance.selectFile(this.maxSize, allowOffline, undefined, mimetypes); + const result = await CoreFileUploaderHelper.selectFile(this.maxSize, allowOffline, undefined, mimetypes); this.files?.push(result); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error selecting file.'); + CoreDomUtils.showErrorModalDefault(error, 'Error selecting file.'); } } @@ -131,7 +131,7 @@ export class CoreAttachmentsComponent implements OnInit { if (askConfirm) { try { - await CoreDomUtils.instance.showDeleteConfirm('core.confirmdeletefile'); + await CoreDomUtils.showDeleteConfirm('core.confirmdeletefile'); } catch { // User cancelled. return; diff --git a/src/core/components/context-menu/context-menu-popover.ts b/src/core/components/context-menu/context-menu-popover.ts index 3a8373981..17e6e1885 100644 --- a/src/core/components/context-menu/context-menu-popover.ts +++ b/src/core/components/context-menu/context-menu-popover.ts @@ -44,7 +44,7 @@ export class CoreContextMenuPopoverComponent { * Close the popover. */ closeMenu(item?: CoreContextMenuItemComponent): void { - PopoverController.instance.dismiss(item); + PopoverController.dismiss(item); } /** diff --git a/src/core/components/context-menu/context-menu.ts b/src/core/components/context-menu/context-menu.ts index 4deb00e33..734b11b0e 100644 --- a/src/core/components/context-menu/context-menu.ts +++ b/src/core/components/context-menu/context-menu.ts @@ -60,9 +60,9 @@ export class CoreContextMenuComponent implements OnInit, OnDestroy { }); // Calculate the unique ID. - this.uniqueId = 'core-context-menu-' + CoreUtils.instance.getUniqueId('CoreContextMenuComponent'); + this.uniqueId = 'core-context-menu-' + CoreUtils.getUniqueId('CoreContextMenuComponent'); - this.instanceId = CoreDomUtils.instance.storeInstanceByElement(elementRef.nativeElement, this); + this.instanceId = CoreDomUtils.storeInstanceByElement(elementRef.nativeElement, this); } /** @@ -70,7 +70,7 @@ export class CoreContextMenuComponent implements OnInit, OnDestroy { */ ngOnInit(): void { this.icon = this.icon || 'ellipsis-vertical'; - this.ariaLabel = this.ariaLabel || this.title || Translate.instance.instant('core.displayoptions'); + this.ariaLabel = this.ariaLabel || this.title || Translate.instant('core.displayoptions'); } /** @@ -177,7 +177,7 @@ export class CoreContextMenuComponent implements OnInit, OnDestroy { */ async showContextMenu(event: MouseEvent): Promise { if (!this.expanded) { - const popover = await PopoverController.instance.create( + const popover = await PopoverController.create( { event, component: CoreContextMenuPopoverComponent, @@ -206,7 +206,7 @@ export class CoreContextMenuComponent implements OnInit, OnDestroy { * Component destroyed. */ ngOnDestroy(): void { - CoreDomUtils.instance.removeInstanceById(this.instanceId); + CoreDomUtils.removeInstanceById(this.instanceId); this.removeMergedItems(); } diff --git a/src/core/components/dynamic-component/dynamic-component.ts b/src/core/components/dynamic-component/dynamic-component.ts index b4ffa9f6d..0057964f1 100644 --- a/src/core/components/dynamic-component/dynamic-component.ts +++ b/src/core/components/dynamic-component/dynamic-component.ts @@ -119,8 +119,8 @@ export class CoreDynamicComponent implements OnChanges, DoCheck { const changes = this.differ.diff(this.data || {}); if (changes) { this.setInputData(); - if (this.instance.ngOnChanges) { - this.instance.ngOnChanges(CoreDomUtils.instance.createChangesFromKeyValueDiff(changes)); + if (this.ngOnChanges) { + this.ngOnChanges(CoreDomUtils.createChangesFromKeyValueDiff(changes)); } } } diff --git a/src/core/components/file/file.ts b/src/core/components/file/file.ts index 60ad14966..b821892c1 100644 --- a/src/core/components/file/file.ts +++ b/src/core/components/file/file.ts @@ -72,35 +72,35 @@ export class CoreFileComponent implements OnInit, OnDestroy { return; } - this.canDelete = CoreUtils.instance.isTrueOrOne(this.canDelete); - this.alwaysDownload = CoreUtils.instance.isTrueOrOne(this.alwaysDownload); - this.canDownload = CoreUtils.instance.isTrueOrOne(this.canDownload); + this.canDelete = CoreUtils.isTrueOrOne(this.canDelete); + this.alwaysDownload = CoreUtils.isTrueOrOne(this.alwaysDownload); + this.canDownload = CoreUtils.isTrueOrOne(this.canDownload); this.fileUrl = this.file.fileurl; this.timemodified = this.file.timemodified || 0; - this.siteId = CoreSites.instance.getCurrentSiteId(); + this.siteId = CoreSites.getCurrentSiteId(); this.fileSize = this.file.filesize; this.fileName = this.file.filename || ''; - if (CoreUtils.instance.isTrueOrOne(this.showSize) && this.fileSize && this.fileSize >= 0) { - this.fileSizeReadable = CoreTextUtils.instance.bytesToSize(this.fileSize, 2); + if (CoreUtils.isTrueOrOne(this.showSize) && this.fileSize && this.fileSize >= 0) { + this.fileSizeReadable = CoreTextUtils.bytesToSize(this.fileSize, 2); } - this.showTime = CoreUtils.instance.isTrueOrOne(this.showTime) && this.timemodified > 0; + this.showTime = CoreUtils.isTrueOrOne(this.showTime) && this.timemodified > 0; if (this.file.isexternalfile) { this.alwaysDownload = true; // Always show the download button in external files. } - this.fileIcon = this.file.mimetype ? CoreMimetypeUtils.instance.getMimetypeIcon(this.file.mimetype) : - CoreMimetypeUtils.instance.getFileIcon(this.fileName); + this.fileIcon = this.file.mimetype ? CoreMimetypeUtils.getMimetypeIcon(this.file.mimetype) : + CoreMimetypeUtils.getFileIcon(this.fileName); if (this.canDownload) { this.calculateState(); try { // Update state when receiving events about this file. - const eventName = await CoreFilepool.instance.getFileEventNameByUrl(this.siteId, this.fileUrl); + const eventName = await CoreFilepool.getFileEventNameByUrl(this.siteId, this.fileUrl); this.observer = CoreEvents.on(eventName, () => { this.calculateState(); @@ -121,9 +121,9 @@ export class CoreFileComponent implements OnInit, OnDestroy { return; } - const state = await CoreFilepool.instance.getFileStateByUrl(this.siteId, this.fileUrl, this.timemodified); + const state = await CoreFilepool.getFileStateByUrl(this.siteId, this.fileUrl, this.timemodified); - const site = await CoreSites.instance.getSite(this.siteId); + const site = await CoreSites.getSite(this.siteId); this.canDownload = site.canDownloadFiles(); @@ -137,13 +137,13 @@ export class CoreFileComponent implements OnInit, OnDestroy { * @return Promise resolved when file is opened. */ protected openFile(): Promise { - return CoreFileHelper.instance.downloadAndOpenFile(this.file!, this.component, this.componentId, this.state, (event) => { + return CoreFileHelper.downloadAndOpenFile(this.file!, this.component, this.componentId, this.state, (event) => { if (event && 'calculating' in event && event.calculating) { // The process is calculating some data required for the download, show the spinner. this.isDownloading = true; } }).catch((error) => { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); }); } @@ -167,18 +167,18 @@ export class CoreFileComponent implements OnInit, OnDestroy { if (!this.canDownload || !this.state || this.state == CoreConstants.NOT_DOWNLOADABLE) { // File cannot be downloaded, just open it. - if (CoreUrlUtils.instance.isLocalFileUrl(this.fileUrl)) { - CoreUtils.instance.openFile(this.fileUrl); + if (CoreUrlUtils.isLocalFileUrl(this.fileUrl)) { + CoreUtils.openFile(this.fileUrl); } else { - CoreUtils.instance.openOnlineFile(CoreUrlUtils.instance.unfixPluginfileURL(this.fileUrl)); + CoreUtils.openOnlineFile(CoreUrlUtils.unfixPluginfileURL(this.fileUrl)); } return; } - if (!CoreApp.instance.isOnline() && (!openAfterDownload || (openAfterDownload && - !CoreFileHelper.instance.isStateDownloaded(this.state)))) { - CoreDomUtils.instance.showErrorModal('core.networkerrormsg', true); + if (!CoreApp.isOnline() && (!openAfterDownload || (openAfterDownload && + !CoreFileHelper.isStateDownloaded(this.state)))) { + CoreDomUtils.showErrorModal('core.networkerrormsg', true); return; } @@ -188,25 +188,25 @@ export class CoreFileComponent implements OnInit, OnDestroy { try { await this.openFile(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); } } else { try { // File doesn't need to be opened (it's a prefetch). Show confirm modal if file size is defined and it's big. - const size = await CorePluginFileDelegate.instance.getFileSize(this.file, this.siteId); + const size = await CorePluginFileDelegate.getFileSize(this.file, this.siteId); if (size) { - await CoreDomUtils.instance.confirmDownloadSize({ size: size, total: true }); + await CoreDomUtils.confirmDownloadSize({ size: size, total: true }); } // User confirmed, add the file to queue. // @todo: Is the invalidate really needed? - await CoreUtils.instance.ignoreErrors(CoreFilepool.instance.invalidateFileByUrl(this.siteId, this.fileUrl)); + await CoreUtils.ignoreErrors(CoreFilepool.invalidateFileByUrl(this.siteId, this.fileUrl)); this.isDownloading = true; try { - await CoreFilepool.instance.addToQueueByUrl( + await CoreFilepool.addToQueueByUrl( this.siteId, this.fileUrl, this.component, @@ -218,11 +218,11 @@ export class CoreFileComponent implements OnInit, OnDestroy { this.file, ); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); this.calculateState(); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); } } } diff --git a/src/core/components/files/files.ts b/src/core/components/files/files.ts index 0a3e6f4f3..694b764f6 100644 --- a/src/core/components/files/files.ts +++ b/src/core/components/files/files.ts @@ -53,7 +53,7 @@ export class CoreFilesComponent implements OnInit, DoCheck { * Component being initialized. */ ngOnInit(): void { - if (CoreUtils.instance.isTrueOrOne(this.showInline) && this.files) { + if (CoreUtils.isTrueOrOne(this.showInline) && this.files) { this.renderInlineFiles(); } } @@ -62,7 +62,7 @@ export class CoreFilesComponent implements OnInit, DoCheck { * Detect and act upon changes that Angular can’t or won’t detect on its own (objects and arrays). */ ngDoCheck(): void { - if (CoreUtils.instance.isTrueOrOne(this.showInline) && this.files) { + if (CoreUtils.isTrueOrOne(this.showInline) && this.files) { // Check if there's any change in the files array. const changes = this.differ.diff(this.files); if (changes) { @@ -76,7 +76,7 @@ export class CoreFilesComponent implements OnInit, DoCheck { */ protected renderInlineFiles(): void { this.contentText = this.files!.reduce((previous, file) => { - const text = CoreMimetypeUtils.instance.getEmbeddedHtml(file); + const text = CoreMimetypeUtils.getEmbeddedHtml(file); return text ? previous + '
' + text : previous; }, ''); diff --git a/src/core/components/iframe/iframe.ts b/src/core/components/iframe/iframe.ts index d934b4174..3269f7629 100644 --- a/src/core/components/iframe/iframe.ts +++ b/src/core/components/iframe/iframe.ts @@ -67,16 +67,16 @@ export class CoreIframeComponent implements OnChanges { this.initialized = true; - this.iframeWidth = (this.iframeWidth && CoreDomUtils.instance.formatPixelsSize(this.iframeWidth)) || '100%'; - this.iframeHeight = (this.iframeHeight && CoreDomUtils.instance.formatPixelsSize(this.iframeHeight)) || '100%'; - this.allowFullscreen = CoreUtils.instance.isTrueOrOne(this.allowFullscreen); + this.iframeWidth = (this.iframeWidth && CoreDomUtils.formatPixelsSize(this.iframeWidth)) || '100%'; + this.iframeHeight = (this.iframeHeight && CoreDomUtils.formatPixelsSize(this.iframeHeight)) || '100%'; + this.allowFullscreen = CoreUtils.isTrueOrOne(this.allowFullscreen); // Show loading only with external URLs. - this.loading = !this.src || !CoreUrlUtils.instance.isLocalFileUrl(this.src); + this.loading = !this.src || !CoreUrlUtils.isLocalFileUrl(this.src); // @todo const navCtrl = this.svComponent ? this.svComponent.getMasterNav() : this.navCtrl; - // CoreIframeUtils.instance.treatFrame(iframe, false, this.navCtrl); - CoreIframeUtils.instance.treatFrame(iframe, false); + // CoreIframeUtils.treatFrame(iframe, false, this.navCtrl); + CoreIframeUtils.treatFrame(iframe, false); iframe.addEventListener('load', () => { this.loading = false; @@ -85,7 +85,7 @@ export class CoreIframeComponent implements OnChanges { iframe.addEventListener('error', () => { this.loading = false; - CoreDomUtils.instance.showErrorModal('core.errorloadingcontent', true); + CoreDomUtils.showErrorModal('core.errorloadingcontent', true); }); if (this.loading) { @@ -100,11 +100,11 @@ export class CoreIframeComponent implements OnChanges { */ async ngOnChanges(changes: {[name: string]: SimpleChange }): Promise { if (changes.src) { - const url = CoreUrlUtils.instance.getYoutubeEmbedUrl(changes.src.currentValue) || changes.src.currentValue; + const url = CoreUrlUtils.getYoutubeEmbedUrl(changes.src.currentValue) || changes.src.currentValue; - await CoreIframeUtils.instance.fixIframeCookies(url); + await CoreIframeUtils.fixIframeCookies(url); - this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(CoreFile.instance.convertFileSrc(url)); + this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(CoreFile.convertFileSrc(url)); // Now that the URL has been set, initialize the iframe. Wait for the iframe to the added to the DOM. setTimeout(() => { diff --git a/src/core/components/infinite-loading/infinite-loading.ts b/src/core/components/infinite-loading/infinite-loading.ts index 8bec2ddb2..69addc88d 100644 --- a/src/core/components/infinite-loading/infinite-loading.ts +++ b/src/core/components/infinite-loading/infinite-loading.ts @@ -73,7 +73,7 @@ export class CoreInfiniteLoadingComponent implements OnChanges { } // Wait until next tick to allow items to render and scroll content to grow. - await CoreUtils.instance.nextTick(); + await CoreUtils.nextTick(); // Calculate distance from edge. const content = this.element.nativeElement.closest('ion-content') as IonContent; @@ -152,7 +152,7 @@ export class CoreInfiniteLoadingComponent implements OnChanges { */ protected getElementHeight(element?: ElementRef): number { if (element && element.nativeElement) { - return CoreDomUtils.instance.getElementHeight(element.nativeElement, true, true, true); + return CoreDomUtils.getElementHeight(element.nativeElement, true, true, true); } return 0; diff --git a/src/core/components/input-errors/input-errors.ts b/src/core/components/input-errors/input-errors.ts index a3db6a307..5024bd9eb 100644 --- a/src/core/components/input-errors/input-errors.ts +++ b/src/core/components/input-errors/input-errors.ts @@ -56,13 +56,13 @@ export class CoreInputErrorsComponent implements OnChanges { protected initErrorMessages(): void { this.errorMessages = this.errorMessages || {}; - this.errorMessages.required = this.errorMessages.required || Translate.instance.instant('core.required'); - this.errorMessages.email = this.errorMessages.email || Translate.instance.instant('core.login.invalidemail'); - this.errorMessages.date = this.errorMessages.date || Translate.instance.instant('core.login.invaliddate'); - this.errorMessages.datetime = this.errorMessages.datetime || Translate.instance.instant('core.login.invaliddate'); - this.errorMessages.datetimelocal = this.errorMessages.datetimelocal || Translate.instance.instant('core.login.invaliddate'); - this.errorMessages.time = this.errorMessages.time || Translate.instance.instant('core.login.invalidtime'); - this.errorMessages.url = this.errorMessages.url || Translate.instance.instant('core.login.invalidurl'); + this.errorMessages.required = this.errorMessages.required || Translate.instant('core.required'); + this.errorMessages.email = this.errorMessages.email || Translate.instant('core.login.invalidemail'); + this.errorMessages.date = this.errorMessages.date || Translate.instant('core.login.invaliddate'); + this.errorMessages.datetime = this.errorMessages.datetime || Translate.instant('core.login.invaliddate'); + this.errorMessages.datetimelocal = this.errorMessages.datetimelocal || Translate.instant('core.login.invaliddate'); + this.errorMessages.time = this.errorMessages.time || Translate.instant('core.login.invalidtime'); + this.errorMessages.url = this.errorMessages.url || Translate.instant('core.login.invalidurl'); // Set empty values by default, the default error messages will be built in the template when needed. this.errorMessages.max = this.errorMessages.max || ''; diff --git a/src/core/components/loading/loading.ts b/src/core/components/loading/loading.ts index f40623dbf..2c0e80675 100644 --- a/src/core/components/loading/loading.ts +++ b/src/core/components/loading/loading.ts @@ -58,7 +58,7 @@ export class CoreLoadingComponent implements OnInit, OnChanges, AfterViewInit { this.element = element.nativeElement; // Calculate the unique ID. - this.uniqueId = 'core-loading-content-' + CoreUtils.instance.getUniqueId('CoreLoadingComponent'); + this.uniqueId = 'core-loading-content-' + CoreUtils.getUniqueId('CoreLoadingComponent'); } /** @@ -67,7 +67,7 @@ export class CoreLoadingComponent implements OnInit, OnChanges, AfterViewInit { ngOnInit(): void { if (!this.message) { // Default loading message. - this.message = Translate.instance.instant('core.loading'); + this.message = Translate.instant('core.loading'); } } diff --git a/src/core/components/local-file/local-file.ts b/src/core/components/local-file/local-file.ts index 66f6500ac..a8a15c27f 100644 --- a/src/core/components/local-file/local-file.ts +++ b/src/core/components/local-file/local-file.ts @@ -59,7 +59,7 @@ export class CoreLocalFileComponent implements OnInit { * Component being initialized. */ async ngOnInit(): Promise { - this.manage = CoreUtils.instance.isTrueOrOne(this.manage); + this.manage = CoreUtils.isTrueOrOne(this.manage); if (!this.file) { return; @@ -68,12 +68,12 @@ export class CoreLocalFileComponent implements OnInit { this.loadFileBasicData(this.file); // Get the size and timemodified. - const metadata = await CoreFile.instance.getMetadata(this.file); + const metadata = await CoreFile.getMetadata(this.file); if (metadata.size >= 0) { - this.size = CoreTextUtils.instance.bytesToSize(metadata.size, 2); + this.size = CoreTextUtils.bytesToSize(metadata.size, 2); } - this.timemodified = CoreTimeUtils.instance.userDate(metadata.modificationTime.getTime(), 'core.strftimedatetimeshort'); + this.timemodified = CoreTimeUtils.userDate(metadata.modificationTime.getTime(), 'core.strftimedatetimeshort'); } @@ -82,11 +82,11 @@ export class CoreLocalFileComponent implements OnInit { */ protected loadFileBasicData(file: FileEntry): void { this.fileName = file.name; - this.fileIcon = CoreMimetypeUtils.instance.getFileIcon(file.name); - this.fileExtension = CoreMimetypeUtils.instance.getFileExtension(file.name); + this.fileIcon = CoreMimetypeUtils.getFileIcon(file.name); + this.fileExtension = CoreMimetypeUtils.getFileExtension(file.name); // Let's calculate the relative path for the file. - this.relativePath = CoreFile.instance.removeBasePath(file.toURL()); + this.relativePath = CoreFile.removeBasePath(file.toURL()); if (!this.relativePath) { // Didn't find basePath, use fullPath but if the user tries to manage the file it'll probably fail. this.relativePath = file.fullPath; @@ -106,21 +106,21 @@ export class CoreLocalFileComponent implements OnInit { e.preventDefault(); e.stopPropagation(); - if (CoreUtils.instance.isTrueOrOne(this.overrideClick) && this.onClick.observers.length) { + if (CoreUtils.isTrueOrOne(this.overrideClick) && this.onClick.observers.length) { this.onClick.emit(); return; } - if (!CoreFileHelper.instance.isOpenableInApp(this.file!)) { + if (!CoreFileHelper.isOpenableInApp(this.file!)) { try { - await CoreFileHelper.instance.showConfirmOpenUnsupportedFile(); + await CoreFileHelper.showConfirmOpenUnsupportedFile(); } catch (error) { return; // Cancelled, stop. } } - CoreUtils.instance.openFile(this.file!.toURL()); + CoreUtils.openFile(this.file!.toURL()); } /** @@ -149,34 +149,34 @@ export class CoreLocalFileComponent implements OnInit { if (newName == this.file!.name) { // Name hasn't changed, stop. this.editMode = false; - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); return; } - const modal = await CoreDomUtils.instance.showModalLoading(); - const fileAndDir = CoreFile.instance.getFileAndDirectoryFromPath(this.relativePath!); - const newPath = CoreTextUtils.instance.concatenatePaths(fileAndDir.directory, newName); + const modal = await CoreDomUtils.showModalLoading(); + const fileAndDir = CoreFile.getFileAndDirectoryFromPath(this.relativePath!); + const newPath = CoreTextUtils.concatenatePaths(fileAndDir.directory, newName); try { // Check if there's a file with this name. - await CoreFile.instance.getFile(newPath); + await CoreFile.getFile(newPath); // There's a file with this name, show error and stop. - CoreDomUtils.instance.showErrorModal('core.errorfileexistssamename', true); + CoreDomUtils.showErrorModal('core.errorfileexistssamename', true); } catch { try { // File doesn't exist, move it. - const fileEntry = await CoreFile.instance.moveFile(this.relativePath!, newPath); + const fileEntry = await CoreFile.moveFile(this.relativePath!, newPath); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, false, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, false, CoreSites.getCurrentSiteId()); this.editMode = false; this.file = fileEntry; this.loadFileBasicData(this.file); this.onRename.emit({ file: this.file }); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errorrenamefile', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errorrenamefile', true); } } finally { modal.dismiss(); @@ -196,15 +196,15 @@ export class CoreLocalFileComponent implements OnInit { try { // Ask confirmation. - await CoreDomUtils.instance.showDeleteConfirm('core.confirmdeletefile'); + await CoreDomUtils.showDeleteConfirm('core.confirmdeletefile'); - modal = await CoreDomUtils.instance.showModalLoading('core.deleting', true); + modal = await CoreDomUtils.showModalLoading('core.deleting', true); - await CoreFile.instance.removeFile(this.relativePath!); + await CoreFile.removeFile(this.relativePath!); this.onDelete.emit(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordeletefile', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordeletefile', true); } finally { modal?.dismiss(); } diff --git a/src/core/components/mark-required/mark-required.ts b/src/core/components/mark-required/mark-required.ts index 56f6d6550..e443d6d32 100644 --- a/src/core/components/mark-required/mark-required.ts +++ b/src/core/components/mark-required/mark-required.ts @@ -51,8 +51,8 @@ export class CoreMarkRequiredComponent implements OnInit, AfterViewInit { * Component being initialized. */ ngOnInit(): void { - this.requiredLabel = Translate.instance.instant('core.required'); - this.coreMarkRequired = CoreUtils.instance.isTrueOrOne(this.coreMarkRequired); + this.requiredLabel = Translate.instant('core.required'); + this.coreMarkRequired = CoreUtils.isTrueOrOne(this.coreMarkRequired); } /** @@ -62,7 +62,7 @@ export class CoreMarkRequiredComponent implements OnInit, AfterViewInit { if (this.coreMarkRequired) { // Add the "required" to the aria-label. const ariaLabel = this.element.getAttribute('aria-label') || - CoreTextUtils.instance.cleanTags(this.element.innerHTML, true); + CoreTextUtils.cleanTags(this.element.innerHTML, true); if (ariaLabel) { this.element.setAttribute('aria-label', ariaLabel + ' ' + this.requiredLabel); } diff --git a/src/core/components/navbar-buttons/navbar-buttons.ts b/src/core/components/navbar-buttons/navbar-buttons.ts index 7697224a4..f24c05a47 100644 --- a/src/core/components/navbar-buttons/navbar-buttons.ts +++ b/src/core/components/navbar-buttons/navbar-buttons.ts @@ -68,7 +68,7 @@ export class CoreNavBarButtonsComponent implements OnInit, OnDestroy { constructor(element: ElementRef) { this.element = element.nativeElement; this.logger = CoreLogger.getInstance('CoreNavBarButtonsComponent'); - this.instanceId = CoreDomUtils.instance.storeInstanceByElement(this.element, this); + this.instanceId = CoreDomUtils.storeInstanceByElement(this.element, this); } /** @@ -96,7 +96,7 @@ export class CoreNavBarButtonsComponent implements OnInit, OnDestroy { const prepend = this.element.hasAttribute('prepend'); - this.movedChildren = CoreDomUtils.instance.moveChildren(this.element, buttonsContainer, prepend); + this.movedChildren = CoreDomUtils.moveChildren(this.element, buttonsContainer, prepend); this.showHideAllElements(); } else { @@ -139,9 +139,9 @@ export class CoreNavBarButtonsComponent implements OnInit, OnDestroy { } // Both containers have a context menu. Merge them to prevent having 2 menus at the same time. - const mainContextMenuInstance: CoreContextMenuComponent = CoreDomUtils.instance.getInstanceByElement(mainContextMenu); + const mainContextMenuInstance: CoreContextMenuComponent = CoreDomUtils.getInstanceByElement(mainContextMenu); const secondaryContextMenuInstance: CoreContextMenuComponent = - CoreDomUtils.instance.getInstanceByElement(secondaryContextMenu); + CoreDomUtils.getInstanceByElement(secondaryContextMenu); // Check that both context menus belong to the same core-tab. We shouldn't merge menus from different tabs. if (mainContextMenuInstance && secondaryContextMenuInstance) { @@ -170,7 +170,7 @@ export class CoreNavBarButtonsComponent implements OnInit, OnDestroy { } // Get the next parent page. - parentPage = CoreDomUtils.instance.closest(parentPage.parentElement, '.ion-page'); + parentPage = CoreDomUtils.closest(parentPage.parentElement, '.ion-page'); if (parentPage) { // Check if the page has a header. If it doesn't, search the next parent page. const header = this.searchHeaderInPage(parentPage); @@ -248,7 +248,7 @@ export class CoreNavBarButtonsComponent implements OnInit, OnDestroy { * Component destroyed. */ ngOnDestroy(): void { - CoreDomUtils.instance.removeInstanceById(this.instanceId); + CoreDomUtils.removeInstanceById(this.instanceId); // This component was destroyed, remove all the buttons that were moved. // The buttons can be moved outside of the current page, that's why we need to manually destroy them. diff --git a/src/core/components/navigation-bar/navigation-bar.ts b/src/core/components/navigation-bar/navigation-bar.ts index 9d7eb2ddd..71f2f28ef 100644 --- a/src/core/components/navigation-bar/navigation-bar.ts +++ b/src/core/components/navigation-bar/navigation-bar.ts @@ -46,7 +46,7 @@ export class CoreNavigationBarComponent { new EventEmitter(); // Function to call when arrow is clicked. Will receive as a param the item to load. showInfo(): void { - CoreTextUtils.instance.viewText(this.title, this.info, { + CoreTextUtils.viewText(this.title, this.info, { component: this.component, componentId: this.componentId, filter: true, diff --git a/src/core/components/recaptcha/recaptcha-modal.ts b/src/core/components/recaptcha/recaptcha-modal.ts index 29e2c4eb0..103731e99 100644 --- a/src/core/components/recaptcha/recaptcha-modal.ts +++ b/src/core/components/recaptcha/recaptcha-modal.ts @@ -42,7 +42,7 @@ export class CoreRecaptchaModalComponent implements OnDestroy { * Close modal. */ closeModal(): void { - ModalController.instance.dismiss({ + ModalController.dismiss({ expired: this.expired, value: this.value, }); diff --git a/src/core/components/recaptcha/recaptcha.ts b/src/core/components/recaptcha/recaptcha.ts index 4efe0fa59..ad9ae50c8 100644 --- a/src/core/components/recaptcha/recaptcha.ts +++ b/src/core/components/recaptcha/recaptcha.ts @@ -46,14 +46,14 @@ export class CoreRecaptchaComponent implements OnInit { * Component being initialized. */ ngOnInit(): void { - this.siteUrl = this.siteUrl || CoreSites.instance.getCurrentSite()?.getURL(); + this.siteUrl = this.siteUrl || CoreSites.getCurrentSite()?.getURL(); } /** * Initialize the lang property. */ protected async initLang(): Promise { - this.lang = await CoreLang.instance.getCurrentLanguage(); + this.lang = await CoreLang.getCurrentLanguage(); } /** @@ -61,12 +61,12 @@ export class CoreRecaptchaComponent implements OnInit { */ async answerRecaptcha(): Promise { // Set the iframe src. We use an iframe because reCaptcha V2 doesn't work with file:// protocol. - const src = CoreTextUtils.instance.concatenatePaths(this.siteUrl!, 'webservice/recaptcha.php?lang=' + this.lang); + const src = CoreTextUtils.concatenatePaths(this.siteUrl!, 'webservice/recaptcha.php?lang=' + this.lang); // Modal to answer the recaptcha. // This is because the size of the recaptcha is dynamic, so it could cause problems if it was displayed inline. - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: CoreRecaptchaModalComponent, cssClass: 'core-modal-fullscreen', componentProps: { diff --git a/src/core/components/send-message-form/send-message-form.ts b/src/core/components/send-message-form/send-message-form.ts index 06ce5ffe3..09a4db8b0 100644 --- a/src/core/components/send-message-form/send-message-form.ts +++ b/src/core/components/send-message-form/send-message-form.ts @@ -55,7 +55,7 @@ export class CoreSendMessageFormComponent implements OnInit { this.onSubmit = new EventEmitter(); this.onResize = new EventEmitter(); - CoreConfig.instance.get(CoreConstants.SETTINGS_SEND_ON_ENTER, !CoreApp.instance.isMobile()).then((sendOnEnter) => { + CoreConfig.get(CoreConstants.SETTINGS_SEND_ON_ENTER, !CoreApp.isMobile()).then((sendOnEnter) => { this.sendOnEnter = !!sendOnEnter; return; @@ -65,11 +65,11 @@ export class CoreSendMessageFormComponent implements OnInit { CoreEvents.on(CoreEvents.SEND_ON_ENTER_CHANGED, (newValue) => { this.sendOnEnter = newValue; - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } ngOnInit(): void { - this.showKeyboard = CoreUtils.instance.isTrueOrOne(this.showKeyboard); + this.showKeyboard = CoreUtils.isTrueOrOne(this.showKeyboard); } /** @@ -90,9 +90,9 @@ export class CoreSendMessageFormComponent implements OnInit { this.message = ''; // Reset the form. - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, false, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, false, CoreSites.getCurrentSiteId()); - value = CoreTextUtils.instance.replaceNewLines(value, '
'); + value = CoreTextUtils.replaceNewLines(value, '
'); this.onSubmit.emit(value); } @@ -117,7 +117,7 @@ export class CoreSendMessageFormComponent implements OnInit { if (this.sendOnEnter && !other) { // Enter clicked, send the message. this.submitForm(e); - } else if (!this.sendOnEnter && !CoreApp.instance.isMobile() && other == 'control') { + } else if (!this.sendOnEnter && !CoreApp.isMobile() && other == 'control') { // Cmd+Enter or Ctrl+Enter, send message. this.submitForm(e); } diff --git a/src/core/components/show-password/show-password.ts b/src/core/components/show-password/show-password.ts index d90cf3615..d61856779 100644 --- a/src/core/components/show-password/show-password.ts +++ b/src/core/components/show-password/show-password.ts @@ -61,7 +61,7 @@ export class CoreShowPasswordComponent implements OnInit, AfterViewInit { * Component being initialized. */ ngOnInit(): void { - this.shown = CoreUtils.instance.isTrueOrOne(this.initialShown); + this.shown = CoreUtils.isTrueOrOne(this.initialShown); this.selector = 'input[name="' + this.name + '"]'; this.setData(); } @@ -126,10 +126,10 @@ export class CoreShowPasswordComponent implements OnInit, AfterViewInit { this.shown = !this.shown; this.setData(); - if (isFocused && CoreApp.instance.isAndroid()) { + if (isFocused && CoreApp.isAndroid()) { // In Android, the keyboard is closed when the input type changes. Focus it again. setTimeout(() => { - CoreDomUtils.instance.focusElement(this.input!); + CoreDomUtils.focusElement(this.input!); }, 400); } } diff --git a/src/core/components/split-view/split-view.ts b/src/core/components/split-view/split-view.ts index 27af0425a..f5b15ab49 100644 --- a/src/core/components/split-view/split-view.ts +++ b/src/core/components/split-view/split-view.ts @@ -68,7 +68,7 @@ export class CoreSplitViewComponent implements AfterViewInit, OnDestroy { this.updateClasses(); this.outletRouteSubject.next(null); }), - CoreScreen.instance.layoutObservable.subscribe(() => this.updateClasses()), + CoreScreen.layoutObservable.subscribe(() => this.updateClasses()), ]; this.updateClasses(); @@ -113,7 +113,7 @@ export class CoreSplitViewComponent implements AfterViewInit, OnDestroy { return CoreSplitViewMode.MenuOnly; } - if (CoreScreen.instance.isMobile) { + if (CoreScreen.isMobile) { return this.contentOutlet.isActivated ? CoreSplitViewMode.ContentOnly : CoreSplitViewMode.MenuOnly; diff --git a/src/core/components/tabs-outlet/tabs-outlet.ts b/src/core/components/tabs-outlet/tabs-outlet.ts index 7567f4619..0fd52aaa9 100644 --- a/src/core/components/tabs-outlet/tabs-outlet.ts +++ b/src/core/components/tabs-outlet/tabs-outlet.ts @@ -87,7 +87,7 @@ export class CoreTabsOutletComponent extends CoreTabsBaseComponent { - return CoreNavigator.instance.navigate(tabToSelect.page, { + return CoreNavigator.navigate(tabToSelect.page, { params: tabToSelect.pageParams, }); } diff --git a/src/core/components/tabs/tab.ts b/src/core/components/tabs/tab.ts index 17876ff91..452e07c68 100644 --- a/src/core/components/tabs/tab.ts +++ b/src/core/components/tabs/tab.ts @@ -87,7 +87,7 @@ export class CoreTabComponent implements OnInit, OnDestroy, CoreTabBase { * Component being initialized. */ ngOnInit(): void { - this.id = this.id || 'core-tab-' + CoreUtils.instance.getUniqueId('CoreTabComponent'); + this.id = this.id || 'core-tab-' + CoreUtils.getUniqueId('CoreTabComponent'); this.element.setAttribute('aria-labelledby', this.id + '-tab'); this.element.setAttribute('id', this.id); @@ -136,7 +136,7 @@ export class CoreTabComponent implements OnInit, OnDestroy, CoreTabBase { protected showHideNavBarButtons(show: boolean): void { const elements = this.element.querySelectorAll('core-navbar-buttons'); elements.forEach((element) => { - const instance: CoreNavBarButtonsComponent = CoreDomUtils.instance.getInstanceByElement(element); + const instance: CoreNavBarButtonsComponent = CoreDomUtils.getInstanceByElement(element); if (instance) { instance.forceHide(!show); diff --git a/src/core/components/timer/timer.ts b/src/core/components/timer/timer.ts index 06bd8c21c..581941a70 100644 --- a/src/core/components/timer/timer.ts +++ b/src/core/components/timer/timer.ts @@ -58,7 +58,7 @@ export class CoreTimerComponent implements OnInit, OnDestroy { // Check time left every 200ms. this.timeInterval = window.setInterval(() => { - this.timeLeft = endTime - CoreTimeUtils.instance.timestamp(); + this.timeLeft = endTime - CoreTimeUtils.timestamp(); if (this.timeLeft < 0) { // Time is up! Stop the timer and call the finish function. diff --git a/src/core/components/user-avatar/user-avatar.ts b/src/core/components/user-avatar/user-avatar.ts index 88077a8f4..a89f204d5 100644 --- a/src/core/components/user-avatar/user-avatar.ts +++ b/src/core/components/user-avatar/user-avatar.ts @@ -52,7 +52,7 @@ export class CoreUserAvatarComponent implements OnInit, OnChanges, OnDestroy { protected pictureObserver: CoreEventObserver; constructor() { - this.currentUserId = CoreSites.instance.getCurrentSiteUserId(); + this.currentUserId = CoreSites.getCurrentSiteUserId(); this.pictureObserver = CoreEvents.on( CoreUserProvider.PROFILE_PICTURE_UPDATED, @@ -61,7 +61,7 @@ export class CoreUserAvatarComponent implements OnInit, OnChanges, OnDestroy { this.avatarUrl = data.picture; } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } @@ -109,7 +109,7 @@ export class CoreUserAvatarComponent implements OnInit, OnChanges, OnDestroy { return false; } - if (CoreUtils.instance.isFalseOrZero(this.user.isonline)) { + if (CoreUtils.isFalseOrZero(this.user.isonline)) { return false; } @@ -120,7 +120,7 @@ export class CoreUserAvatarComponent implements OnInit, OnChanges, OnDestroy { return this.user.lastaccess * 1000 >= time; } else { // You have to have Internet access first. - return !!this.user.isonline && CoreApp.instance.isOnline(); + return !!this.user.isonline && CoreApp.isOnline(); } } @@ -138,7 +138,7 @@ export class CoreUserAvatarComponent implements OnInit, OnChanges, OnDestroy { event.stopPropagation(); // @todo Decide which navCtrl to use. If this component is inside a split view, use the split view's master nav. - CoreNavigator.instance.navigateToSitePath('user', { + CoreNavigator.navigateToSitePath('user', { params: { userId: this.userId, courseId: this.courseId, diff --git a/src/core/directives/auto-focus.ts b/src/core/directives/auto-focus.ts index 874691689..1beefc28d 100644 --- a/src/core/directives/auto-focus.ts +++ b/src/core/directives/auto-focus.ts @@ -55,7 +55,7 @@ export class CoreAutoFocusDirective implements OnInit { * Function after the view is initialized. */ protected autoFocus(): void { - const autoFocus = CoreUtils.instance.isTrueOrOne(this.coreAutoFocus); + const autoFocus = CoreUtils.isTrueOrOne(this.coreAutoFocus); if (autoFocus) { // Wait a bit to make sure the view is loaded. setTimeout(() => { @@ -67,7 +67,7 @@ export class CoreAutoFocusDirective implements OnInit { element = this.element.querySelector('textarea') || element; } - CoreDomUtils.instance.focusElement(element); + CoreDomUtils.focusElement(element); }, 200); } } diff --git a/src/core/directives/external-content.ts b/src/core/directives/external-content.ts index fa2baff68..e8a6975d8 100644 --- a/src/core/directives/external-content.ts +++ b/src/core/directives/external-content.ts @@ -98,7 +98,7 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { newSource.setAttribute('src', url); if (type) { - if (CoreApp.instance.isAndroid() && type == 'video/quicktime') { + if (CoreApp.isAndroid() && type == 'video/quicktime') { // Fix for VideoJS/Chrome bug https://github.com/videojs/video.js/issues/423 . newSource.setAttribute('type', 'video/mp4'); } else { @@ -113,7 +113,7 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { * Get the URL that should be handled and, if valid, handle it. */ protected async checkAndHandleExternalContent(): Promise { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); const siteId = this.siteId || currentSite?.getId(); const tagName = this.element.tagName.toUpperCase(); let targetAttr; @@ -197,7 +197,7 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { return; } - const line = Platform.instance.is('tablet') || CoreApp.instance.isAndroid() ? 90 : 80; + const line = Platform.is('tablet') || CoreApp.isAndroid() ? 90 : 80; // Position all subtitles to a percentage of video height. // eslint-disable-next-line @typescript-eslint/no-explicit-any Array.from(track.cues).forEach((cue: any) => { @@ -214,8 +214,8 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { } - if (!url || !url.match(/^https?:\/\//i) || CoreUrlUtils.instance.isLocalFileUrl(url) || - (tagName === 'A' && !CoreUrlUtils.instance.isDownloadableUrl(url))) { + if (!url || !url.match(/^https?:\/\//i) || CoreUrlUtils.isLocalFileUrl(url) || + (tagName === 'A' && !CoreUrlUtils.isDownloadableUrl(url))) { this.logger.debug('Ignoring non-downloadable URL: ' + url); if (tagName === 'SOURCE') { @@ -226,9 +226,9 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { throw new CoreError('Non-downloadable URL'); } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - if (!site.canDownloadFiles() && CoreUrlUtils.instance.isPluginFileUrl(url)) { + if (!site.canDownloadFiles() && CoreUrlUtils.isPluginFileUrl(url)) { this.element.parentElement?.removeChild(this.element); // Remove element since it'll be broken. throw new CoreError('Site doesn\'t allow downloading files.'); @@ -239,7 +239,7 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { let finalUrl: string; if (targetAttr === 'src' && tagName !== 'SOURCE' && tagName !== 'TRACK' && tagName !== 'VIDEO' && tagName !== 'AUDIO') { - finalUrl = await CoreFilepool.instance.getSrcByUrl( + finalUrl = await CoreFilepool.getSrcByUrl( site.getId(), url, this.component, @@ -249,7 +249,7 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { downloadUnknown, ); } else { - finalUrl = await CoreFilepool.instance.getUrlByUrl( + finalUrl = await CoreFilepool.getUrlByUrl( site.getId(), url, this.component, @@ -259,10 +259,10 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { downloadUnknown, ); - finalUrl = CoreFile.instance.convertFileSrc(finalUrl); + finalUrl = CoreFile.convertFileSrc(finalUrl); } - if (!CoreUrlUtils.instance.isLocalFileUrl(finalUrl)) { + if (!CoreUrlUtils.isLocalFileUrl(finalUrl)) { /* In iOS, if we use the same URL in embedded file and background download then the download only downloads a few bytes (cached ones). Add a hash to the URL so both URLs are different. */ finalUrl = finalUrl + '#moodlemobile-embedded'; @@ -282,13 +282,13 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { } // Set events to download big files (not downloaded automatically). - if (!CoreUrlUtils.instance.isLocalFileUrl(finalUrl) && targetAttr != 'poster' && + if (!CoreUrlUtils.isLocalFileUrl(finalUrl) && targetAttr != 'poster' && (tagName == 'VIDEO' || tagName == 'AUDIO' || tagName == 'A' || tagName == 'SOURCE')) { const eventName = tagName == 'A' ? 'click' : 'play'; let clickableEl = this.element; if (tagName == 'SOURCE') { - clickableEl = CoreDomUtils.instance.closest(this.element, 'video,audio'); + clickableEl = CoreDomUtils.closest(this.element, 'video,audio'); if (!clickableEl) { return; } @@ -297,9 +297,9 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { clickableEl.addEventListener(eventName, () => { // User played media or opened a downloadable link. // Download the file if in wifi and it hasn't been downloaded already (for big files). - if (CoreApp.instance.isWifi()) { + if (CoreApp.isWifi()) { // We aren't using the result, so it doesn't matter which of the 2 functions we call. - CoreFilepool.instance.getUrlByUrl(site.getId(), url, this.component, this.componentId, 0, false); + CoreFilepool.getUrlByUrl(site.getId(), url, this.component, this.componentId, 0, false); } }); } @@ -327,17 +327,17 @@ export class CoreExternalContentDirective implements AfterViewInit, OnChanges { return; } - urls = CoreUtils.instance.uniqueArray(urls); // Remove duplicates. + urls = CoreUtils.uniqueArray(urls); // Remove duplicates. const promises = urls.map(async (url) => { - const finalUrl = await CoreFilepool.instance.getUrlByUrl(siteId, url, this.component, this.componentId, 0, true, true); + const finalUrl = await CoreFilepool.getUrlByUrl(siteId, url, this.component, this.componentId, 0, true, true); this.logger.debug('Using URL ' + finalUrl + ' for ' + url + ' in inline styles'); inlineStyles = inlineStyles!.replace(new RegExp(url, 'gi'), finalUrl); }); try { - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); this.element.setAttribute('style', inlineStyles); } catch (error) { diff --git a/src/core/directives/fa-icon.ts b/src/core/directives/fa-icon.ts index 381b36aab..b85f743a8 100644 --- a/src/core/directives/fa-icon.ts +++ b/src/core/directives/fa-icon.ts @@ -75,7 +75,7 @@ export class CoreFaIconDirective implements OnChanges { if (CoreConstants.BUILD.isDevelopment || CoreConstants.BUILD.isTesting) { try { - await Http.instance.get(src, { responseType: 'text' }).toPromise(); + await Http.get(src, { responseType: 'text' }).toPromise(); } catch (error) { this.logger.error(`Icon ${this.name} not found`); } diff --git a/src/core/directives/format-text.ts b/src/core/directives/format-text.ts index 7772bf535..9997a4d3e 100644 --- a/src/core/directives/format-text.ts +++ b/src/core/directives/format-text.ts @@ -171,7 +171,7 @@ export class CoreFormatTextDirective implements OnChanges { container.classList.add('atto_image_button_text-bottom'); } - CoreDomUtils.instance.wrapElement(img, container); + CoreDomUtils.wrapElement(img, container); } /** @@ -202,8 +202,8 @@ export class CoreFormatTextDirective implements OnChanges { return; } - const imgSrc = CoreTextUtils.instance.escapeHTML(img.getAttribute('data-original-src') || img.getAttribute('src')); - const label = Translate.instance.instant('core.openfullimage'); + const imgSrc = CoreTextUtils.escapeHTML(img.getAttribute('data-original-src') || img.getAttribute('src')); + const label = Translate.instant('core.openfullimage'); const anchor = document.createElement('a'); anchor.classList.add('core-image-viewer-icon'); @@ -214,7 +214,7 @@ export class CoreFormatTextDirective implements OnChanges { anchor.addEventListener('click', (e: Event) => { e.preventDefault(); e.stopPropagation(); - CoreDomUtils.instance.viewImage(imgSrc, img.getAttribute('alt'), this.component, this.componentId, true); + CoreDomUtils.viewImage(imgSrc, img.getAttribute('alt'), this.component, this.componentId, true); }); img.parentNode?.appendChild(anchor); @@ -253,11 +253,11 @@ export class CoreFormatTextDirective implements OnChanges { * Display the "Show more" in the element. */ protected displayShowMore(): void { - const expandInFullview = CoreUtils.instance.isTrueOrOne(this.fullOnClick) || false; + const expandInFullview = CoreUtils.isTrueOrOne(this.fullOnClick) || false; const showMoreDiv = document.createElement('div'); showMoreDiv.classList.add('core-show-more'); - showMoreDiv.innerHTML = Translate.instance.instant('core.showmore'); + showMoreDiv.innerHTML = Translate.instant('core.showmore'); this.element.appendChild(showMoreDiv); if (expandInFullview) { @@ -284,7 +284,7 @@ export class CoreFormatTextDirective implements OnChanges { return; } - const expandInFullview = CoreUtils.instance.isTrueOrOne(this.fullOnClick) || false; + const expandInFullview = CoreUtils.isTrueOrOne(this.fullOnClick) || false; if (!expandInFullview && !this.showMoreDisplayed) { // Nothing to do on click, just stop. @@ -301,10 +301,10 @@ export class CoreFormatTextDirective implements OnChanges { return; } else { // Open a new state with the contents. - const filter = typeof this.filter != 'undefined' ? CoreUtils.instance.isTrueOrOne(this.filter) : undefined; + const filter = typeof this.filter != 'undefined' ? CoreUtils.isTrueOrOne(this.filter) : undefined; - CoreTextUtils.instance.viewText( - this.fullTitle || Translate.instance.instant('core.description'), + CoreTextUtils.viewText( + this.fullTitle || Translate.instant('core.description'), this.text, { component: this.component, @@ -344,7 +344,7 @@ export class CoreFormatTextDirective implements OnChanges { this.element.setAttribute('maxHeight', String(this.maxHeight)); } if (!this.element.getAttribute('singleLine')) { - this.element.setAttribute('singleLine', String(CoreUtils.instance.isTrueOrOne(this.singleLine))); + this.element.setAttribute('singleLine', String(CoreUtils.isTrueOrOne(this.singleLine))); } this.text = this.text ? this.text.trim() : ''; @@ -359,7 +359,7 @@ export class CoreFormatTextDirective implements OnChanges { (this.fullOnClick || (window.innerWidth < 576 || window.innerHeight < 576))) { // Don't collapse in big screens. // Move the children to the current element to be able to calculate the height. - CoreDomUtils.instance.moveChildren(result.div, this.element); + CoreDomUtils.moveChildren(result.div, this.element); // Calculate the height now. this.calculateHeight(); @@ -371,14 +371,14 @@ export class CoreFormatTextDirective implements OnChanges { // Recalculate the height if a parent core-loading displays the content. this.loadingChangedListener = CoreEvents.on(CoreEvents.CORE_LOADING_CHANGED, (data: CoreEventLoadingChangedData) => { - if (data.loaded && CoreDomUtils.instance.closest(this.element.parentElement, '#' + data.uniqueId)) { + if (data.loaded && CoreDomUtils.closest(this.element.parentElement, '#' + data.uniqueId)) { // The format-text is inside the loading, re-calculate the height. this.calculateHeight(); } }); } } else { - CoreDomUtils.instance.moveChildren(result.div, this.element); + CoreDomUtils.moveChildren(result.div, this.element); // Add magnifying glasses to images. this.addMagnifyingGlasses(); @@ -386,7 +386,7 @@ export class CoreFormatTextDirective implements OnChanges { if (result.options.filter) { // Let filters handle HTML. We do it here because we don't want them to block the render of the text. - CoreFilterDelegate.instance.handleHtml( + CoreFilterDelegate.handleHtml( this.element, result.filters, this.viewContainerRef, @@ -409,7 +409,7 @@ export class CoreFormatTextDirective implements OnChanges { */ protected async formatContents(): Promise { // Retrieve the site since it might be needed later. - const site = await CoreUtils.instance.ignoreErrors(CoreSites.instance.getSite(this.siteId)); + const site = await CoreUtils.ignoreErrors(CoreSites.getSite(this.siteId)); const siteId = site?.getId(); @@ -418,21 +418,21 @@ export class CoreFormatTextDirective implements OnChanges { } const filter = typeof this.filter == 'undefined' ? - !!(this.contextLevel && typeof this.contextInstanceId != 'undefined') : CoreUtils.instance.isTrueOrOne(this.filter); + !!(this.contextLevel && typeof this.contextInstanceId != 'undefined') : CoreUtils.isTrueOrOne(this.filter); const options: CoreFilterFormatTextOptions = { - clean: CoreUtils.instance.isTrueOrOne(this.clean), - singleLine: CoreUtils.instance.isTrueOrOne(this.singleLine), + clean: CoreUtils.isTrueOrOne(this.clean), + singleLine: CoreUtils.isTrueOrOne(this.singleLine), highlight: this.highlight, courseId: this.courseId, - wsNotFiltered: CoreUtils.instance.isTrueOrOne(this.wsNotFiltered), + wsNotFiltered: CoreUtils.isTrueOrOne(this.wsNotFiltered), }; let formatted: string; let filters: CoreFilterFilter[] = []; if (filter) { - const filterResult = await CoreFilterHelper.instance.getFiltersAndFormatText( + const filterResult = await CoreFilterHelper.getFiltersAndFormatText( this.text || '', this.contextLevel || '', this.contextInstanceId ?? -1, @@ -443,7 +443,7 @@ export class CoreFormatTextDirective implements OnChanges { filters = filterResult.filters; formatted = filterResult.text; } else { - formatted = await CoreFilter.instance.formatText(this.text || '', options, [], siteId); + formatted = await CoreFilter.formatText(this.text || '', options, [], siteId); } formatted = this.treatWindowOpen(formatted); @@ -507,7 +507,7 @@ export class CoreFormatTextDirective implements OnChanges { externalImages.push(externalImage); } - if (CoreUtils.instance.isTrueOrOne(this.adaptImg) && !img.classList.contains('icon')) { + if (CoreUtils.isTrueOrOne(this.adaptImg) && !img.classList.contains('icon')) { this.adaptImage(img); } }); @@ -555,14 +555,14 @@ export class CoreFormatTextDirective implements OnChanges { // Handle all kind of frames. frames.forEach((frame: HTMLFrameElement | HTMLObjectElement | HTMLEmbedElement) => { - CoreIframeUtils.instance.treatFrame(frame, false); + CoreIframeUtils.treatFrame(frame, false); }); - CoreDomUtils.instance.handleBootstrapTooltips(div); + CoreDomUtils.handleBootstrapTooltips(div); if (externalImages.length) { // Wait for images to load. - const promise = CoreUtils.instance.allPromises(externalImages.map((externalImage) => { + const promise = CoreUtils.allPromises(externalImages.map((externalImage) => { if (externalImage.loaded) { // Image has already been loaded, no need to wait. return Promise.resolve(); @@ -572,7 +572,7 @@ export class CoreFormatTextDirective implements OnChanges { })); // Automatically reject the promise after 5 seconds to prevent blocking the user forever. - await CoreUtils.instance.ignoreErrors(CoreUtils.instance.timeoutPromise(promise, 5000)); + await CoreUtils.ignoreErrors(CoreUtils.timeoutPromise(promise, 5000)); } } @@ -583,17 +583,17 @@ export class CoreFormatTextDirective implements OnChanges { * @return The width of the element in pixels. When 0 is returned it means the element is not visible. */ protected getElementWidth(element: HTMLElement): number { - let width = CoreDomUtils.instance.getElementWidth(element); + let width = CoreDomUtils.getElementWidth(element); if (!width) { // All elements inside are floating or inline. Change display mode to allow calculate the width. const parentWidth = element.parentElement ? - CoreDomUtils.instance.getElementWidth(element.parentElement, true, false, false, true) : 0; + CoreDomUtils.getElementWidth(element.parentElement, true, false, false, true) : 0; const previousDisplay = getComputedStyle(element, null).display; element.style.display = 'inline-block'; - width = CoreDomUtils.instance.getElementWidth(element); + width = CoreDomUtils.getElementWidth(element); // If width is incorrectly calculated use parent width instead. if (parentWidth > 0 && (!width || width > parentWidth)) { @@ -613,7 +613,7 @@ export class CoreFormatTextDirective implements OnChanges { * @return The height of the element in pixels. When 0 is returned it means the element is not visible. */ protected getElementHeight(element: HTMLElement): number { - return CoreDomUtils.instance.getElementHeight(element) || 0; + return CoreDomUtils.getElementHeight(element) || 0; } /** @@ -674,7 +674,7 @@ export class CoreFormatTextDirective implements OnChanges { canTreatVimeo: boolean, ): Promise { const src = iframe.src; - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); this.addMediaAdaptClass(iframe); @@ -683,7 +683,7 @@ export class CoreFormatTextDirective implements OnChanges { const finalUrl = await currentSite.getAutoLoginUrl(src, false); iframe.src = finalUrl; - CoreIframeUtils.instance.treatFrame(iframe, false); + CoreIframeUtils.treatFrame(iframe, false); return; } @@ -692,7 +692,7 @@ export class CoreFormatTextDirective implements OnChanges { // Check if it's a Vimeo video. If it is, use the wsplayer script instead to make restricted videos work. const matches = iframe.src.match(/https?:\/\/player\.vimeo\.com\/video\/([0-9]+)/); if (matches && matches[1]) { - let newUrl = CoreTextUtils.instance.concatenatePaths(site.getURL(), '/media/player/vimeo/wsplayer.php?video=') + + let newUrl = CoreTextUtils.concatenatePaths(site.getURL(), '/media/player/vimeo/wsplayer.php?video=') + matches[1] + '&token=' + site.getToken(); // Width and height are mandatory, we need to calculate them. @@ -744,7 +744,7 @@ export class CoreFormatTextDirective implements OnChanges { } } - CoreIframeUtils.instance.treatFrame(iframe, false); + CoreIframeUtils.treatFrame(iframe, false); } /** diff --git a/src/core/directives/link.ts b/src/core/directives/link.ts index c5c7597d4..cdebc6524 100644 --- a/src/core/directives/link.ts +++ b/src/core/directives/link.ts @@ -54,7 +54,7 @@ export class CoreLinkDirective implements OnInit { * Function executed when the component is initialized. */ ngOnInit(): void { - this.inApp = typeof this.inApp == 'undefined' ? this.inApp : CoreUtils.instance.isTrueOrOne(this.inApp); + this.inApp = typeof this.inApp == 'undefined' ? this.inApp : CoreUtils.isTrueOrOne(this.inApp); // @todo: Handle split view? @@ -65,7 +65,7 @@ export class CoreLinkDirective implements OnInit { let href = this.href || this.element.getAttribute('href') || this.element.getAttribute('xlink:href'); - if (!href || CoreUrlUtils.instance.getUrlScheme(href) == 'javascript') { + if (!href || CoreUrlUtils.getUrlScheme(href) == 'javascript') { return; } @@ -74,10 +74,10 @@ export class CoreLinkDirective implements OnInit { const openIn = this.element.getAttribute('data-open-in'); - if (CoreUtils.instance.isTrueOrOne(this.capture)) { - href = CoreTextUtils.instance.decodeURI(href); + if (CoreUtils.isTrueOrOne(this.capture)) { + href = CoreTextUtils.decodeURI(href); - const treated = await CoreContentLinksHelper.instance.handleLink(href, undefined, true, true); + const treated = await CoreContentLinksHelper.handleLink(href, undefined, true, true); if (!treated) { this.navigate(href, openIn); @@ -97,14 +97,14 @@ export class CoreLinkDirective implements OnInit { */ protected async navigate(href: string, openIn?: string | null): Promise { - if (CoreUrlUtils.instance.isLocalFileUrl(href)) { + if (CoreUrlUtils.isLocalFileUrl(href)) { return this.openLocalFile(href); } if (href.charAt(0) == '#') { // Look for id or name. href = href.substr(1); - CoreDomUtils.instance.scrollToElementBySelector( + CoreDomUtils.scrollToElementBySelector( this.element.closest('ion-content'), this.content, `#${href}, [name='${href}']`, @@ -127,18 +127,18 @@ export class CoreLinkDirective implements OnInit { protected async openLocalFile(path: string): Promise { const filename = path.substr(path.lastIndexOf('/') + 1); - if (!CoreFileHelper.instance.isOpenableInApp({ filename })) { + if (!CoreFileHelper.isOpenableInApp({ filename })) { try { - await CoreFileHelper.instance.showConfirmOpenUnsupportedFile(); + await CoreFileHelper.showConfirmOpenUnsupportedFile(); } catch (error) { return; // Cancelled, stop. } } try { - await CoreUtils.instance.openFile(path); + await CoreUtils.openFile(path); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } } @@ -151,38 +151,38 @@ export class CoreLinkDirective implements OnInit { */ protected async openExternalLink(href: string, openIn?: string | null): Promise { // It's an external link, we will open with browser. Check if we need to auto-login. - if (!CoreSites.instance.isLoggedIn()) { + if (!CoreSites.isLoggedIn()) { // Not logged in, cannot auto-login. if (this.inApp) { - CoreUtils.instance.openInApp(href); + CoreUtils.openInApp(href); } else { - CoreUtils.instance.openInBrowser(href); + CoreUtils.openInBrowser(href); } return; } // Check if URL does not have any protocol, so it's a relative URL. - if (!CoreUrlUtils.instance.isAbsoluteURL(href)) { + if (!CoreUrlUtils.isAbsoluteURL(href)) { // Add the site URL at the begining. if (href.charAt(0) == '/') { - href = CoreSites.instance.getCurrentSite()!.getURL() + href; + href = CoreSites.getCurrentSite()!.getURL() + href; } else { - href = CoreSites.instance.getCurrentSite()!.getURL() + '/' + href; + href = CoreSites.getCurrentSite()!.getURL() + '/' + href; } } if (this.autoLogin == 'yes') { if (this.inApp) { - await CoreSites.instance.getCurrentSite()!.openInAppWithAutoLogin(href); + await CoreSites.getCurrentSite()!.openInAppWithAutoLogin(href); } else { - await CoreSites.instance.getCurrentSite()!.openInBrowserWithAutoLogin(href); + await CoreSites.getCurrentSite()!.openInBrowserWithAutoLogin(href); } } else if (this.autoLogin == 'no') { if (this.inApp) { - CoreUtils.instance.openInApp(href); + CoreUtils.openInApp(href); } else { - CoreUtils.instance.openInBrowser(href); + CoreUtils.openInBrowser(href); } } else { // Priority order is: core-link inApp attribute > forceOpenLinksIn setting > data-open-in HTML attribute. @@ -196,9 +196,9 @@ export class CoreLinkDirective implements OnInit { } if (openInApp) { - await CoreSites.instance.getCurrentSite()!.openInAppWithAutoLoginIfSameSite(href); + await CoreSites.getCurrentSite()!.openInAppWithAutoLoginIfSameSite(href); } else { - await CoreSites.instance.getCurrentSite()!.openInBrowserWithAutoLoginIfSameSite(href); + await CoreSites.getCurrentSite()!.openInBrowserWithAutoLoginIfSameSite(href); } } } diff --git a/src/core/directives/long-press.ts b/src/core/directives/long-press.ts index 4dc50bf87..4bc79463e 100644 --- a/src/core/directives/long-press.ts +++ b/src/core/directives/long-press.ts @@ -39,7 +39,7 @@ export class CoreLongPressDirective implements OnInit, OnDestroy { * Initialize gesture listening. */ ngOnInit(): void { - this.pressGesture = GestureController.instance.create({ + this.pressGesture = GestureController.create({ el: this.element, threshold: 0, gestureName: 'longpress', diff --git a/src/core/directives/tests/format-text.test.ts b/src/core/directives/tests/format-text.test.ts index 498d3fb79..c76c81e34 100644 --- a/src/core/directives/tests/format-text.test.ts +++ b/src/core/directives/tests/format-text.test.ts @@ -101,8 +101,8 @@ describe('CoreFormatTextDirective', () => { expect(image).not.toBeNull(); expect(image.src).toEqual('file://local-path/'); - expect(CoreSites.instance.getSite).toHaveBeenCalledWith(site.getId()); - expect(CoreFilepool.instance.getSrcByUrl).toHaveBeenCalledTimes(1); + expect(CoreSites.getSite).toHaveBeenCalledWith(site.getId()); + expect(CoreFilepool.getSrcByUrl).toHaveBeenCalledTimes(1); }); it.todo('should format text'); diff --git a/src/core/directives/user-link.ts b/src/core/directives/user-link.ts index 9413d94e0..f7261e1dc 100644 --- a/src/core/directives/user-link.ts +++ b/src/core/directives/user-link.ts @@ -50,7 +50,7 @@ export class CoreUserLinkDirective implements OnInit { event.stopPropagation(); // @todo If this directive is inside a split view, use the split view's master nav. - CoreNavigator.instance.navigateToSitePath('user', { + CoreNavigator.navigateToSitePath('user', { params: CoreObject.withoutEmpty({ userId: this.userId, courseId: this.courseId, diff --git a/src/core/features/block/classes/base-block-component.ts b/src/core/features/block/classes/base-block-component.ts index 20c020c08..bc3bc2d66 100644 --- a/src/core/features/block/classes/base-block-component.ts +++ b/src/core/features/block/classes/base-block-component.ts @@ -52,12 +52,12 @@ export abstract class CoreBlockBaseComponent implements OnInit { async ngOnInit(): Promise { if (this.block.configs && this.block.configs.length > 0) { this.block.configs.map((config) => { - config.value = CoreTextUtils.instance.parseJSON(config.value); + config.value = CoreTextUtils.parseJSON(config.value); return config; }); - this.block.configsRecord = CoreUtils.instance.arrayToObject(this.block.configs, 'name'); + this.block.configsRecord = CoreUtils.arrayToObject(this.block.configs, 'name'); } await this.loadContent(); @@ -124,7 +124,7 @@ export abstract class CoreBlockBaseComponent implements OnInit { this.logger.error(error); // Error getting data, fail. - CoreDomUtils.instance.showErrorModalDefault(error, this.fetchContentDefaultError, true); + CoreDomUtils.showErrorModalDefault(error, this.fetchContentDefaultError, true); } this.loaded = true; diff --git a/src/core/features/block/components/block/block.ts b/src/core/features/block/components/block/block.ts index 595c283ad..bb534d946 100644 --- a/src/core/features/block/components/block/block.ts +++ b/src/core/features/block/components/block/block.ts @@ -87,13 +87,13 @@ export class CoreBlockComponent implements OnInit, OnDestroy, DoCheck { */ async initBlock(): Promise { try { - const data = await CoreBlockDelegate.instance.getBlockDisplayData(this.block, this.contextLevel, this.instanceId); + const data = await CoreBlockDelegate.getBlockDisplayData(this.block, this.contextLevel, this.instanceId); if (!data) { // Block not supported, don't render it. But, site plugins might not have finished loading. // Subscribe to the observable in block delegate that will tell us if blocks are updated. // We can retry init later if that happens. - this.blockSubscription = CoreBlockDelegate.instance.blocksUpdateObservable.subscribe( + this.blockSubscription = CoreBlockDelegate.blocksUpdateObservable.subscribe( (): void => { this.blockSubscription?.unsubscribe(); delete this.blockSubscription; diff --git a/src/core/features/block/components/course-blocks/course-blocks.ts b/src/core/features/block/components/course-blocks/course-blocks.ts index a1eb6b785..ad8b01d5f 100644 --- a/src/core/features/block/components/course-blocks/course-blocks.ts +++ b/src/core/features/block/components/course-blocks/course-blocks.ts @@ -67,8 +67,8 @@ export class CoreBlockCourseBlocksComponent implements OnInit { async invalidateBlocks(): Promise { const promises: Promise[] = []; - if (CoreBlockHelper.instance.canGetCourseBlocks()) { - promises.push(CoreCourse.instance.invalidateCourseBlocks(this.courseId)); + if (CoreBlockHelper.canGetCourseBlocks()) { + promises.push(CoreCourse.invalidateCourseBlocks(this.courseId)); } // Invalidate the blocks. @@ -89,9 +89,9 @@ export class CoreBlockCourseBlocksComponent implements OnInit { async loadContent(): Promise { try { - this.blocks = await CoreBlockHelper.instance.getCourseBlocks(this.courseId); + this.blocks = await CoreBlockHelper.getCourseBlocks(this.courseId); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); this.blocks = []; } @@ -115,7 +115,7 @@ export class CoreBlockCourseBlocksComponent implements OnInit { * @return Promise resolved when done. */ async doRefresh(): Promise { - await CoreUtils.instance.ignoreErrors(this.invalidateBlocks()); + await CoreUtils.ignoreErrors(this.invalidateBlocks()); await this.loadContent(); } diff --git a/src/core/features/block/components/only-title-block/only-title-block.ts b/src/core/features/block/components/only-title-block/only-title-block.ts index 35f7b7d73..4e777f6c0 100644 --- a/src/core/features/block/components/only-title-block/only-title-block.ts +++ b/src/core/features/block/components/only-title-block/only-title-block.ts @@ -44,7 +44,7 @@ export class CoreBlockOnlyTitleComponent extends CoreBlockBaseComponent implemen */ gotoBlock(): void { // @todo test that this is working properly. - CoreNavigator.instance.navigateToSitePath(this.link!, { params: this.linkParams }); + CoreNavigator.navigateToSitePath(this.link!, { params: this.linkParams }); } } diff --git a/src/core/features/block/services/block-delegate.ts b/src/core/features/block/services/block-delegate.ts index bd80bbc25..403584f84 100644 --- a/src/core/features/block/services/block-delegate.ts +++ b/src/core/features/block/services/block-delegate.ts @@ -106,7 +106,7 @@ export class CoreBlockDelegateService extends CoreDelegate { * @return Whether it's disabled. */ areBlocksDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site && site.isFeatureDisabled('NoDelegate_SiteBlocks'); } @@ -118,7 +118,7 @@ export class CoreBlockDelegateService extends CoreDelegate { * @return Whether it's disabled. */ areBlocksDisabledInCourses(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site && site.isFeatureDisabled('NoDelegate_CourseBlocks'); } @@ -130,7 +130,7 @@ export class CoreBlockDelegateService extends CoreDelegate { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async areBlocksDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.areBlocksDisabledInSite(site); } @@ -198,4 +198,4 @@ export class CoreBlockDelegateService extends CoreDelegate { } -export class CoreBlockDelegate extends makeSingleton(CoreBlockDelegateService) {} +export const CoreBlockDelegate = makeSingleton(CoreBlockDelegateService, ['blocksUpdateObservable']); diff --git a/src/core/features/block/services/block-helper.ts b/src/core/features/block/services/block-helper.ts index 80c5261a6..c946bd75b 100644 --- a/src/core/features/block/services/block-helper.ts +++ b/src/core/features/block/services/block-helper.ts @@ -29,7 +29,7 @@ export class CoreBlockHelperProvider { * @return true if enabled, false otherwise. */ canGetCourseBlocks(): boolean { - return CoreCourse.instance.canGetCourseBlocks() && !CoreBlockDelegate.instance.areBlocksDisabledInCourses(); + return CoreCourse.canGetCourseBlocks() && !CoreBlockDelegate.areBlocksDisabledInCourses(); } /** @@ -45,8 +45,8 @@ export class CoreBlockHelperProvider { return []; } - const blocks = await CoreCourse.instance.getCourseBlocks(courseId); - const hasSupportedBlock = CoreBlockDelegate.instance.hasSupportedBlock(blocks); + const blocks = await CoreCourse.getCourseBlocks(courseId); + const hasSupportedBlock = CoreBlockDelegate.hasSupportedBlock(blocks); if (!hasSupportedBlock) { return []; } @@ -56,5 +56,4 @@ export class CoreBlockHelperProvider { } -export class CoreBlockHelper extends makeSingleton(CoreBlockHelperProvider) {} - +export const CoreBlockHelper = makeSingleton(CoreBlockHelperProvider); diff --git a/src/core/features/comments/comments.module.ts b/src/core/features/comments/comments.module.ts index 23ed1bbfc..491918ac8 100644 --- a/src/core/features/comments/comments.module.ts +++ b/src/core/features/comments/comments.module.ts @@ -44,9 +44,9 @@ const routes: Routes = [ provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreCronDelegate.instance.register(CoreCommentsSyncCronHandler.instance); + CoreCronDelegate.register(CoreCommentsSyncCronHandler.instance); - CoreComments.instance.initialize(); + CoreComments.initialize(); }, }, ], diff --git a/src/core/features/comments/components/add/add-modal.ts b/src/core/features/comments/components/add/add-modal.ts index e4fbcba09..1808431d6 100644 --- a/src/core/features/comments/components/add/add-modal.ts +++ b/src/core/features/comments/components/add/add-modal.ts @@ -48,12 +48,12 @@ export class CoreCommentsAddComponent { e.preventDefault(); e.stopPropagation(); - CoreApp.instance.closeKeyboard(); - const loadingModal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + CoreApp.closeKeyboard(); + const loadingModal = await CoreDomUtils.showModalLoading('core.sending', true); // Freeze the add comment button. this.processing = true; try { - const commentsResponse = await CoreComments.instance.addComment( + const commentsResponse = await CoreComments.addComment( this.content, this.contextLevel, this.instanceId, @@ -62,21 +62,21 @@ export class CoreCommentsAddComponent { this.area, ); - CoreDomUtils.instance.triggerFormSubmittedEvent( + CoreDomUtils.triggerFormSubmittedEvent( this.formElement, !!commentsResponse, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); - ModalController.instance.dismiss({ comment: commentsResponse }).finally(() => { - CoreDomUtils.instance.showToast( + ModalController.dismiss({ comment: commentsResponse }).finally(() => { + CoreDomUtils.showToast( commentsResponse ? 'core.comments.eventcommentcreated' : 'core.datastoredoffline', true, 3000, ); }); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); this.processing = false; } finally { loadingModal.dismiss(); @@ -87,8 +87,8 @@ export class CoreCommentsAddComponent { * Close modal. */ closeModal(): void { - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); - ModalController.instance.dismiss(); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); + ModalController.dismiss(); } } diff --git a/src/core/features/comments/components/comments/comments.ts b/src/core/features/comments/components/comments/comments.ts index d18cc34b1..8d591ad31 100644 --- a/src/core/features/comments/components/comments/comments.ts +++ b/src/core/features/comments/components/comments/comments.ts @@ -58,18 +58,18 @@ export class CoreCommentsCommentsComponent implements OnInit, OnChanges, OnDestr this.onLoading = new EventEmitter(); - this.disabled = CoreComments.instance.areCommentsDisabledInSite(); + this.disabled = CoreComments.areCommentsDisabledInSite(); // Update visibility if current site info is updated. this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { const wasDisabled = this.disabled; - this.disabled = CoreComments.instance.areCommentsDisabledInSite(); + this.disabled = CoreComments.areCommentsDisabledInSite(); if (wasDisabled && !this.disabled) { this.fetchData(); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); // Refresh comments if event received. this.refreshCommentsObserver = CoreEvents.on( @@ -80,10 +80,10 @@ export class CoreCommentsCommentsComponent implements OnInit, OnChanges, OnDestr this.undefinedOrEqual(data, 'component') && this.undefinedOrEqual(data, 'itemId') && this.undefinedOrEqual(data, 'area')) { - CoreUtils.instance.ignoreErrors(this.doRefresh()); + CoreUtils.ignoreErrors(this.doRefresh()); } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); // Refresh comments count if event received. @@ -101,7 +101,7 @@ export class CoreCommentsCommentsComponent implements OnInit, OnChanges, OnDestr this.commentsCount = newNumber + ''; } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); } @@ -133,7 +133,7 @@ export class CoreCommentsCommentsComponent implements OnInit, OnChanges, OnDestr this.commentsLoaded = false; this.onLoading.emit(true); - const commentsCount = await CoreComments.instance.getCommentsCount( + const commentsCount = await CoreComments.getCommentsCount( this.contextLevel, this.instanceId, this.component, @@ -163,7 +163,7 @@ export class CoreCommentsCommentsComponent implements OnInit, OnChanges, OnDestr * @return Promise resolved when done. */ async invalidateComments(): Promise { - await CoreComments.instance.invalidateCommentsData( + await CoreComments.invalidateCommentsData( this.contextLevel, this.instanceId, this.component, @@ -185,7 +185,7 @@ export class CoreCommentsCommentsComponent implements OnInit, OnChanges, OnDestr return; } - CoreNavigator.instance.navigateToSitePath( + CoreNavigator.navigateToSitePath( 'comments/' + this.contextLevel + '/' + this.instanceId + '/' + this.component + '/' + this.itemId + '/', { params: { diff --git a/src/core/features/comments/pages/viewer/viewer.page.ts b/src/core/features/comments/pages/viewer/viewer.page.ts index d3d089270..b6e50625b 100644 --- a/src/core/features/comments/pages/viewer/viewer.page.ts +++ b/src/core/features/comments/pages/viewer/viewer.page.ts @@ -83,7 +83,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { constructor( protected route: ActivatedRoute, ) { - this.currentUserId = CoreSites.instance.getCurrentSiteUserId(); + this.currentUserId = CoreSites.getCurrentSiteUserId(); // Refresh data if comments are synchronized automatically. this.syncObserver = CoreEvents.on(CoreCommentsSyncProvider.AUTO_SYNCED, (data) => { @@ -103,7 +103,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { this.comments = []; this.fetchComments(false); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } /** @@ -111,18 +111,18 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { */ async ngOnInit(): Promise { // Is implicit the user can delete if he can add. - this.addDeleteCommentsAvailable = await CoreComments.instance.isAddCommentsAvailable(); - this.currentUserId = CoreSites.instance.getCurrentSiteUserId(); + this.addDeleteCommentsAvailable = await CoreComments.isAddCommentsAvailable(); + this.currentUserId = CoreSites.getCurrentSiteUserId(); this.commentsLoaded = false; - this.contextLevel = CoreNavigator.instance.getRouteParam('contextLevel')!; - this.instanceId = CoreNavigator.instance.getRouteNumberParam('instanceId')!; - this.componentName = CoreNavigator.instance.getRouteParam('componentName')!; - this.itemId = CoreNavigator.instance.getRouteNumberParam('itemId')!; - this.area = CoreNavigator.instance.getRouteParam('area') || ''; - this.title = CoreNavigator.instance.getRouteNumberParam('title') || - Translate.instance.instant('core.comments.comments'); - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId'); + this.contextLevel = CoreNavigator.getRouteParam('contextLevel')!; + this.instanceId = CoreNavigator.getRouteNumberParam('instanceId')!; + this.componentName = CoreNavigator.getRouteParam('componentName')!; + this.itemId = CoreNavigator.getRouteNumberParam('itemId')!; + this.area = CoreNavigator.getRouteParam('area') || ''; + this.title = CoreNavigator.getRouteNumberParam('title') || + Translate.instant('core.comments.comments'); + this.courseId = CoreNavigator.getRouteNumberParam('courseId'); await this.fetchComments(true); } @@ -138,12 +138,12 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { this.loadMoreError = false; if (sync) { - await CoreUtils.instance.ignoreErrors(this.syncComments(showErrors)); + await CoreUtils.ignoreErrors(this.syncComments(showErrors)); } try { // Get comments data. - const commentsResponse = await CoreComments.instance.getComments( + const commentsResponse = await CoreComments.getComments( this.contextLevel, this.instanceId, this.componentName, @@ -173,9 +173,9 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { } catch (error) { this.loadMoreError = true; // Set to prevent infinite calls with infinite-loading. if (error && this.componentName == 'assignsubmission_comments') { - CoreDomUtils.instance.showAlertTranslated('core.notice', 'core.comments.commentsnotworking'); + CoreDomUtils.showAlertTranslated('core.notice', 'core.comments.commentsnotworking'); } else { - CoreDomUtils.instance.showErrorModalDefault(error, Translate.instance.instant('core.error') + ': get_comments'); + CoreDomUtils.showErrorModalDefault(error, Translate.instant('core.error') + ': get_comments'); } } finally { this.commentsLoaded = true; @@ -232,9 +232,9 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { * @param warnings the warnings */ private showSyncWarnings(warnings: string[]): void { - const message = CoreTextUtils.instance.buildMessage(warnings); + const message = CoreTextUtils.buildMessage(warnings); if (message) { - CoreDomUtils.instance.showErrorModal(message); + CoreDomUtils.showErrorModal(message); } } @@ -246,7 +246,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { */ private async syncComments(showErrors: boolean): Promise { try { - const result = await CoreCommentsSync.instance.syncComments( + const result = await CoreCommentsSync.syncComments( this.contextLevel, this.instanceId, this.componentName, @@ -256,7 +256,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { this.showSyncWarnings(result?.warnings || []); } catch (error) { if (showErrors) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errorsync', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errorsync', true); } throw new CoreError(error); @@ -281,7 +281,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { content: this.offlineComment ? this.offlineComment!.content : '', }; - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: CoreCommentsAddComponent, componentProps: params, }); @@ -305,7 +305,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { itemId: this.itemId, area: this.area, countChange: 1, - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } else if (result?.data?.comment === false) { // Comments added in offline mode. @@ -326,7 +326,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { const modified = 'lastmodified' in comment ? comment.lastmodified : comment.timecreated; - const time = CoreTimeUtils.instance.userDate( + const time = CoreTimeUtils.userDate( modified * 1000, 'core.strftimerecentfull', ); @@ -342,7 +342,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { }; try { - await CoreDomUtils.instance.showDeleteConfirm('core.comments.deletecommentbyon', { + await CoreDomUtils.showDeleteConfirm('core.comments.deletecommentbyon', { $a: { user: comment.fullname || '', time: time }, }); @@ -352,7 +352,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { } try { - const deletedOnline = await CoreComments.instance.deleteComment(deleteComment); + const deletedOnline = await CoreComments.deleteComment(deleteComment); this.showDelete = false; if (deletedOnline) { @@ -367,7 +367,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { itemId: this.itemId, area: this.area, countChange: -1, - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } } else { this.loadOfflineData(); @@ -375,9 +375,9 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { this.invalidateComments(); - CoreDomUtils.instance.showToast('core.comments.eventcommentdeleted', true, 3000); + CoreDomUtils.showToast('core.comments.eventcommentdeleted', true, 3000); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Delete comment failed.'); + CoreDomUtils.showErrorModalDefault(error, 'Delete comment failed.'); } } @@ -387,7 +387,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { * @return Resolved when done. */ protected invalidateComments(): Promise { - return CoreComments.instance.invalidateCommentsData( + return CoreComments.invalidateCommentsData( this.contextLevel, this.instanceId, this.componentName, @@ -405,7 +405,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { protected async loadCommentProfile(comment: CoreCommentsDataWithUser): Promise { // Get the user profile image. try { - const user = await CoreUser.instance.getProfile(comment.userid!, undefined, true); + const user = await CoreUser.getProfile(comment.userid!, undefined, true); comment.profileimageurl = user.profileimageurl; comment.fullname = user.fullname; } catch { @@ -426,7 +426,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { let hasDeletedComments = false; // Load the only offline comment allowed if any. - promises.push(CoreCommentsOffline.instance.getComment( + promises.push(CoreCommentsOffline.getComment( this.contextLevel, this.instanceId, this.componentName, @@ -440,7 +440,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { } if (!this.currentUser) { - this.currentUser = await CoreUser.instance.getProfile(this.currentUserId, undefined, true); + this.currentUser = await CoreUser.getProfile(this.currentUserId, undefined, true); } if (this.currentUser) { @@ -453,7 +453,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { })); // Load deleted comments offline. - promises.push(CoreCommentsOffline.instance.getDeletedComments( + promises.push(CoreCommentsOffline.getDeletedComments( this.contextLevel, this.instanceId, this.componentName, @@ -490,7 +490,7 @@ export class CoreCommentsViewerPage implements OnInit, OnDestroy { e.preventDefault(); e.stopPropagation(); - await CoreCommentsOffline.instance.undoDeleteComment(comment.id); + await CoreCommentsOffline.undoDeleteComment(comment.id); comment.deleted = false; this.showDelete = false; diff --git a/src/core/features/comments/services/comments-offline.ts b/src/core/features/comments/services/comments-offline.ts index 8936940cf..9ab9ade8a 100644 --- a/src/core/features/comments/services/comments-offline.ts +++ b/src/core/features/comments/services/comments-offline.ts @@ -31,7 +31,7 @@ export class CoreCommentsOfflineProvider { * @return Promise resolved with comments. */ async getAllComments(siteId?: string): Promise<(CoreCommentsDBRecord | CoreCommentsDeletedDBRecord)[]> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const results = await Promise.all([ site.getDb().getRecords(COMMENTS_TABLE), site.getDb().getRecords(COMMENTS_DELETED_TABLE), @@ -60,7 +60,7 @@ export class CoreCommentsOfflineProvider { siteId?: string, ): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecord(COMMENTS_TABLE, { contextlevel: contextLevel, @@ -95,7 +95,7 @@ export class CoreCommentsOfflineProvider { ): Promise<(CoreCommentsDBRecord | CoreCommentsDeletedDBRecord)[]> { let comments: (CoreCommentsDBRecord | CoreCommentsDeletedDBRecord)[] = []; - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const comment = await this.getComment(contextLevel, instanceId, component, itemId, area, siteId); @@ -114,7 +114,7 @@ export class CoreCommentsOfflineProvider { * @return Promise resolved with comments. */ async getAllDeletedComments(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecords(COMMENTS_DELETED_TABLE); } @@ -139,7 +139,7 @@ export class CoreCommentsOfflineProvider { siteId?: string, ): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecords(COMMENTS_DELETED_TABLE, { contextlevel: contextLevel, @@ -172,7 +172,7 @@ export class CoreCommentsOfflineProvider { area: string = '', siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(COMMENTS_TABLE, { contextlevel: contextLevel, @@ -202,7 +202,7 @@ export class CoreCommentsOfflineProvider { area: string = '', siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(COMMENTS_DELETED_TABLE, { contextlevel: contextLevel, @@ -234,8 +234,8 @@ export class CoreCommentsOfflineProvider { area: string = '', siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); - const now = CoreTimeUtils.instance.timestamp(); + const site = await CoreSites.getSite(siteId); + const now = CoreTimeUtils.timestamp(); const data: CoreCommentsDBRecord = { contextlevel: contextLevel, instanceid: instanceId, @@ -272,8 +272,8 @@ export class CoreCommentsOfflineProvider { area: string = '', siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); - const now = CoreTimeUtils.instance.timestamp(); + const site = await CoreSites.getSite(siteId); + const now = CoreTimeUtils.timestamp(); const data: CoreCommentsDeletedDBRecord = { contextlevel: contextLevel, instanceid: instanceId, @@ -295,7 +295,7 @@ export class CoreCommentsOfflineProvider { * @return Promise resolved if deleted, rejected if failure. */ async undoDeleteComment(commentId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(COMMENTS_DELETED_TABLE, { commentid: commentId }); } diff --git a/src/core/features/comments/services/comments-sync.ts b/src/core/features/comments/services/comments-sync.ts index 2231fde65..5d256f95a 100644 --- a/src/core/features/comments/services/comments-sync.ts +++ b/src/core/features/comments/services/comments-sync.ts @@ -55,7 +55,7 @@ export class CoreCommentsSyncProvider extends CoreSyncBaseProvider { - const comments = await CoreCommentsOffline.instance.getAllComments(siteId); + const comments = await CoreCommentsOffline.getAllComments(siteId); const commentsUnique: { [syncId: string]: (CoreCommentsDBRecord | CoreCommentsDeletedDBRecord) } = {}; // Get Unique array. @@ -155,7 +155,7 @@ export class CoreCommentsSyncProvider extends CoreSyncBaseProvider { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const syncId = this.getSyncId(contextLevel, instanceId, component, itemId, area); @@ -197,13 +197,13 @@ export class CoreCommentsSyncProvider extends CoreSyncBaseProvider { countChange++; - return CoreCommentsOffline.instance.removeComment(contextLevel, instanceId, component, itemId, area, siteId); + return CoreCommentsOffline.removeComment(contextLevel, instanceId, component, itemId, area, siteId); })); } }); if (deleteCommentIds.length > 0) { - promises.push(CoreComments.instance.deleteCommentsOnline( + promises.push(CoreComments.deleteCommentsOnline( deleteCommentIds, contextLevel, instanceId, @@ -245,7 +245,7 @@ export class CoreCommentsSyncProvider extends CoreSyncBaseProvider { countChange--; - return CoreCommentsOffline.instance.removeDeletedComments( + return CoreCommentsOffline.removeDeletedComments( contextLevel, instanceId, component, @@ -269,17 +269,17 @@ export class CoreCommentsSyncProvider extends CoreSyncBaseProvider { - result.warnings.push(Translate.instance.instant('core.comments.warningcommentsnotsent', { + result.warnings.push(Translate.instant('core.comments.warningcommentsnotsent', { error: error, })); }); @@ -315,7 +315,7 @@ export class CoreCommentsSyncProvider extends CoreSyncBaseProvider { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Convenience function to store a comment to be synchronized later. const storeOffline = async (): Promise => { - await CoreCommentsOffline.instance.saveComment(content, contextLevel, instanceId, component, itemId, area, siteId); + await CoreCommentsOffline.saveComment(content, contextLevel, instanceId, component, itemId, area, siteId); return false; }; - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // App is offline, store the comment. return storeOffline(); } @@ -88,7 +88,7 @@ export class CoreCommentsProvider { try { return await this.addCommentOnline(content, contextLevel, instanceId, component, itemId, area, siteId); } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // It's a WebService error, the user cannot send the message so don't store it. throw error; } @@ -132,7 +132,7 @@ export class CoreCommentsProvider { const commentsResponse = await this.addCommentsOnline(comments, siteId); // A comment was added, invalidate them. - await CoreUtils.instance.ignoreErrors( + await CoreUtils.ignoreErrors( this.invalidateCommentsData(contextLevel, instanceId, component, itemId, area, siteId), ); @@ -155,7 +155,7 @@ export class CoreCommentsProvider { return; } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data: CoreCommentsAddCommentsWSParams = { comments: comments, }; @@ -170,7 +170,7 @@ export class CoreCommentsProvider { * @return Whether it's disabled. */ areCommentsDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('NoDelegate_CoreComments'); } @@ -182,7 +182,7 @@ export class CoreCommentsProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async areCommentsDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.areCommentsDisabledInSite(site); } @@ -196,11 +196,11 @@ export class CoreCommentsProvider { * doesn't mean that comments have been deleted, the resolve param can contain errors for comments not deleted. */ async deleteComment(comment: CoreCommentsCommentBasicData, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Offline comment, just delete it. if (!comment.id) { - await CoreCommentsOffline.instance.removeComment( + await CoreCommentsOffline.removeComment( comment.contextlevel, comment.instanceid, comment.component, @@ -214,7 +214,7 @@ export class CoreCommentsProvider { // Convenience function to store the action to be synchronized later. const storeOffline = async (): Promise => { - await CoreCommentsOffline.instance.deleteComment( + await CoreCommentsOffline.deleteComment( comment.id!, comment.contextlevel, comment.instanceid, @@ -227,7 +227,7 @@ export class CoreCommentsProvider { return false; }; - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // App is offline, store the comment. return storeOffline(); } @@ -246,7 +246,7 @@ export class CoreCommentsProvider { return true; } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // It's a WebService error, the user cannot send the comment so don't store it. throw error; } @@ -277,7 +277,7 @@ export class CoreCommentsProvider { area: string = '', siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data: CoreCommentsDeleteCommentsWSParams = { comments: commentIds, @@ -285,7 +285,7 @@ export class CoreCommentsProvider { await site.write('core_comment_delete_comments', data); - await CoreUtils.instance.ignoreErrors( + await CoreUtils.ignoreErrors( this.invalidateCommentsData(contextLevel, instanceId, component, itemId, area, siteId), ); } @@ -298,7 +298,7 @@ export class CoreCommentsProvider { * @since 3.8 */ async isAddCommentsAvailable(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // First check if it's disabled. if (this.areCommentsDisabledInSite(site)) { @@ -360,7 +360,7 @@ export class CoreCommentsProvider { page: number = 0, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCommentsGetCommentsWSParams = { contextlevel: contextLevel, @@ -409,7 +409,7 @@ export class CoreCommentsProvider { siteId?: string, ): Promise { - siteId = siteId ? siteId : CoreSites.instance.getCurrentSiteId(); + siteId = siteId ? siteId : CoreSites.getCurrentSiteId(); let trueCount = false; // Convenience function to get comments number on a page. @@ -473,9 +473,9 @@ export class CoreCommentsProvider { area: string = '', siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - await CoreUtils.instance.allPromises([ + await CoreUtils.allPromises([ // This is done with starting with to avoid conflicts with previous keys that were including page. site.invalidateWsCacheForKeyStartingWith(this.getCommentsCacheKey( contextLevel, @@ -498,7 +498,7 @@ export class CoreCommentsProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCommentsByInstance(contextLevel: string, instanceId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getCommentsPrefixCacheKey(contextLevel, instanceId)); } diff --git a/src/core/features/comments/services/handlers/sync-cron.ts b/src/core/features/comments/services/handlers/sync-cron.ts index f4285afda..bb45f90d1 100644 --- a/src/core/features/comments/services/handlers/sync-cron.ts +++ b/src/core/features/comments/services/handlers/sync-cron.ts @@ -33,7 +33,7 @@ export class CoreCommentsSyncCronHandlerService implements CoreCronHandler { * @return Promise resolved when done, rejected if failure. */ execute(siteId?: string, force?: boolean): Promise { - return CoreCommentsSync.instance.syncAllComments(siteId, force); + return CoreCommentsSync.syncAllComments(siteId, force); } /** diff --git a/src/core/features/contentlinks/classes/module-grade-handler.ts b/src/core/features/contentlinks/classes/module-grade-handler.ts index 6ef3e76c5..1b3b8f29b 100644 --- a/src/core/features/contentlinks/classes/module-grade-handler.ts +++ b/src/core/features/contentlinks/classes/module-grade-handler.ts @@ -72,11 +72,11 @@ export class CoreContentLinksModuleGradeHandler extends CoreContentLinksHandlerB return [{ action: async (siteId): Promise => { // Check if userid is the site's current user. - const modal = await CoreDomUtils.instance.showModalLoading(); - const site = await CoreSites.instance.getSite(siteId); + const modal = await CoreDomUtils.showModalLoading(); + const site = await CoreSites.getSite(siteId); if (!params.userid || Number(params.userid) == site.getUserId()) { // No user specified or current user. Navigate to module. - CoreCourseHelper.instance.navigateToModule( + CoreCourseHelper.navigateToModule( Number(params.id), siteId, courseId, diff --git a/src/core/features/contentlinks/classes/module-index-handler.ts b/src/core/features/contentlinks/classes/module-index-handler.ts index e0a3175eb..472dc609a 100644 --- a/src/core/features/contentlinks/classes/module-index-handler.ts +++ b/src/core/features/contentlinks/classes/module-index-handler.ts @@ -88,7 +88,7 @@ export class CoreContentLinksModuleIndexHandler extends CoreContentLinksHandlerB return [{ action: (siteId) => { - CoreCourseHelper.instance.navigateToModuleByInstance( + CoreCourseHelper.navigateToModuleByInstance( instanceId, this.modName, siteId, @@ -103,7 +103,7 @@ export class CoreContentLinksModuleIndexHandler extends CoreContentLinksHandlerB return [{ action: (siteId) => { - CoreCourseHelper.instance.navigateToModule( + CoreCourseHelper.navigateToModule( parseInt(params.id, 10), siteId, courseId, diff --git a/src/core/features/contentlinks/classes/module-list-handler.ts b/src/core/features/contentlinks/classes/module-list-handler.ts index 17cbf75af..6b4f5528c 100644 --- a/src/core/features/contentlinks/classes/module-list-handler.ts +++ b/src/core/features/contentlinks/classes/module-list-handler.ts @@ -61,11 +61,11 @@ export class CoreContentLinksModuleListHandler extends CoreContentLinksHandlerBa return [{ action: (siteId): void => { - CoreNavigator.instance.navigateToSitePath('course/list-mod-type', { + CoreNavigator.navigateToSitePath('course/list-mod-type', { params: { courseId: params.id, modName: this.modName, - title: this.title || Translate.instance.instant('addon.mod_' + this.modName + '.modulenameplural'), + title: this.title || Translate.instant('addon.mod_' + this.modName + '.modulenameplural'), }, siteId, }); diff --git a/src/core/features/contentlinks/pages/choose-site/choose-site.ts b/src/core/features/contentlinks/pages/choose-site/choose-site.ts index d04005b5c..29c38d202 100644 --- a/src/core/features/contentlinks/pages/choose-site/choose-site.ts +++ b/src/core/features/contentlinks/pages/choose-site/choose-site.ts @@ -42,7 +42,7 @@ export class CoreContentLinksChooseSitePage implements OnInit { * Component being initialized. */ async ngOnInit(): Promise { - const url = CoreNavigator.instance.getRouteParam('url'); + const url = CoreNavigator.getRouteParam('url'); if (!url) { return this.leaveView(); } @@ -52,7 +52,7 @@ export class CoreContentLinksChooseSitePage implements OnInit { try { // Check if it's the root URL. - const data = await CoreSites.instance.isStoredRootURL(this.url); + const data = await CoreSites.isStoredRootURL(this.url); if (data.site) { // It's the root URL. this.isRootURL = true; @@ -60,21 +60,21 @@ export class CoreContentLinksChooseSitePage implements OnInit { siteIds = data.siteIds; } else if (data.siteIds.length) { // Not root URL, but the URL belongs to at least 1 site. Check if there is any action to treat the link. - this.action = await CoreContentLinksHelper.instance.getFirstValidActionFor(this.url); + this.action = await CoreContentLinksHelper.getFirstValidActionFor(this.url); if (!this.action) { - throw new CoreError(Translate.instance.instant('core.contentlinks.errornoactions')); + throw new CoreError(Translate.instant('core.contentlinks.errornoactions')); } siteIds = this.action.sites; } else { // No sites to treat the URL. - throw new CoreError(Translate.instance.instant('core.contentlinks.errornosites')); + throw new CoreError(Translate.instant('core.contentlinks.errornosites')); } // Get the sites that can perform the action. - this.sites = await CoreSites.instance.getSites(siteIds); + this.sites = await CoreSites.getSites(siteIds); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.contentlinks.errornosites', true); + CoreDomUtils.showErrorModalDefault(error, 'core.contentlinks.errornosites', true); this.leaveView(); } @@ -95,7 +95,7 @@ export class CoreContentLinksChooseSitePage implements OnInit { */ siteClicked(siteId: string): void { if (this.isRootURL) { - CoreNavigator.instance.navigateToSiteHome({ siteId }); + CoreNavigator.navigateToSiteHome({ siteId }); } else if (this.action) { this.action.action(siteId); } @@ -106,9 +106,9 @@ export class CoreContentLinksChooseSitePage implements OnInit { */ protected async leaveView(): Promise { try { - await CoreSites.instance.logout(); + await CoreSites.logout(); } finally { - await CoreNavigator.instance.navigate('/login/sites', { reset: true }); + await CoreNavigator.navigate('/login/sites', { reset: true }); } } diff --git a/src/core/features/contentlinks/services/contentlinks-delegate.ts b/src/core/features/contentlinks/services/contentlinks-delegate.ts index b295bc2ae..8c40a4724 100644 --- a/src/core/features/contentlinks/services/contentlinks-delegate.ts +++ b/src/core/features/contentlinks/services/contentlinks-delegate.ts @@ -162,10 +162,10 @@ export class CoreContentLinksDelegateService { } // Get the list of sites the URL belongs to. - const siteIds = await CoreSites.instance.getSiteIdsFromUrl(url, true, username); + const siteIds = await CoreSites.getSiteIdsFromUrl(url, true, username); const linkActions: CoreContentLinksHandlerActions[] = []; const promises: Promise[] = []; - const params = CoreUrlUtils.instance.extractUrlParams(url); + const params = CoreUrlUtils.extractUrlParams(url); for (const name in this.handlers) { const handler = this.handlers[name]; const checkAll = handler.checkAllUsers; @@ -177,7 +177,7 @@ export class CoreContentLinksDelegateService { } // Filter the site IDs using the isEnabled function. - promises.push(CoreUtils.instance.filterEnabledSites(siteIds, isEnabledFn, checkAll).then(async (siteIds) => { + promises.push(CoreUtils.filterEnabledSites(siteIds, isEnabledFn, checkAll).then(async (siteIds) => { if (!siteIds.length) { // No sites supported, no actions. return; @@ -204,7 +204,7 @@ export class CoreContentLinksDelegateService { })); } try { - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); } catch { // Ignore errors. } @@ -256,7 +256,7 @@ export class CoreContentLinksDelegateService { let disabled = false; if (handler.featureName) { // Check if the feature is disabled. - disabled = await CoreSites.instance.isFeatureDisabled(handler.featureName, siteId); + disabled = await CoreSites.isFeatureDisabled(handler.featureName, siteId); } if (disabled) { @@ -311,4 +311,4 @@ export class CoreContentLinksDelegateService { } -export class CoreContentLinksDelegate extends makeSingleton(CoreContentLinksDelegateService) {} +export const CoreContentLinksDelegate = makeSingleton(CoreContentLinksDelegateService); diff --git a/src/core/features/contentlinks/services/contentlinks-helper.ts b/src/core/features/contentlinks/services/contentlinks-helper.ts index f0d19002b..6e7d52cfd 100644 --- a/src/core/features/contentlinks/services/contentlinks-helper.ts +++ b/src/core/features/contentlinks/services/contentlinks-helper.ts @@ -39,7 +39,7 @@ export class CoreContentLinksHelperProvider { async canHandleLink(url: string, courseId?: number, username?: string, checkRoot?: boolean): Promise { try { if (checkRoot) { - const data = await CoreSites.instance.isStoredRootURL(url, username); + const data = await CoreSites.isStoredRootURL(url, username); if (data.site) { // URL is the root of the site, can handle it. @@ -70,7 +70,7 @@ export class CoreContentLinksHelperProvider { username?: string, data?: unknown, ): Promise { - const actions = await CoreContentLinksDelegate.instance.getActionsFor(url, courseId, username, data); + const actions = await CoreContentLinksDelegate.getActionsFor(url, courseId, username, data); if (!actions) { return; } @@ -91,7 +91,7 @@ export class CoreContentLinksHelperProvider { * @deprecated since 3.9.5. Use CoreNavigator.navigateToSitePath instead. */ async goInSite(navCtrlUnused: unknown, pageName: string, pageParams: Params, siteId?: string): Promise { - await CoreNavigator.instance.navigateToSitePath(pageName, { params: pageParams, siteId }); + await CoreNavigator.navigateToSitePath(pageName, { params: pageParams, siteId }); } /** @@ -101,7 +101,7 @@ export class CoreContentLinksHelperProvider { * @todo set correct root. */ async goToChooseSite(url: string): Promise { - await CoreNavigator.instance.navigate('CoreContentLinksChooseSitePage @todo', { params: { url }, reset: true }); + await CoreNavigator.navigate('CoreContentLinksChooseSitePage @todo', { params: { url }, reset: true }); } /** @@ -122,7 +122,7 @@ export class CoreContentLinksHelperProvider { ): Promise { try { if (checkRoot) { - const data = await CoreSites.instance.isStoredRootURL(url, username); + const data = await CoreSites.isStoredRootURL(url, username); if (data.site) { // URL is the root of the site. @@ -137,20 +137,20 @@ export class CoreContentLinksHelperProvider { if (!action) { return false; } - if (!CoreSites.instance.isLoggedIn()) { + if (!CoreSites.isLoggedIn()) { // No current site. Perform the action if only 1 site found, choose the site otherwise. if (action.sites?.length == 1) { action.action(action.sites[0]); } else { this.goToChooseSite(url); } - } else if (action.sites?.length == 1 && action.sites[0] == CoreSites.instance.getCurrentSiteId()) { + } else if (action.sites?.length == 1 && action.sites[0] == CoreSites.getCurrentSiteId()) { // Current site. action.action(action.sites[0]); } else { try { // Not current site or more than one site. Ask for confirmation. - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.contentlinks.confirmurlothersite')); + await CoreDomUtils.showConfirm(Translate.instant('core.contentlinks.confirmurlothersite')); if (action.sites?.length == 1) { action.action(action.sites[0]); } else { @@ -179,7 +179,7 @@ export class CoreContentLinksHelperProvider { * @return Promise resolved when done. */ async handleRootURL(site: CoreSite, openBrowserRoot?: boolean, checkToken?: boolean): Promise { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); if (currentSite && currentSite.getURL() == site.getURL() && (!checkToken || currentSite.getToken() == site.getToken())) { // Already logged in. @@ -188,10 +188,10 @@ export class CoreContentLinksHelperProvider { } } else { // Login in the site. - await CoreNavigator.instance.navigateToSiteHome({ siteId: site.getId() }); + await CoreNavigator.navigateToSiteHome({ siteId: site.getId() }); } } } -export class CoreContentLinksHelper extends makeSingleton(CoreContentLinksHelperProvider) {} +export const CoreContentLinksHelper = makeSingleton(CoreContentLinksHelperProvider); diff --git a/src/core/features/course/classes/activity-prefetch-handler.ts b/src/core/features/course/classes/activity-prefetch-handler.ts index 3a0803887..08b234392 100644 --- a/src/core/features/course/classes/activity-prefetch-handler.ts +++ b/src/core/features/course/classes/activity-prefetch-handler.ts @@ -82,9 +82,9 @@ export class CoreCourseActivityPrefetchHandlerBase extends CoreCourseModulePrefe downloadFunction: () => Promise, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // Cannot prefetch in offline. throw new CoreNetworkError(); } @@ -119,9 +119,9 @@ export class CoreCourseActivityPrefetchHandlerBase extends CoreCourseModulePrefe // Package marked as downloading, get module info to be able to handle links. Get module filters too. await Promise.all([ - CoreCourse.instance.getModuleBasicInfo(module.id, siteId), - CoreCourse.instance.getModule(module.id, courseId, undefined, false, true, siteId), - CoreFilterHelper.instance.getFilters('module', module.id, { courseId }), + CoreCourse.getModuleBasicInfo(module.id, siteId), + CoreCourse.getModule(module.id, courseId, undefined, false, true, siteId), + CoreFilterHelper.getFilters('module', module.id, { courseId }), ]); // Call the download function. @@ -151,9 +151,9 @@ export class CoreCourseActivityPrefetchHandlerBase extends CoreCourseModulePrefe * @return Promise resolved when done. */ setDownloaded(id: number, siteId?: string, extra?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - return CoreFilepool.instance.storePackageStatus(siteId, CoreConstants.DOWNLOADED, this.component, id, extra); + return CoreFilepool.storePackageStatus(siteId, CoreConstants.DOWNLOADED, this.component, id, extra); } /** @@ -164,9 +164,9 @@ export class CoreCourseActivityPrefetchHandlerBase extends CoreCourseModulePrefe * @return Promise resolved when done. */ setDownloading(id: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - return CoreFilepool.instance.storePackageStatus(siteId, CoreConstants.DOWNLOADING, this.component, id); + return CoreFilepool.storePackageStatus(siteId, CoreConstants.DOWNLOADING, this.component, id); } /** @@ -177,9 +177,9 @@ export class CoreCourseActivityPrefetchHandlerBase extends CoreCourseModulePrefe * @return Rejected promise. */ async setPreviousStatus(id: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - await CoreFilepool.instance.setPackagePreviousStatus(siteId, this.component, id); + await CoreFilepool.setPackagePreviousStatus(siteId, this.component, id); } /** @@ -192,9 +192,9 @@ export class CoreCourseActivityPrefetchHandlerBase extends CoreCourseModulePrefe * @deprecated since 3.9.5. Use setPreviousStatus instead. */ async setPreviousStatusAndReject(id: number, error?: Error, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - await CoreFilepool.instance.setPackagePreviousStatus(siteId, this.component, id); + await CoreFilepool.setPackagePreviousStatus(siteId, this.component, id); throw error; } diff --git a/src/core/features/course/classes/activity-sync.ts b/src/core/features/course/classes/activity-sync.ts index ee5bb8983..0bfaf2254 100644 --- a/src/core/features/course/classes/activity-sync.ts +++ b/src/core/features/course/classes/activity-sync.ts @@ -39,7 +39,7 @@ export class CoreCourseActivitySyncBaseProvider extends CoreSyncBasePr siteId?: string, ): Promise { // Get the module updates to check if the data was updated or not. - const result = await CoreCourseModulePrefetchDelegate.instance.getModuleUpdates(module, courseId, true, siteId); + const result = await CoreCourseModulePrefetchDelegate.getModuleUpdates(module, courseId, true, siteId); if (!result?.updates.length) { return; diff --git a/src/core/features/course/classes/main-activity-component.ts b/src/core/features/course/classes/main-activity-component.ts index 5425d7dd7..4fdcfe9e9 100644 --- a/src/core/features/course/classes/main-activity-component.ts +++ b/src/core/features/course/classes/main-activity-component.ts @@ -56,10 +56,10 @@ export class CoreCourseModuleMainActivityComponent extends CoreCourseModuleMainR super(loggerName, courseContentsPage); // Refresh online status when changes. - this.onlineSubscription = Network.instance.onChange().subscribe(() => { + this.onlineSubscription = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { - this.isOnline = CoreApp.instance.isOnline(); + NgZone.run(() => { + this.isOnline = CoreApp.isOnline(); }); }); } @@ -72,7 +72,7 @@ export class CoreCourseModuleMainActivityComponent extends CoreCourseModuleMainR this.hasOffline = false; this.syncIcon = CoreConstants.ICON_LOADING; - this.moduleName = CoreCourse.instance.translateModuleName(this.moduleName || ''); + this.moduleName = CoreCourse.translateModuleName(this.moduleName || ''); if (this.syncEventName) { // Refresh data if this discussion is synchronized automatically. @@ -122,7 +122,7 @@ export class CoreCourseModuleMainActivityComponent extends CoreCourseModuleMainR this.syncIcon = CoreConstants.ICON_LOADING; try { - await CoreUtils.instance.ignoreErrors(this.invalidateContent()); + await CoreUtils.ignoreErrors(this.invalidateContent()); await this.loadContent(true, sync, showErrors); } finally { @@ -190,7 +190,7 @@ export class CoreCourseModuleMainActivityComponent extends CoreCourseModuleMainR * @return Promise resolved when done. */ protected async loadContent(refresh?: boolean, sync: boolean = false, showErrors: boolean = false): Promise { - this.isOnline = CoreApp.instance.isOnline(); + this.isOnline = CoreApp.isOnline(); if (!this.module) { // This can happen if course format changes from single activity to weekly/topics. @@ -205,7 +205,7 @@ export class CoreCourseModuleMainActivityComponent extends CoreCourseModuleMainR return await this.refreshContent(sync); } - CoreDomUtils.instance.showErrorModalDefault(error, this.fetchContentDefaultError, true); + CoreDomUtils.showErrorModalDefault(error, this.fetchContentDefaultError, true); } finally { this.loaded = true; this.refreshIcon = CoreConstants.ICON_REFRESH; @@ -244,13 +244,13 @@ export class CoreCourseModuleMainActivityComponent extends CoreCourseModuleMainR const result = <{warnings?: CoreWSExternalWarning[]}> await this.sync(); if (result?.warnings?.length) { - CoreDomUtils.instance.showErrorModal(result.warnings[0]); + CoreDomUtils.showErrorModal(result.warnings[0]); } return this.hasSyncSucceed(result); } catch (error) { if (showErrors) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errorsync', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errorsync', true); } return false; diff --git a/src/core/features/course/classes/main-resource-component.ts b/src/core/features/course/classes/main-resource-component.ts index 92fc58eb9..79bb5727a 100644 --- a/src/core/features/course/classes/main-resource-component.ts +++ b/src/core/features/course/classes/main-resource-component.ts @@ -85,7 +85,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, * Component being initialized. */ async ngOnInit(): Promise { - this.siteId = CoreSites.instance.getCurrentSiteId(); + this.siteId = CoreSites.getCurrentSiteId(); this.description = this.module?.description; this.componentId = this.module?.id; this.externalUrl = this.module?.url; @@ -108,11 +108,11 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, // If it's a single activity course and the refresher is displayed within the component, // call doRefresh on the section page to refresh the course data. - if (this.courseContentsPage && !CoreCourseModuleDelegate.instance.displayRefresherInSingleActivity(this.module.modname)) { - await CoreUtils.instance.ignoreErrors(this.courseContentsPage.doRefresh()); + if (this.courseContentsPage && !CoreCourseModuleDelegate.displayRefresherInSingleActivity(this.module.modname)) { + await CoreUtils.ignoreErrors(this.courseContentsPage.doRefresh()); } - await CoreUtils.instance.ignoreErrors(this.refreshContent(true, showErrors)); + await CoreUtils.ignoreErrors(this.refreshContent(true, showErrors)); refresher?.detail.complete(); done && done(); @@ -135,7 +135,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, this.refreshIcon = CoreConstants.ICON_LOADING; try { - await CoreUtils.instance.ignoreErrors(this.invalidateContent()); + await CoreUtils.ignoreErrors(this.invalidateContent()); await this.loadContent(true); } finally { @@ -178,7 +178,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, try { await this.fetchContent(refresh); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, this.fetchContentDefaultError, true); + CoreDomUtils.showErrorModalDefault(error, this.fetchContentDefaultError, true); } finally { this.loaded = true; this.refreshIcon = CoreConstants.ICON_REFRESH; @@ -194,7 +194,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, } // All data obtained, now fill the context menu. - CoreCourseHelper.instance.fillContextMenu(this, this.module, this.courseId!, refresh, this.component); + CoreCourseHelper.fillContextMenu(this, this.module, this.courseId!, refresh, this.component); } /** @@ -209,7 +209,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, * Expand the description. */ expandDescription(): void { - CoreTextUtils.instance.viewText(Translate.instance.instant('core.description'), this.description!, { + CoreTextUtils.viewText(Translate.instant('core.description'), this.description!, { component: this.component, componentId: this.module?.id, filter: true, @@ -224,7 +224,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, */ async gotoBlog(): Promise { // const params: Params = { cmId: this.module?.id }; - // @todo return CoreNavigator.instance.navigateToSitePath('AddonBlogEntriesPage', { params }); + // @todo return CoreNavigator.navigateToSitePath('AddonBlogEntriesPage', { params }); } /** @@ -237,7 +237,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, return; } - CoreCourseHelper.instance.contextMenuPrefetch(this, this.module, this.courseId!, done); + CoreCourseHelper.contextMenuPrefetch(this, this.module, this.courseId!, done); } /** @@ -251,12 +251,12 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, } if (this.prefetchStatus == CoreConstants.DOWNLOADING) { - CoreDomUtils.instance.showAlertTranslated(undefined, 'core.course.cannotdeletewhiledownloading'); + CoreDomUtils.showAlertTranslated(undefined, 'core.course.cannotdeletewhiledownloading'); return; } - CoreCourseHelper.instance.confirmAndRemoveFiles(this.module, this.courseId!, done); + CoreCourseHelper.confirmAndRemoveFiles(this.module, this.courseId!, done); } /** @@ -267,14 +267,14 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, */ protected getErrorDownloadingSomeFilesMessage(error: string | CoreTextErrorObject, multiLine?: boolean): string { if (multiLine) { - return CoreTextUtils.instance.buildSeveralParagraphsMessage([ - Translate.instance.instant('core.errordownloadingsomefiles'), + return CoreTextUtils.buildSeveralParagraphsMessage([ + Translate.instant('core.errordownloadingsomefiles'), error, ]); } else { - error = CoreTextUtils.instance.getErrorMessageFromError(error) || error; + error = CoreTextUtils.getErrorMessageFromError(error) || error; - return Translate.instance.instant('core.errordownloadingsomefiles') + (error ? ' ' + error : ''); + return Translate.instant('core.errordownloadingsomefiles') + (error ? ' ' + error : ''); } } @@ -284,7 +284,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, * @param error The specific error. */ protected showErrorDownloadingSomeFiles(error: string | CoreTextErrorObject): void { - CoreDomUtils.instance.showErrorModal(this.getErrorDownloadingSomeFilesMessage(error, true)); + CoreDomUtils.showErrorModal(this.getErrorDownloadingSomeFilesMessage(error, true)); } /** @@ -322,7 +322,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, }, this.siteId); // Also, get the current status. - const status = await CoreCourseModulePrefetchDelegate.instance.getModuleStatus(this.module, this.courseId!); + const status = await CoreCourseModulePrefetchDelegate.getModuleStatus(this.module, this.courseId!); this.currentStatus = status; this.showStatus(status); @@ -355,7 +355,7 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, if (this.currentStatus != CoreConstants.DOWNLOADED) { // Download content. This function also loads module contents if needed. try { - await CoreCourseModulePrefetchDelegate.instance.downloadModule(this.module, this.courseId!); + await CoreCourseModulePrefetchDelegate.downloadModule(this.module, this.courseId!); // If we reach here it means the download process already loaded the contents, no need to do it again. contentsAlreadyLoaded = true; @@ -368,14 +368,14 @@ export class CoreCourseModuleMainResourceComponent implements OnInit, OnDestroy, if (!this.module.contents.length || (refresh && !contentsAlreadyLoaded)) { // Try to load the contents. - const ignoreCache = refresh && CoreApp.instance.isOnline(); + const ignoreCache = refresh && CoreApp.isOnline(); try { - await CoreCourse.instance.loadModuleContents(this.module, this.courseId, undefined, false, ignoreCache); + await CoreCourse.loadModuleContents(this.module, this.courseId, undefined, false, ignoreCache); } catch (error) { // Error loading contents. If we ignored cache, try to get the cached value. if (ignoreCache && !this.module.contents) { - await CoreCourse.instance.loadModuleContents(this.module, this.courseId); + await CoreCourse.loadModuleContents(this.module, this.courseId); } else if (!this.module.contents) { // Not able to load contents, throw the error. throw error; diff --git a/src/core/features/course/classes/module-prefetch-handler.ts b/src/core/features/course/classes/module-prefetch-handler.ts index 6c3d48ab1..1df8285e0 100644 --- a/src/core/features/course/classes/module-prefetch-handler.ts +++ b/src/core/features/course/classes/module-prefetch-handler.ts @@ -67,7 +67,7 @@ export class CoreCourseModulePrefetchHandlerBase implements CoreCourseModulePref * @return Promise of the current download. */ async addOngoingDownload(id: number, promise: Promise, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const uniqueId = this.getUniqueId(id); @@ -125,7 +125,7 @@ export class CoreCourseModulePrefetchHandlerBase implements CoreCourseModulePref try { const files = await this.getFiles(module, courseId); - return await CorePluginFileDelegate.instance.getFilesDownloadSize(files); + return await CorePluginFileDelegate.getFilesDownloadSize(files); } catch { return { size: -1, total: false }; } @@ -140,9 +140,9 @@ export class CoreCourseModulePrefetchHandlerBase implements CoreCourseModulePref */ // eslint-disable-next-line @typescript-eslint/no-unused-vars async getDownloadedSize(module: CoreCourseAnyModuleData, courseId: number): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); - return CoreFilepool.instance.getFilesSizeByComponent(siteId, this.component, module.id); + return CoreFilepool.getFilesSizeByComponent(siteId, this.component, module.id); } /** @@ -184,12 +184,12 @@ export class CoreCourseModulePrefetchHandlerBase implements CoreCourseModulePref if (typeof instance.introfiles != 'undefined') { return instance.introfiles; } else if (instance.intro) { - return CoreFilepool.instance.extractDownloadableFilesFromHtmlAsFakeFileObjects(instance.intro); + return CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(instance.intro); } } if ('description' in module && module.description) { - return CoreFilepool.instance.extractDownloadableFilesFromHtmlAsFakeFileObjects(module.description); + return CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(module.description); } return []; @@ -203,7 +203,7 @@ export class CoreCourseModulePrefetchHandlerBase implements CoreCourseModulePref * @return Promise of the current download. */ async getOngoingDownload(id: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.isDownloading(id, siteId)) { // There's already a download ongoing, return the promise. @@ -244,7 +244,7 @@ export class CoreCourseModulePrefetchHandlerBase implements CoreCourseModulePref */ // eslint-disable-next-line @typescript-eslint/no-unused-vars invalidateModule(module: CoreCourseAnyModuleData, courseId: number): Promise { - return CoreCourse.instance.invalidateModule(module.id); + return CoreCourse.invalidateModule(module.id); } /** @@ -268,7 +268,7 @@ export class CoreCourseModulePrefetchHandlerBase implements CoreCourseModulePref * @return True if downloading, false otherwise. */ isDownloading(id: number, siteId?: string): boolean { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); return !!(this.downloadPromises[siteId] && this.downloadPromises[siteId][this.getUniqueId(id)]); } @@ -330,7 +330,7 @@ export class CoreCourseModulePrefetchHandlerBase implements CoreCourseModulePref */ // eslint-disable-next-line @typescript-eslint/no-unused-vars removeFiles(module: CoreCourseAnyModuleData, courseId: number): Promise { - return CoreFilepool.instance.removeFilesByComponent(CoreSites.instance.getCurrentSiteId(), this.component, module.id); + return CoreFilepool.removeFilesByComponent(CoreSites.getCurrentSiteId(), this.component, module.id); } } diff --git a/src/core/features/course/classes/resource-prefetch-handler.ts b/src/core/features/course/classes/resource-prefetch-handler.ts index 899fb729f..d55fd69c8 100644 --- a/src/core/features/course/classes/resource-prefetch-handler.ts +++ b/src/core/features/course/classes/resource-prefetch-handler.ts @@ -57,12 +57,12 @@ export class CoreCourseResourcePrefetchHandlerBase extends CoreCourseModulePrefe * @return Promise resolved when all content is downloaded. */ async downloadOrPrefetch(module: CoreCourseWSModule, courseId: number, prefetch?: boolean, dirPath?: string): Promise { - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // Cannot download in offline. throw new CoreNetworkError(); } - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); if (this.isDownloading(module.id, siteId)) { // There's already a download ongoing for this module, return the promise. @@ -92,7 +92,7 @@ export class CoreCourseResourcePrefetchHandlerBase extends CoreCourseModulePrefe dirPath?: string, ): Promise { // Get module info to be able to handle links. - await CoreCourse.instance.getModuleBasicInfo(module.id, siteId); + await CoreCourse.getModuleBasicInfo(module.id, siteId); // Load module contents (ignore cache so we always have the latest data). await this.loadContents(module, courseId, true); @@ -106,11 +106,11 @@ export class CoreCourseResourcePrefetchHandlerBase extends CoreCourseModulePrefe if (dirPath) { // Download intro files in filepool root folder. promises.push( - CoreFilepool.instance.downloadOrPrefetchFiles(siteId, introFiles, prefetch, false, this.component, module.id), + CoreFilepool.downloadOrPrefetchFiles(siteId, introFiles, prefetch, false, this.component, module.id), ); // Download content files inside dirPath. - promises.push(CoreFilepool.instance.downloadOrPrefetchPackage( + promises.push(CoreFilepool.downloadOrPrefetchPackage( siteId, contentFiles, prefetch, @@ -121,7 +121,7 @@ export class CoreCourseResourcePrefetchHandlerBase extends CoreCourseModulePrefe )); } else { // No dirPath, download everything in filepool root folder. - promises.push(CoreFilepool.instance.downloadOrPrefetchPackage( + promises.push(CoreFilepool.downloadOrPrefetchPackage( siteId, introFiles.concat(contentFiles), prefetch, @@ -130,7 +130,7 @@ export class CoreCourseResourcePrefetchHandlerBase extends CoreCourseModulePrefe )); } - promises.push(CoreFilterHelper.instance.getFilters('module', module.id, { courseId })); + promises.push(CoreFilterHelper.getFilters('module', module.id, { courseId })); await Promise.all(promises); } @@ -162,11 +162,11 @@ export class CoreCourseResourcePrefetchHandlerBase extends CoreCourseModulePrefe */ // eslint-disable-next-line @typescript-eslint/no-unused-vars async invalidateContent(moduleId: number, courseId: number): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); await Promise.all([ - CoreCourse.instance.invalidateModule(moduleId), - CoreFilepool.instance.invalidateFilesByComponent(siteId, this.component, moduleId), + CoreCourse.invalidateModule(moduleId), + CoreFilepool.invalidateFilesByComponent(siteId, this.component, moduleId), ]); } @@ -179,7 +179,7 @@ export class CoreCourseResourcePrefetchHandlerBase extends CoreCourseModulePrefe * @return Promise resolved when loaded. */ loadContents(module: CoreCourseWSModule, courseId: number, ignoreCache?: boolean): Promise { - return CoreCourse.instance.loadModuleContents(module, courseId, undefined, false, ignoreCache); + return CoreCourse.loadModuleContents(module, courseId, undefined, false, ignoreCache); } /** diff --git a/src/core/features/course/components/format/format.ts b/src/core/features/course/components/format/format.ts index 3ca97684b..07414a062 100644 --- a/src/core/features/course/components/format/format.ts +++ b/src/core/features/course/components/format/format.ts @@ -132,8 +132,8 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { // Check if the affected section is being downloaded. // If so, we don't update section status because it'll already be updated when the download finishes. - const downloadId = CoreCourseHelper.instance.getSectionDownloadId({ id: data.sectionId }); - if (CoreCourseModulePrefetchDelegate.instance.isBeingDownloaded(downloadId)) { + const downloadId = CoreCourseHelper.getSectionDownloadId({ id: data.sectionId }); + if (CoreCourseModulePrefetchDelegate.isBeingDownloaded(downloadId)) { return; } @@ -144,14 +144,14 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { } // Recalculate the status. - await CoreCourseHelper.instance.calculateSectionStatus(section, this.course.id, false); + await CoreCourseHelper.calculateSectionStatus(section, this.course.id, false); - if (section.isDownloading && !CoreCourseModulePrefetchDelegate.instance.isBeingDownloaded(downloadId)) { + if (section.isDownloading && !CoreCourseModulePrefetchDelegate.isBeingDownloaded(downloadId)) { // All the modules are now downloading, set a download all promise. this.prefetch(section); } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); // Listen for select course tab events to select the right section if needed. @@ -184,8 +184,8 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { // Course has changed, try to get the components. this.getComponents(); - this.displaySectionSelector = CoreCourseFormatDelegate.instance.displaySectionSelector(this.course); - this.displayBlocks = CoreCourseFormatDelegate.instance.displayBlocks(this.course); + this.displaySectionSelector = CoreCourseFormatDelegate.displaySectionSelector(this.course); + this.displayBlocks = CoreCourseFormatDelegate.displayBlocks(this.course); this.progress = 'progress' in this.course && typeof this.course.progress == 'number' && this.course.progress >= 0 && this.course.completionusertracked !== false ? this.course.progress : undefined; if ('overviewfiles' in this.course) { @@ -241,7 +241,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { * @return Promise resolved when done. */ protected async loadCourseFormatComponent(): Promise { - this.courseFormatComponent = await CoreCourseFormatDelegate.instance.getCourseFormatComponent(this.course!); + this.courseFormatComponent = await CoreCourseFormatDelegate.getCourseFormatComponent(this.course!); } /** @@ -250,7 +250,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { * @return Promise resolved when done. */ protected async loadCourseSummaryComponent(): Promise { - this.courseSummaryComponent = await CoreCourseFormatDelegate.instance.getCourseSummaryComponent(this.course!); + this.courseSummaryComponent = await CoreCourseFormatDelegate.getCourseSummaryComponent(this.course!); } /** @@ -259,7 +259,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { * @return Promise resolved when done. */ protected async loadSectionSelectorComponent(): Promise { - this.sectionSelectorComponent = await CoreCourseFormatDelegate.instance.getSectionSelectorComponent(this.course!); + this.sectionSelectorComponent = await CoreCourseFormatDelegate.getSectionSelectorComponent(this.course!); } /** @@ -268,7 +268,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { * @return Promise resolved when done. */ protected async loadSingleSectionComponent(): Promise { - this.singleSectionComponent = await CoreCourseFormatDelegate.instance.getSingleSectionComponent(this.course!); + this.singleSectionComponent = await CoreCourseFormatDelegate.getSingleSectionComponent(this.course!); } /** @@ -277,7 +277,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { * @return Promise resolved when done. */ protected async loadAllSectionsComponent(): Promise { - this.allSectionsComponent = await CoreCourseFormatDelegate.instance.getAllSectionsComponent(this.course!); + this.allSectionsComponent = await CoreCourseFormatDelegate.getAllSectionsComponent(this.course!); } /** @@ -296,7 +296,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { if (!newSection) { // Section not found, calculate which one to use. - newSection = await CoreCourseFormatDelegate.instance.getCurrentSection(this.course!, sections); + newSection = await CoreCourseFormatDelegate.getCurrentSection(this.course!, sections); } this.sectionChanged(newSection); @@ -326,7 +326,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { if (!this.loaded) { // No section specified, not found or not visible, get current section. - const section = await CoreCourseFormatDelegate.instance.getCurrentSection(this.course!, sections); + const section = await CoreCourseFormatDelegate.getCurrentSection(this.course!, sections); this.loaded = true; this.sectionChanged(section); @@ -345,7 +345,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { this.sectionSelectorExpanded = true; - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: CoreCourseSectionSelectorComponent, componentProps: { course: this.course, @@ -404,7 +404,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { if (this.moduleId && typeof previousValue == 'undefined') { setTimeout(() => { - CoreDomUtils.instance.scrollToElementBySelector( + CoreDomUtils.scrollToElementBySelector( this.elementRef.nativeElement, this.content, '#core-course-module-' + this.moduleId, @@ -416,8 +416,8 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { if (!previousValue || previousValue.id != newSection.id) { // First load or section changed, add log in Moodle. - CoreUtils.instance.ignoreErrors( - CoreCourse.instance.logView(this.course!.id, newSection.section, undefined, this.course!.fullname), + CoreUtils.ignoreErrors( + CoreCourse.logView(this.course!.id, newSection.section, undefined, this.course!.fullname), ); } } @@ -443,7 +443,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { return; } - CoreUtils.instance.ignoreErrors(CoreCourseHelper.instance.calculateSectionsStatus(this.sections, this.course.id, refresh)); + CoreUtils.ignoreErrors(CoreCourseHelper.calculateSectionsStatus(this.sections, this.course.id, refresh)); } /** @@ -456,13 +456,13 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { section.isCalculating = true; try { - await CoreCourseHelper.instance.confirmDownloadSizeSection(this.course!.id, section, this.sections); + await CoreCourseHelper.confirmDownloadSizeSection(this.course!.id, section, this.sections); await this.prefetchSection(section, true); } catch (error) { // User cancelled or there was an error calculating the size. if (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } } finally { section.isCalculating = false; @@ -478,14 +478,14 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { */ protected async prefetchSection(section: CoreCourseSectionWithStatus, manual?: boolean): Promise { try { - await CoreCourseHelper.instance.prefetchSection(section, this.course!.id, this.sections); + await CoreCourseHelper.prefetchSection(section, this.course!.id, this.sections); } catch (error) { // Don't show error message if it's an automatic download. if (!manual) { return; } - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingsection', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingsection', true); } } @@ -572,9 +572,9 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { // The download status of a section might have been changed from within a module page. if (this.selectedSection && this.selectedSection.id !== CoreCourseProvider.ALL_SECTIONS_ID) { - CoreCourseHelper.instance.calculateSectionStatus(this.selectedSection, this.course.id, false, false); + CoreCourseHelper.calculateSectionStatus(this.selectedSection, this.course.id, false, false); } else { - CoreCourseHelper.instance.calculateSectionsStatus(this.sections, this.course.id, false, false); + CoreCourseHelper.calculateSectionsStatus(this.sections, this.course.id, false, false); } } @@ -633,7 +633,7 @@ export class CoreCourseFormatComponent implements OnInit, OnChanges, OnDestroy { return; } - CoreCourseHelper.instance.calculateSectionsStatus(this.sections, this.course.id, false, false); + CoreCourseHelper.calculateSectionsStatus(this.sections, this.course.id, false, false); } } diff --git a/src/core/features/course/components/module-completion/module-completion.ts b/src/core/features/course/components/module-completion/module-completion.ts index 8f195d0f0..4646dc0dc 100644 --- a/src/core/features/course/components/module-completion/module-completion.ts +++ b/src/core/features/course/components/module-completion/module-completion.ts @@ -71,11 +71,11 @@ export class CoreCourseModuleCompletionComponent implements OnChanges { e.preventDefault(); e.stopPropagation(); - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); this.completion.state = this.completion.state === 1 ? 0 : 1; try { - const response = await CoreCourse.instance.markCompletedManually( + const response = await CoreCourse.markCompletedManually( this.completion.cmid, this.completion.state === 1, this.completion.courseId!, @@ -91,7 +91,7 @@ export class CoreCourseModuleCompletionComponent implements OnChanges { this.completionChanged.emit(this.completion); } catch (error) { this.completion.state = this.completion.state === 1 ? 0 : 1; - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errorchangecompletion', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errorchangecompletion', true); } finally { modal.dismiss(); } @@ -146,7 +146,7 @@ export class CoreCourseModuleCompletionComponent implements OnChanges { return; } - const result = await CoreFilterHelper.instance.getFiltersAndFormatText( + const result = await CoreFilterHelper.getFiltersAndFormatText( moduleName, 'module', this.moduleId, @@ -160,7 +160,7 @@ export class CoreCourseModuleCompletionComponent implements OnChanges { if (this.completion.overrideby > 0) { langKey += '-override'; - const profile = await CoreUser.instance.getProfile(this.completion.overrideby, this.completion.courseId, true); + const profile = await CoreUser.getProfile(this.completion.overrideby, this.completion.courseId, true); translateParams = { $a: { @@ -170,7 +170,7 @@ export class CoreCourseModuleCompletionComponent implements OnChanges { }; } - this.completionDescription = Translate.instance.instant(langKey, translateParams); + this.completionDescription = Translate.instant(langKey, translateParams); } } diff --git a/src/core/features/course/components/module/module.ts b/src/core/features/course/components/module/module.ts index d3450472b..b1bdd5a0d 100644 --- a/src/core/features/course/components/module/module.ts +++ b/src/core/features/course/components/module/module.ts @@ -86,7 +86,7 @@ export class CoreCourseModuleComponent implements OnInit, OnDestroy { } this.courseId = this.courseId || this.module.course; - this.modNameTranslated = CoreCourse.instance.translateModuleName(this.module.modname) || ''; + this.modNameTranslated = CoreCourse.translateModuleName(this.module.modname) || ''; if (!this.module.handlerData) { return; @@ -96,8 +96,8 @@ export class CoreCourseModuleComponent implements OnInit, OnDestroy { if (this.module.handlerData.showDownloadButton) { // Listen for changes on this module status, even if download isn't enabled. - this.prefetchHandler = CoreCourseModulePrefetchDelegate.instance.getPrefetchHandlerFor(this.module); - this.canCheckUpdates = CoreCourseModulePrefetchDelegate.instance.canCheckUpdates(); + this.prefetchHandler = CoreCourseModulePrefetchDelegate.getPrefetchHandlerFor(this.module); + this.canCheckUpdates = CoreCourseModulePrefetchDelegate.canCheckUpdates(); this.statusObserver = CoreEvents.on(CoreEvents.PACKAGE_STATUS_CHANGED, (data) => { if (!this.module || data.componentId != this.module.id || !this.prefetchHandler || @@ -106,7 +106,7 @@ export class CoreCourseModuleComponent implements OnInit, OnDestroy { } // Call determineModuleStatus to get the right status to display. - const status = CoreCourseModulePrefetchDelegate.instance.determineModuleStatus(this.module, data.status); + const status = CoreCourseModulePrefetchDelegate.determineModuleStatus(this.module, data.status); if (this.downloadEnabled) { // Download is enabled, show the status. @@ -115,7 +115,7 @@ export class CoreCourseModuleComponent implements OnInit, OnDestroy { // Download isn't enabled but the handler defines a updateStatus function, call it anyway. this.module.handlerData.updateStatus(status); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } } @@ -165,7 +165,7 @@ export class CoreCourseModuleComponent implements OnInit, OnDestroy { // Get download size to ask for confirm if it's high. const size = await this.prefetchHandler.getDownloadSize(this.module, this.courseId!, true); - await CoreCourseHelper.instance.prefetchModule(this.prefetchHandler, this.module, size, this.courseId!, refresh); + await CoreCourseHelper.prefetchModule(this.prefetchHandler, this.module, size, this.courseId!, refresh); const eventData = { sectionId: this.section?.id, @@ -177,7 +177,7 @@ export class CoreCourseModuleComponent implements OnInit, OnDestroy { // Error, hide spinner. this.spinner = false; if (!this.isDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); } } } @@ -208,7 +208,7 @@ export class CoreCourseModuleComponent implements OnInit, OnDestroy { return; } - const status = await CoreCourseModulePrefetchDelegate.instance.getModuleStatus(this.module, this.courseId); + const status = await CoreCourseModulePrefetchDelegate.getModuleStatus(this.module, this.courseId); this.showStatus(status); } diff --git a/src/core/features/course/components/section-selector/section-selector.ts b/src/core/features/course/components/section-selector/section-selector.ts index 623d4473b..06b74987d 100644 --- a/src/core/features/course/components/section-selector/section-selector.ts +++ b/src/core/features/course/components/section-selector/section-selector.ts @@ -45,7 +45,7 @@ export class CoreCourseSectionSelectorComponent implements OnInit { return; } - const formatOptions = CoreUtils.instance.objectToKeyValueMap(this.course.courseformatoptions, 'name', 'value'); + const formatOptions = CoreUtils.objectToKeyValueMap(this.course.courseformatoptions, 'name', 'value'); if (!formatOptions || formatOptions.coursedisplay != 1 || formatOptions.completionusertracked === false) { return; @@ -77,7 +77,7 @@ export class CoreCourseSectionSelectorComponent implements OnInit { * Close the modal. */ closeModal(): void { - ModalController.instance.dismiss(); + ModalController.dismiss(); } /** @@ -87,7 +87,7 @@ export class CoreCourseSectionSelectorComponent implements OnInit { */ selectSection(section: SectionWithProgress): void { if (section.uservisible !== false) { - ModalController.instance.dismiss(section); + ModalController.dismiss(section); } } diff --git a/src/core/features/course/components/tag-area/tag-area.ts b/src/core/features/course/components/tag-area/tag-area.ts index 401ba9b64..9f841771f 100644 --- a/src/core/features/course/components/tag-area/tag-area.ts +++ b/src/core/features/course/components/tag-area/tag-area.ts @@ -36,7 +36,7 @@ export class CoreCourseTagAreaComponent { openCourse(courseId: number): void { // @todo If this component is inside a split view, use the master nav to open it. // const navCtrl = this.splitviewCtrl ? this.splitviewCtrl.getMasterNav() : this.navCtrl; - CoreCourseHelper.instance.getAndOpenCourse(courseId); + CoreCourseHelper.getAndOpenCourse(courseId); } } diff --git a/src/core/features/course/components/unsupported-module/unsupported-module.ts b/src/core/features/course/components/unsupported-module/unsupported-module.ts index b03e6709b..b8be27123 100644 --- a/src/core/features/course/components/unsupported-module/unsupported-module.ts +++ b/src/core/features/course/components/unsupported-module/unsupported-module.ts @@ -41,9 +41,9 @@ export class CoreCourseUnsupportedModuleComponent implements OnInit { return; } - this.isDisabledInSite = CoreCourseModuleDelegate.instance.isModuleDisabledInSite(this.module.modname); - this.isSupportedByTheApp = CoreCourseModuleDelegate.instance.hasHandler(this.module.modname); - this.moduleName = CoreCourse.instance.translateModuleName(this.module.modname); + this.isDisabledInSite = CoreCourseModuleDelegate.isModuleDisabledInSite(this.module.modname); + this.isSupportedByTheApp = CoreCourseModuleDelegate.hasHandler(this.module.modname); + this.moduleName = CoreCourse.translateModuleName(this.module.modname); } } diff --git a/src/core/features/course/course.module.ts b/src/core/features/course/course.module.ts index 4d1563d58..8c921270f 100644 --- a/src/core/features/course/course.module.ts +++ b/src/core/features/course/course.module.ts @@ -67,13 +67,13 @@ const courseIndexRoutes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreCronDelegate.instance.register(CoreCourseSyncCronHandler.instance); - CoreCronDelegate.instance.register(CoreCourseLogCronHandler.instance); - CoreTagAreaDelegate.instance.registerHandler(CoreCourseTagAreaHandler.instance); - CoreTagAreaDelegate.instance.registerHandler(CoreCourseModulesTagAreaHandler.instance); + CoreCronDelegate.register(CoreCourseSyncCronHandler.instance); + CoreCronDelegate.register(CoreCourseLogCronHandler.instance); + CoreTagAreaDelegate.registerHandler(CoreCourseTagAreaHandler.instance); + CoreTagAreaDelegate.registerHandler(CoreCourseModulesTagAreaHandler.instance); - CoreCourse.instance.initialize(); - CoreCourseModulePrefetchDelegate.instance.initialize(); + CoreCourse.initialize(); + CoreCourseModulePrefetchDelegate.initialize(); }, }, ], diff --git a/src/core/features/course/directives/download-module-main-file.ts b/src/core/features/course/directives/download-module-main-file.ts index 3d99485de..bf62ab094 100644 --- a/src/core/features/course/directives/download-module-main-file.ts +++ b/src/core/features/course/directives/download-module-main-file.ts @@ -55,19 +55,19 @@ export class CoreCourseDownloadModuleMainFileDirective implements OnInit { ev.preventDefault(); ev.stopPropagation(); - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); const courseId = typeof this.courseId == 'string' ? parseInt(this.courseId, 10) : this.courseId; try { if (!this.module) { // Try to get the module from cache. this.moduleId = typeof this.moduleId == 'string' ? parseInt(this.moduleId, 10) : this.moduleId; - this.module = await CoreCourse.instance.getModule(this.moduleId!, courseId); + this.module = await CoreCourse.getModule(this.moduleId!, courseId); } const componentId = this.componentId || module.id; - await CoreCourseHelper.instance.downloadModuleAndOpenFile( + await CoreCourseHelper.downloadModuleAndOpenFile( this.module, courseId ?? this.module.course!, this.component, @@ -75,7 +75,7 @@ export class CoreCourseDownloadModuleMainFileDirective implements OnInit { this.files, ); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); } finally { modal.dismiss(); } diff --git a/src/core/features/course/format/singleactivity/components/singleactivity.ts b/src/core/features/course/format/singleactivity/components/singleactivity.ts index 3cb1f4e42..eae6ca273 100644 --- a/src/core/features/course/format/singleactivity/components/singleactivity.ts +++ b/src/core/features/course/format/singleactivity/components/singleactivity.ts @@ -65,7 +65,7 @@ export class CoreCourseFormatSingleActivityComponent implements OnChanges { if (module && !this.componentClass) { // We haven't obtained the class yet. Get it now. - const component = await CoreCourseModuleDelegate.instance.getMainComponent(this.course, module); + const component = await CoreCourseModuleDelegate.getMainComponent(this.course, module); this.componentClass = component || CoreCourseUnsupportedModuleComponent; } } diff --git a/src/core/features/course/format/singleactivity/services/handlers/singleactivity-format.ts b/src/core/features/course/format/singleactivity/services/handlers/singleactivity-format.ts index a23f09060..9efe6fc27 100644 --- a/src/core/features/course/format/singleactivity/services/handlers/singleactivity-format.ts +++ b/src/core/features/course/format/singleactivity/services/handlers/singleactivity-format.ts @@ -115,7 +115,7 @@ export class CoreCourseFormatSingleActivityHandlerService implements CoreCourseF */ displayRefresher(course: CoreCourseAnyCourseData, sections: CoreCourseWSSection[]): boolean { if (sections?.[0]?.modules?.[0]) { - return CoreCourseModuleDelegate.instance.displayRefresherInSingleActivity(sections[0].modules[0].modname); + return CoreCourseModuleDelegate.displayRefresherInSingleActivity(sections[0].modules[0].modname); } else { return true; } @@ -149,4 +149,4 @@ export class CoreCourseFormatSingleActivityHandlerService implements CoreCourseF } -export class CoreCourseFormatSingleActivityHandler extends makeSingleton(CoreCourseFormatSingleActivityHandlerService) {} +export const CoreCourseFormatSingleActivityHandler = makeSingleton(CoreCourseFormatSingleActivityHandlerService); diff --git a/src/core/features/course/format/singleactivity/singleactivity.module.ts b/src/core/features/course/format/singleactivity/singleactivity.module.ts index be619a5ab..8db7ae9f3 100644 --- a/src/core/features/course/format/singleactivity/singleactivity.module.ts +++ b/src/core/features/course/format/singleactivity/singleactivity.module.ts @@ -32,7 +32,7 @@ import { CoreCourseFormatSingleActivityHandler } from './services/handlers/singl multi: true, deps: [], useFactory: () => () => { - CoreCourseFormatDelegate.instance.registerHandler(CoreCourseFormatSingleActivityHandler.instance); + CoreCourseFormatDelegate.registerHandler(CoreCourseFormatSingleActivityHandler.instance); }, }, ], diff --git a/src/core/features/course/format/social/services/handlers/social-format.ts b/src/core/features/course/format/social/services/handlers/social-format.ts index dde6c8711..e4a0201c8 100644 --- a/src/core/features/course/format/social/services/handlers/social-format.ts +++ b/src/core/features/course/format/social/services/handlers/social-format.ts @@ -29,4 +29,4 @@ export class CoreCourseFormatSocialHandlerService extends CoreCourseFormatSingle } -export class CoreCourseFormatSocialHandler extends makeSingleton(CoreCourseFormatSocialHandlerService) {} +export const CoreCourseFormatSocialHandler = makeSingleton(CoreCourseFormatSocialHandlerService); diff --git a/src/core/features/course/format/social/social.module.ts b/src/core/features/course/format/social/social.module.ts index 7455034b7..918fd0a25 100644 --- a/src/core/features/course/format/social/social.module.ts +++ b/src/core/features/course/format/social/social.module.ts @@ -26,7 +26,7 @@ import { CoreCourseFormatSocialHandler } from './services/handlers/social-format multi: true, deps: [], useFactory: () => () => { - CoreCourseFormatDelegate.instance.registerHandler(CoreCourseFormatSocialHandler.instance); + CoreCourseFormatDelegate.registerHandler(CoreCourseFormatSocialHandler.instance); }, }, ], diff --git a/src/core/features/course/format/topics/services/handlers/topics-format.ts b/src/core/features/course/format/topics/services/handlers/topics-format.ts index 78d305273..650b97982 100644 --- a/src/core/features/course/format/topics/services/handlers/topics-format.ts +++ b/src/core/features/course/format/topics/services/handlers/topics-format.ts @@ -37,4 +37,4 @@ export class CoreCourseFormatTopicsHandlerService implements CoreCourseFormatHan } -export class CoreCourseFormatTopicsHandler extends makeSingleton(CoreCourseFormatTopicsHandlerService) {} +export const CoreCourseFormatTopicsHandler = makeSingleton(CoreCourseFormatTopicsHandlerService); diff --git a/src/core/features/course/format/topics/topics.module.ts b/src/core/features/course/format/topics/topics.module.ts index 01c8518c4..3760c31c0 100644 --- a/src/core/features/course/format/topics/topics.module.ts +++ b/src/core/features/course/format/topics/topics.module.ts @@ -26,7 +26,7 @@ import { CoreCourseFormatTopicsHandler } from './services/handlers/topics-format multi: true, deps: [], useFactory: () => () => { - CoreCourseFormatDelegate.instance.registerHandler(CoreCourseFormatTopicsHandler.instance); + CoreCourseFormatDelegate.registerHandler(CoreCourseFormatTopicsHandler.instance); }, }, ], diff --git a/src/core/features/course/format/weeks/services/handlers/weeks-format.ts b/src/core/features/course/format/weeks/services/handlers/weeks-format.ts index 6f6b96752..4e7682eee 100644 --- a/src/core/features/course/format/weeks/services/handlers/weeks-format.ts +++ b/src/core/features/course/format/weeks/services/handlers/weeks-format.ts @@ -48,7 +48,7 @@ export class CoreCourseFormatWeeksHandlerService implements CoreCourseFormatHand * @return Current section (or promise resolved with current section). */ async getCurrentSection(course: CoreCourseAnyCourseData, sections: CoreCourseSection[]): Promise { - const now = CoreTimeUtils.instance.timestamp(); + const now = CoreTimeUtils.timestamp(); if ((course.startdate && now < course.startdate) || (course.enddate && now > course.enddate)) { // Course hasn't started yet or it has ended already. Return all sections. @@ -93,4 +93,4 @@ export class CoreCourseFormatWeeksHandlerService implements CoreCourseFormatHand } -export class CoreCourseFormatWeeksHandler extends makeSingleton(CoreCourseFormatWeeksHandlerService) {} +export const CoreCourseFormatWeeksHandler = makeSingleton(CoreCourseFormatWeeksHandlerService); diff --git a/src/core/features/course/format/weeks/weeks.module.ts b/src/core/features/course/format/weeks/weeks.module.ts index 3ad1b0f19..bf7c5e685 100644 --- a/src/core/features/course/format/weeks/weeks.module.ts +++ b/src/core/features/course/format/weeks/weeks.module.ts @@ -26,7 +26,7 @@ import { CoreCourseFormatWeeksHandler } from './services/handlers/weeks-format'; multi: true, deps: [], useFactory: () => () => { - CoreCourseFormatDelegate.instance.registerHandler(CoreCourseFormatWeeksHandler.instance); + CoreCourseFormatDelegate.registerHandler(CoreCourseFormatWeeksHandler.instance); }, }, ], diff --git a/src/core/features/course/pages/contents/contents.ts b/src/core/features/course/pages/contents/contents.ts index b44c95803..489fc3aef 100644 --- a/src/core/features/course/pages/contents/contents.ts +++ b/src/core/features/course/pages/contents/contents.ts @@ -88,23 +88,23 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { * Component being initialized. */ async ngOnInit(): Promise { - const course = CoreNavigator.instance.getRouteParam('course'); + const course = CoreNavigator.getRouteParam('course'); if (!course) { - CoreDomUtils.instance.showErrorModal('Missing required course parameter.'); - CoreNavigator.instance.back(); + CoreDomUtils.showErrorModal('Missing required course parameter.'); + CoreNavigator.back(); return; } this.course = course; - this.sectionId = CoreNavigator.instance.getRouteNumberParam('sectionId'); - this.sectionNumber = CoreNavigator.instance.getRouteNumberParam('sectionNumber'); - this.moduleId = CoreNavigator.instance.getRouteNumberParam('moduleId'); + this.sectionId = CoreNavigator.getRouteNumberParam('sectionId'); + this.sectionNumber = CoreNavigator.getRouteNumberParam('sectionNumber'); + this.moduleId = CoreNavigator.getRouteNumberParam('moduleId'); - this.displayEnableDownload = !CoreSites.instance.getCurrentSite()?.isOfflineDisabled() && - CoreCourseFormatDelegate.instance.displayEnableDownload(this.course); - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); + this.displayEnableDownload = !CoreSites.getCurrentSite()?.isOfflineDisabled() && + CoreCourseFormatDelegate.displayEnableDownload(this.course); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); this.initListeners(); @@ -127,11 +127,11 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { if (data.courseId == this.course.id || data.courseId == CoreCourseProvider.ALL_COURSES_CLEARED) { this.updateCourseStatus(data.status); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } // Check if the course format requires the view to be refreshed when completion changes. - const shouldRefresh = await CoreCourseFormatDelegate.instance.shouldRefreshWhenCompletionChanges(this.course); + const shouldRefresh = await CoreCourseFormatDelegate.shouldRefreshWhenCompletionChanges(this.course); if (!shouldRefresh) { return; } @@ -153,7 +153,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { this.refreshAfterCompletionChange(false); if (data.warnings && data.warnings[0]) { - CoreDomUtils.instance.showErrorModal(data.warnings[0]); + CoreDomUtils.showErrorModal(data.warnings[0]); } }); } @@ -177,17 +177,17 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { } // Course is being downloaded. Get the download promise. - const promise = CoreCourseHelper.instance.getCourseDownloadPromise(this.course.id); + const promise = CoreCourseHelper.getCourseDownloadPromise(this.course.id); if (promise) { // There is a download promise. Show an error if it fails. promise.catch((error) => { if (!this.isDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); } }); } else { // No download, this probably means that the app was closed while downloading. Set previous status. - const status = await CoreCourse.instance.setCoursePreviousStatus(this.course.id); + const status = await CoreCourse.setCoursePreviousStatus(this.course.id); this.updateCourseStatus(status); } @@ -202,7 +202,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { */ protected async loadData(refresh?: boolean, sync?: boolean): Promise { // First of all, get the course because the data might have changed. - const result = await CoreUtils.instance.ignoreErrors(CoreCourseHelper.instance.getCourse(this.course.id)); + const result = await CoreUtils.ignoreErrors(CoreCourseHelper.getCourse(this.course.id)); if (result) { if (this.course.id === result.course.id && 'displayname' in this.course && !('displayname' in result.course)) { @@ -214,9 +214,9 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { if (sync) { // Try to synchronize the course data. // For now we don't allow manual syncing, so ignore errors. - const result = await CoreUtils.instance.ignoreErrors(CoreCourseSync.instance.syncCourse(this.course.id)); + const result = await CoreUtils.ignoreErrors(CoreCourseSync.syncCourse(this.course.id)); if (result?.warnings?.length) { - CoreDomUtils.instance.showErrorModal(result.warnings[0]); + CoreDomUtils.showErrorModal(result.warnings[0]); } } @@ -227,7 +227,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { this.loadCourseFormatOptions(), ]); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.couldnotloadsectioncontent', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.couldnotloadsectioncontent', true); } } @@ -239,13 +239,13 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { */ protected async loadSections(refresh?: boolean): Promise { // Get all the sections. - const sections = await CoreCourse.instance.getSections(this.course.id, false, true); + const sections = await CoreCourse.getSections(this.course.id, false, true); if (refresh) { // Invalidate the recently downloaded module list. To ensure info can be prefetched. - const modules = CoreCourse.instance.getSectionsModules(sections); + const modules = CoreCourse.getSectionsModules(sections); - await CoreCourseModulePrefetchDelegate.instance.invalidateModules(modules, this.course.id); + await CoreCourseModulePrefetchDelegate.invalidateModules(modules, this.course.id); } let completionStatus: Record = {}; @@ -256,10 +256,10 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { if (sectionWithModules && typeof sectionWithModules.modules[0].completion != 'undefined') { // The module already has completion (3.6 onwards). Load the offline completion. - await CoreUtils.instance.ignoreErrors(CoreCourseHelper.instance.loadOfflineCompletion(this.course.id, sections)); + await CoreUtils.ignoreErrors(CoreCourseHelper.loadOfflineCompletion(this.course.id, sections)); } else { - const fetchedData = await CoreUtils.instance.ignoreErrors( - CoreCourse.instance.getActivitiesCompletionStatus(this.course.id), + const fetchedData = await CoreUtils.ignoreErrors( + CoreCourse.getActivitiesCompletionStatus(this.course.id), ); completionStatus = fetchedData || completionStatus; @@ -267,7 +267,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { } // Add handlers - const result = CoreCourseHelper.instance.addHandlerDataForModules( + const result = CoreCourseHelper.addHandlerDataForModules( sections, this.course.id, completionStatus, @@ -276,13 +276,13 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { ); this.sections = result.sections; - if (CoreCourseFormatDelegate.instance.canViewAllSections(this.course)) { + if (CoreCourseFormatDelegate.canViewAllSections(this.course)) { // Add a fake first section (all sections). - this.sections.unshift(CoreCourseHelper.instance.createAllSectionsSection()); + this.sections.unshift(CoreCourseHelper.createAllSectionsSection()); } // Get whether to show the refresher now that we have sections. - this.displayRefresher = CoreCourseFormatDelegate.instance.displayRefresher(this.course, this.sections); + this.displayRefresher = CoreCourseFormatDelegate.displayRefresher(this.course, this.sections); } /** @@ -292,7 +292,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ protected async loadMenuHandlers(refresh?: boolean): Promise { - this.courseMenuHandlers = await CoreCourseOptionsDelegate.instance.getMenuHandlersToDisplay(this.course, refresh); + this.courseMenuHandlers = await CoreCourseOptionsDelegate.getMenuHandlersToDisplay(this.course, refresh); } /** @@ -303,23 +303,23 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { protected async loadCourseFormatOptions(): Promise { // Load the course format options when course completion is enabled to show completion progress on sections. - if (!this.course.enablecompletion || !CoreCourses.instance.isGetCoursesByFieldAvailable()) { + if (!this.course.enablecompletion || !CoreCourses.isGetCoursesByFieldAvailable()) { return; } if ('courseformatoptions' in this.course && this.course.courseformatoptions) { // Already loaded. - this.formatOptions = CoreUtils.instance.objectToKeyValueMap(this.course.courseformatoptions, 'name', 'value'); + this.formatOptions = CoreUtils.objectToKeyValueMap(this.course.courseformatoptions, 'name', 'value'); return; } - const course = await CoreUtils.instance.ignoreErrors(CoreCourses.instance.getCourseByField('id', this.course.id)); + const course = await CoreUtils.ignoreErrors(CoreCourses.getCourseByField('id', this.course.id)); course && Object.assign(this.course, course); if (course?.courseformatoptions) { - this.formatOptions = CoreUtils.instance.objectToKeyValueMap(course.courseformatoptions, 'name', 'value'); + this.formatOptions = CoreUtils.objectToKeyValueMap(course.courseformatoptions, 'name', 'value'); } } @@ -330,7 +330,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ async doRefresh(refresher?: CustomEvent): Promise { - await CoreUtils.instance.ignoreErrors(this.invalidateData()); + await CoreUtils.ignoreErrors(this.invalidateData()); try { await this.loadData(true, true); @@ -338,7 +338,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { // Do not call doRefresh on the format component if the refresher is defined in the format component // to prevent an inifinite loop. if (this.displayRefresher && this.formatComponent) { - await CoreUtils.instance.ignoreErrors(this.formatComponent.doRefresh(refresher)); + await CoreUtils.ignoreErrors(this.formatComponent.doRefresh(refresher)); } refresher?.detail.complete(); @@ -358,7 +358,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { return; } - await CoreUtils.instance.ignoreErrors(this.invalidateData()); + await CoreUtils.ignoreErrors(this.invalidateData()); await this.refreshAfterCompletionChange(true); } @@ -371,12 +371,12 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { protected async invalidateData(): Promise { const promises: Promise[] = []; - promises.push(CoreCourse.instance.invalidateSections(this.course.id)); - promises.push(CoreCourses.instance.invalidateUserCourses()); - promises.push(CoreCourseFormatDelegate.instance.invalidateData(this.course, this.sections || [])); + promises.push(CoreCourse.invalidateSections(this.course.id)); + promises.push(CoreCourses.invalidateUserCourses()); + promises.push(CoreCourseFormatDelegate.invalidateData(this.course, this.sections || [])); if (this.sections) { - promises.push(CoreCourseModulePrefetchDelegate.instance.invalidateCourseUpdates(this.course.id)); + promises.push(CoreCourseModulePrefetchDelegate.invalidateCourseUpdates(this.course.id)); } await Promise.all(promises); @@ -417,7 +417,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ protected async determineCoursePrefetchIcon(): Promise { - this.prefetchCourseData = await CoreCourseHelper.instance.getCourseStatusIconAndTitle(this.course.id); + this.prefetchCourseData = await CoreCourseHelper.getCourseStatusIconAndTitle(this.course.id); } /** @@ -425,7 +425,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { */ async prefetchCourse(): Promise { try { - await CoreCourseHelper.instance.confirmAndPrefetchCourse( + await CoreCourseHelper.confirmAndPrefetchCourse( this.prefetchCourseData, this.course, this.sections, @@ -437,7 +437,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { return; } - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); } } @@ -455,14 +455,14 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { * @param status Status to show. */ protected updateCourseStatus(status: string): void { - this.prefetchCourseData = CoreCourseHelper.instance.getCourseStatusIconAndTitleFromStatus(status); + this.prefetchCourseData = CoreCourseHelper.getCourseStatusIconAndTitleFromStatus(status); } /** * Open the course summary */ openCourseSummary(): void { - CoreNavigator.instance.navigateToSitePath('/courses/preview', { params: { course: this.course, avoidOpenCourse: true } }); + CoreNavigator.navigateToSitePath('/courses/preview', { params: { course: this.course, avoidOpenCourse: true } }); } /** @@ -472,7 +472,7 @@ export class CoreCourseContentsPage implements OnInit, OnDestroy { */ openMenuItem(item: CoreCourseOptionsMenuHandlerToDisplay): void { const params = Object.assign({ course: this.course }, item.data.pageParams); - CoreNavigator.instance.navigateToSitePath(item.data.page, { params }); + CoreNavigator.navigateToSitePath(item.data.page, { params }); } /** diff --git a/src/core/features/course/pages/index/index.ts b/src/core/features/course/pages/index/index.ts index 3723a5360..87062e459 100644 --- a/src/core/features/course/pages/index/index.ts +++ b/src/core/features/course/pages/index/index.ts @@ -79,22 +79,22 @@ export class CoreCourseIndexPage implements OnInit, OnDestroy { */ async ngOnInit(): Promise { // Get params. - this.course = CoreNavigator.instance.getRouteParam('course'); - this.firstTabName = CoreNavigator.instance.getRouteParam('selectedTab'); - const module = CoreNavigator.instance.getRouteParam('module'); - const modParams = CoreNavigator.instance.getRouteParam('modParams'); + this.course = CoreNavigator.getRouteParam('course'); + this.firstTabName = CoreNavigator.getRouteParam('selectedTab'); + const module = CoreNavigator.getRouteParam('module'); + const modParams = CoreNavigator.getRouteParam('modParams'); - this.currentPagePath = CoreNavigator.instance.getCurrentPath(); - this.contentsTab.page = CoreTextUtils.instance.concatenatePaths(this.currentPagePath, this.contentsTab.page); + this.currentPagePath = CoreNavigator.getCurrentPath(); + this.contentsTab.page = CoreTextUtils.concatenatePaths(this.currentPagePath, this.contentsTab.page); this.contentsTab.pageParams = { course: this.course, - sectionId: CoreNavigator.instance.getRouteNumberParam('sectionId'), - sectionNumber: CoreNavigator.instance.getRouteNumberParam('sectionNumber'), + sectionId: CoreNavigator.getRouteNumberParam('sectionId'), + sectionNumber: CoreNavigator.getRouteNumberParam('sectionNumber'), }; if (module) { this.contentsTab.pageParams!.moduleId = module.id; - CoreCourseHelper.instance.openModule(module, this.course!.id, this.contentsTab.pageParams!.sectionId, modParams); + CoreCourseHelper.openModule(module, this.course!.id, this.contentsTab.pageParams!.sectionId, modParams); } this.tabs.push(this.contentsTab); @@ -113,7 +113,7 @@ export class CoreCourseIndexPage implements OnInit, OnDestroy { */ protected async loadCourseHandlers(): Promise { // Load the course handlers. - const handlers = await CoreCourseOptionsDelegate.instance.getHandlersToDisplay(this.course!, false, false); + const handlers = await CoreCourseOptionsDelegate.getHandlersToDisplay(this.course!, false, false); this.tabs = [...this.tabs, ...handlers.map(handler => handler.data)]; @@ -121,7 +121,7 @@ export class CoreCourseIndexPage implements OnInit, OnDestroy { // Add the courseId to the handler component data. handlers.forEach((handler, index) => { - handler.data.page = CoreTextUtils.instance.concatenatePaths(this.currentPagePath, handler.data.page); + handler.data.page = CoreTextUtils.concatenatePaths(this.currentPagePath, handler.data.page); handler.data.pageParams = handler.data.pageParams || {}; handler.data.pageParams.courseId = this.course!.id; @@ -147,17 +147,17 @@ export class CoreCourseIndexPage implements OnInit, OnDestroy { */ protected async loadTitle(): Promise { // Get the title to display initially. - this.title = CoreCourseFormatDelegate.instance.getCourseTitle(this.course!); + this.title = CoreCourseFormatDelegate.getCourseTitle(this.course!); // Load sections. - const sections = await CoreUtils.instance.ignoreErrors(CoreCourse.instance.getSections(this.course!.id, false, true)); + const sections = await CoreUtils.ignoreErrors(CoreCourse.getSections(this.course!.id, false, true)); if (!sections) { return; } // Get the title again now that we have sections. - this.title = CoreCourseFormatDelegate.instance.getCourseTitle(this.course!, sections); + this.title = CoreCourseFormatDelegate.getCourseTitle(this.course!, sections); } /** diff --git a/src/core/features/course/pages/list-mod-type/list-mod-type.ts b/src/core/features/course/pages/list-mod-type/list-mod-type.ts index 319b75b38..f4dd7492a 100644 --- a/src/core/features/course/pages/list-mod-type/list-mod-type.ts +++ b/src/core/features/course/pages/list-mod-type/list-mod-type.ts @@ -46,10 +46,10 @@ export class CoreCourseListModTypePage implements OnInit { * @inheritdoc */ async ngOnInit(): Promise { - this.title = CoreNavigator.instance.getRouteParam('title') || ''; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId'); - this.modName = CoreNavigator.instance.getRouteParam('modName'); - this.downloadEnabled = !CoreSites.instance.getCurrentSite()?.isOfflineDisabled(); + this.title = CoreNavigator.getRouteParam('title') || ''; + this.courseId = CoreNavigator.getRouteNumberParam('courseId'); + this.modName = CoreNavigator.getRouteParam('modName'); + this.downloadEnabled = !CoreSites.getCurrentSite()?.isOfflineDisabled(); try { await this.fetchData(); @@ -70,7 +70,7 @@ export class CoreCourseListModTypePage implements OnInit { try { // Get all the modules in the course. - let sections = await CoreCourse.instance.getSections(this.courseId, false, true); + let sections = await CoreCourse.getSections(this.courseId, false, true); sections = sections.filter((section) => { if (!section.modules) { @@ -78,7 +78,7 @@ export class CoreCourseListModTypePage implements OnInit { } section.modules = section.modules.filter((mod) => { - if (mod.uservisible === false || !CoreCourse.instance.moduleHasView(mod)) { + if (mod.uservisible === false || !CoreCourse.moduleHasView(mod)) { // Ignore this module. return false; } @@ -86,7 +86,7 @@ export class CoreCourseListModTypePage implements OnInit { if (this.modName === 'resources') { // Check that the module is a resource. if (typeof this.archetypes[mod.modname] == 'undefined') { - this.archetypes[mod.modname] = CoreCourseModuleDelegate.instance.supportsFeature( + this.archetypes[mod.modname] = CoreCourseModuleDelegate.supportsFeature( mod.modname, CoreConstants.FEATURE_MOD_ARCHETYPE, CoreConstants.MOD_ARCHETYPE_OTHER, @@ -105,11 +105,11 @@ export class CoreCourseListModTypePage implements OnInit { return section.modules.length > 0; }); - const result = CoreCourseHelper.instance.addHandlerDataForModules(sections, this.courseId); + const result = CoreCourseHelper.addHandlerDataForModules(sections, this.courseId); this.sections = result.sections; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting data'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting data'); } } @@ -120,7 +120,7 @@ export class CoreCourseListModTypePage implements OnInit { * @return Promise resolved when done. */ async refreshData(refresher: CustomEvent): Promise { - await CoreUtils.instance.ignoreErrors(CoreCourse.instance.invalidateSections(this.courseId || 0)); + await CoreUtils.ignoreErrors(CoreCourse.invalidateSections(this.courseId || 0)); try { await this.fetchData(); diff --git a/src/core/features/course/pages/unsupported-module/unsupported-module.ts b/src/core/features/course/pages/unsupported-module/unsupported-module.ts index 92c489dc4..78bb28a44 100644 --- a/src/core/features/course/pages/unsupported-module/unsupported-module.ts +++ b/src/core/features/course/pages/unsupported-module/unsupported-module.ts @@ -35,15 +35,15 @@ export class CoreCourseUnsupportedModulePage implements OnInit { * @inheritDoc */ ngOnInit(): void { - this.module = CoreNavigator.instance.getRouteParam('module'); - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId'); + this.module = CoreNavigator.getRouteParam('module'); + this.courseId = CoreNavigator.getRouteNumberParam('courseId'); } /** * Expand the description. */ expandDescription(): void { - CoreTextUtils.instance.viewText(Translate.instance.instant('core.description'), this.module!.description!, { + CoreTextUtils.viewText(Translate.instant('core.description'), this.module!.description!, { filter: true, contextLevel: 'module', instanceId: this.module!.id, diff --git a/src/core/features/course/services/course-helper.ts b/src/core/features/course/services/course-helper.ts index ceeeaf0e3..70465dc51 100644 --- a/src/core/features/course/services/course-helper.ts +++ b/src/core/features/course/services/course-helper.ts @@ -186,7 +186,7 @@ export class CoreCourseHelperProvider { hasContent = true; section.modules.forEach((module) => { - module.handlerData = CoreCourseModuleDelegate.instance.getModuleDataFor( + module.handlerData = CoreCourseModuleDelegate.getModuleDataFor( module.modname, module, courseId, @@ -245,7 +245,7 @@ export class CoreCourseHelperProvider { const sectionWithStatus = section; // Get the status of this section. - const result = await CoreCourseModulePrefetchDelegate.instance.getModulesStatus( + const result = await CoreCourseModulePrefetchDelegate.getModulesStatus( section.modules, courseId, section.id, @@ -256,12 +256,12 @@ export class CoreCourseHelperProvider { // Check if it's being downloaded. const downloadId = this.getSectionDownloadId(section); - if (CoreCourseModulePrefetchDelegate.instance.isBeingDownloaded(downloadId)) { + if (CoreCourseModulePrefetchDelegate.isBeingDownloaded(downloadId)) { result.status = CoreConstants.DOWNLOADING; } sectionWithStatus.downloadStatus = result.status; - sectionWithStatus.canCheckUpdates = CoreCourseModulePrefetchDelegate.instance.canCheckUpdates(); + sectionWithStatus.canCheckUpdates = CoreCourseModulePrefetchDelegate.canCheckUpdates(); // Set this section data. if (result.status !== CoreConstants.DOWNLOADING) { @@ -270,7 +270,7 @@ export class CoreCourseHelperProvider { } else { // Section is being downloaded. sectionWithStatus.isDownloading = true; - CoreCourseModulePrefetchDelegate.instance.setOnProgress(downloadId, (data) => { + CoreCourseModulePrefetchDelegate.setOnProgress(downloadId, (data) => { sectionWithStatus.count = data.count; sectionWithStatus.total = data.total; }); @@ -311,7 +311,7 @@ export class CoreCourseHelperProvider { const result = await this.calculateSectionStatus(section, courseId, refresh, checkUpdates); // Calculate "All sections" status. - allSectionsStatus = CoreFilepool.instance.determinePackagesStatus(allSectionsStatus, result.statusData.status); + allSectionsStatus = CoreFilepool.determinePackagesStatus(allSectionsStatus, result.statusData.status); } finally { section.isCalculating = false; } @@ -323,7 +323,7 @@ export class CoreCourseHelperProvider { if (allSectionsSection) { // Set "All sections" data. allSectionsSection.downloadStatus = allSectionsStatus; - allSectionsSection.canCheckUpdates = CoreCourseModulePrefetchDelegate.instance.canCheckUpdates(); + allSectionsSection.canCheckUpdates = CoreCourseModulePrefetchDelegate.canCheckUpdates(); allSectionsSection.isDownloading = allSectionsStatus === CoreConstants.DOWNLOADING; } @@ -356,7 +356,7 @@ export class CoreCourseHelperProvider { ): Promise { const initialIcon = data.icon; const initialStatus = data.statusTranslatable; - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); data.downloadSucceeded = false; data.icon = CoreConstants.ICON_DOWNLOADING; @@ -364,7 +364,7 @@ export class CoreCourseHelperProvider { // Get the sections first if needed. if (!sections) { - sections = await CoreCourse.instance.getSections(course.id, false, true); + sections = await CoreCourse.getSections(course.id, false, true); } try { @@ -380,10 +380,10 @@ export class CoreCourseHelperProvider { // User confirmed, get the course handlers if needed. if (!courseHandlers) { - courseHandlers = await CoreCourseOptionsDelegate.instance.getHandlersToDisplay(course); + courseHandlers = await CoreCourseOptionsDelegate.getHandlersToDisplay(course); } if (!menuHandlers) { - menuHandlers = await CoreCourseOptionsDelegate.instance.getMenuHandlersToDisplay(course); + menuHandlers = await CoreCourseOptionsDelegate.getMenuHandlersToDisplay(course); } // Now we have all the data, download the course. @@ -404,10 +404,10 @@ export class CoreCourseHelperProvider { courses: CoreEnrolledCourseDataWithExtraInfoAndOptions[], onProgress?: (data: CoreCourseCoursesProgress) => void, ): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); // Confirm the download without checking size because it could take a while. - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.areyousure')); + await CoreDomUtils.showConfirm(Translate.instant('core.areyousure')); const total = courses.length; let count = 0; @@ -420,18 +420,18 @@ export class CoreCourseHelperProvider { let success = true; // Get the sections and the handlers. - subPromises.push(CoreCourse.instance.getSections(course.id, false, true).then((courseSections) => { + subPromises.push(CoreCourse.getSections(course.id, false, true).then((courseSections) => { sections = courseSections; return; })); - subPromises.push(CoreCourseOptionsDelegate.instance.getHandlersToDisplay(course).then((cHandlers) => { + subPromises.push(CoreCourseOptionsDelegate.getHandlersToDisplay(course).then((cHandlers) => { handlers = cHandlers; return; })); - subPromises.push(CoreCourseOptionsDelegate.instance.getMenuHandlersToDisplay(course).then((mHandlers) => { + subPromises.push(CoreCourseOptionsDelegate.getMenuHandlersToDisplay(course).then((mHandlers) => { menuHandlers = mHandlers; return; @@ -456,7 +456,7 @@ export class CoreCourseHelperProvider { onProgress({ count: 0, total: total, success: true }); } - return CoreUtils.instance.allPromises(promises); + return CoreUtils.allPromises(promises); } /** @@ -472,9 +472,9 @@ export class CoreCourseHelperProvider { try { - await CoreDomUtils.instance.showDeleteConfirm('core.course.confirmdeletestoreddata'); + await CoreDomUtils.showDeleteConfirm('core.course.confirmdeletestoreddata'); - modal = await CoreDomUtils.instance.showModalLoading(); + modal = await CoreDomUtils.showModalLoading(); await this.removeModuleStoredData(module, courseId); @@ -482,7 +482,7 @@ export class CoreCourseHelperProvider { } catch (error) { if (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } } finally { modal?.dismiss(); @@ -516,23 +516,23 @@ export class CoreCourseHelperProvider { // Calculate the size of the download. if (section && section.id != CoreCourseProvider.ALL_SECTIONS_ID) { - sizeSum = await CoreCourseModulePrefetchDelegate.instance.getDownloadSize(section.modules, courseId); + sizeSum = await CoreCourseModulePrefetchDelegate.getDownloadSize(section.modules, courseId); // Check if the section has embedded files in the description. - hasEmbeddedFiles = CoreFilepool.instance.extractDownloadableFilesFromHtml(section.summary).length > 0; + hasEmbeddedFiles = CoreFilepool.extractDownloadableFilesFromHtml(section.summary).length > 0; } else { await Promise.all(sections!.map(async (section) => { if (section.id == CoreCourseProvider.ALL_SECTIONS_ID) { return; } - const sectionSize = await CoreCourseModulePrefetchDelegate.instance.getDownloadSize(section.modules, courseId); + const sectionSize = await CoreCourseModulePrefetchDelegate.getDownloadSize(section.modules, courseId); sizeSum.total = sizeSum.total && sectionSize.total; sizeSum.size += sectionSize.size; // Check if the section has embedded files in the description. - if (!hasEmbeddedFiles && CoreFilepool.instance.extractDownloadableFilesFromHtml(section.summary).length > 0) { + if (!hasEmbeddedFiles && CoreFilepool.extractDownloadableFilesFromHtml(section.summary).length > 0) { hasEmbeddedFiles = true; } })); @@ -543,7 +543,7 @@ export class CoreCourseHelperProvider { } // Show confirm modal if needed. - await CoreDomUtils.instance.confirmDownloadSize(sizeSum, undefined, undefined, undefined, undefined, alwaysConfirm); + await CoreDomUtils.confirmDownloadSize(sizeSum, undefined, undefined, undefined, undefined, alwaysConfirm); } /** @@ -567,11 +567,11 @@ export class CoreCourseHelperProvider { try { // We need to call getDownloadSize, the package might have been updated. - const size = await CoreCourseModulePrefetchDelegate.instance.getModuleDownloadSize(module, courseId, true); + const size = await CoreCourseModulePrefetchDelegate.getModuleDownloadSize(module, courseId, true); - await CoreDomUtils.instance.confirmDownloadSize(size); + await CoreDomUtils.confirmDownloadSize(size); - await CoreCourseModulePrefetchDelegate.instance.prefetchModule(module, courseId, true); + await CoreCourseModulePrefetchDelegate.prefetchModule(module, courseId, true); // Success, close menu. done && done(); @@ -579,7 +579,7 @@ export class CoreCourseHelperProvider { instance.prefetchStatusIcon = initialIcon; if (!instance.isDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); } } } @@ -592,7 +592,7 @@ export class CoreCourseHelperProvider { createAllSectionsSection(): CoreCourseSection { return { id: CoreCourseProvider.ALL_SECTIONS_ID, - name: Translate.instance.instant('core.course.allsections'), + name: Translate.instant('core.course.allsections'), hasContent: true, summary: '', summaryformat: 1, @@ -609,10 +609,10 @@ export class CoreCourseHelperProvider { async determineCoursesStatus(courses: CoreCourseBasicData[]): Promise { // Get the status of each course. const promises: Promise[] = []; - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); courses.forEach((course) => { - promises.push(CoreCourse.instance.getCourseStatus(course.id, siteId)); + promises.push(CoreCourse.getCourseStatus(course.id, siteId)); }); const statuses = await Promise.all(promises); @@ -647,37 +647,37 @@ export class CoreCourseHelperProvider { files?: CoreCourseModuleContentFile[], siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!files || !files.length) { // Make sure that module contents are loaded. - await CoreCourse.instance.loadModuleContents(module, courseId); + await CoreCourse.loadModuleContents(module, courseId); files = module.contents; } if (!files || !files.length) { - throw new CoreError(Translate.instance.instant('core.filenotfound')); + throw new CoreError(Translate.instant('core.filenotfound')); } - if (!CoreFileHelper.instance.isOpenableInApp(module.contents[0])) { - await CoreFileHelper.instance.showConfirmOpenUnsupportedFile(); + if (!CoreFileHelper.isOpenableInApp(module.contents[0])) { + await CoreFileHelper.showConfirmOpenUnsupportedFile(); } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const mainFile = files[0]; // Check if the file should be opened in browser. - if (CoreFileHelper.instance.shouldOpenInBrowser(mainFile)) { + if (CoreFileHelper.shouldOpenInBrowser(mainFile)) { return this.openModuleFileInBrowser(mainFile.fileurl, site, module, courseId, component, componentId, files); } // File shouldn't be opened in browser. Download the module if it needs to be downloaded. const result = await this.downloadModuleWithMainFileIfNeeded(module, courseId, component || '', componentId, files, siteId); - if (CoreUrlUtils.instance.isLocalFileUrl(result.path)) { - return CoreUtils.instance.openFile(result.path); + if (CoreUrlUtils.isLocalFileUrl(result.path)) { + return CoreUtils.openFile(result.path); } /* In iOS, if we use the same URL in embedded browser and background download then the download only @@ -685,13 +685,13 @@ export class CoreCourseHelperProvider { result.path = result.path + '#moodlemobile-embedded'; try { - await CoreUtils.instance.openOnlineFile(result.path); + await CoreUtils.openOnlineFile(result.path); } catch (error) { // Error opening the file, some apps don't allow opening online files. - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw error; } else if (result.status === CoreConstants.DOWNLOADING) { - throw new CoreError(Translate.instance.instant('core.erroropenfiledownloading')); + throw new CoreError(Translate.instant('core.erroropenfiledownloading')); } let path: string | undefined; @@ -699,13 +699,13 @@ export class CoreCourseHelperProvider { // Not downloaded, download it now and return the local file. await this.downloadModule(module, courseId, component, componentId, files, siteId); - path = await CoreFilepool.instance.getInternalUrlByUrl(siteId, mainFile.fileurl); + path = await CoreFilepool.getInternalUrlByUrl(siteId, mainFile.fileurl); } else { // File is outdated or stale and can't be opened in online, return the local URL. - path = await CoreFilepool.instance.getInternalUrlByUrl(siteId, mainFile.fileurl); + path = await CoreFilepool.getInternalUrlByUrl(siteId, mainFile.fileurl); } - await CoreUtils.instance.openFile(path); + await CoreUtils.openFile(path); } } @@ -730,16 +730,16 @@ export class CoreCourseHelperProvider { componentId?: string | number, files?: CoreCourseModuleContentFile[], ): Promise { - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // Not online, get the offline file. It will fail if not found. let path: string | undefined; try { - path = await CoreFilepool.instance.getInternalUrlByUrl(site.getId(), fileUrl); + path = await CoreFilepool.getInternalUrlByUrl(site.getId(), fileUrl); } catch { throw new CoreNetworkError(); } - return CoreUtils.instance.openFile(path); + return CoreUtils.openFile(path); } // Open in browser. @@ -751,9 +751,9 @@ export class CoreCourseHelperProvider { // Remove forcedownload when not followed by any param. fixedUrl = fixedUrl.replace(/[?|&]forcedownload=\d+/, ''); - CoreUtils.instance.openInBrowser(fixedUrl); + CoreUtils.openInBrowser(fixedUrl); - if (CoreFile.instance.isAvailable()) { + if (CoreFile.isAvailable()) { // Download the file if needed (file outdated or not downloaded). // Download will be in background, don't return the promise. this.downloadModule(module, courseId, component, componentId, files, site.getId()); @@ -781,7 +781,7 @@ export class CoreCourseHelperProvider { siteId?: string, ): Promise<{ fixedUrl: string; path: string; status?: string }> { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!files || !files.length) { // Module not valid, stop. @@ -789,11 +789,11 @@ export class CoreCourseHelperProvider { } const mainFile = files[0]; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const fixedUrl = await site.checkAndFixPluginfileURL(mainFile.fileurl); - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { return { path: fixedUrl, // Use the online URL. fixedUrl, @@ -801,7 +801,7 @@ export class CoreCourseHelperProvider { } // The file system is available. - const status = await CoreFilepool.instance.getPackageStatus(siteId, component, componentId); + const status = await CoreFilepool.getPackageStatus(siteId, component, componentId); let path = ''; @@ -811,10 +811,10 @@ export class CoreCourseHelperProvider { } else if (status === CoreConstants.DOWNLOADED) { try { // Get the local file URL. - path = await CoreFilepool.instance.getInternalUrlByUrl(siteId, mainFile.fileurl); + path = await CoreFilepool.getInternalUrlByUrl(siteId, mainFile.fileurl); } catch (error){ // File not found, mark the module as not downloaded. - await CoreFilepool.instance.storePackageStatus(siteId, CoreConstants.NOT_DOWNLOADED, component, componentId); + await CoreFilepool.storePackageStatus(siteId, CoreConstants.NOT_DOWNLOADED, component, componentId); } } @@ -853,9 +853,9 @@ export class CoreCourseHelperProvider { componentId?: string | number, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const isOnline = CoreApp.instance.isOnline(); + const isOnline = CoreApp.isOnline(); const mainFile = files[0]; const timemodified = mainFile.timemodified || 0; @@ -864,26 +864,26 @@ export class CoreCourseHelperProvider { throw new CoreNetworkError(); } - const shouldDownloadFirst = await CoreFilepool.instance.shouldDownloadFileBeforeOpen(fixedUrl, mainFile.filesize); + const shouldDownloadFirst = await CoreFilepool.shouldDownloadFileBeforeOpen(fixedUrl, mainFile.filesize); if (shouldDownloadFirst) { // Download and then return the local URL. await this.downloadModule(module, courseId, component, componentId, files, siteId); - return CoreFilepool.instance.getInternalUrlByUrl(siteId, mainFile.fileurl); + return CoreFilepool.getInternalUrlByUrl(siteId, mainFile.fileurl); } // Start the download if in wifi, but return the URL right away so the file is opened. - if (CoreApp.instance.isWifi()) { + if (CoreApp.isWifi()) { this.downloadModule(module, courseId, component, componentId, files, siteId); } - if (!CoreFileHelper.instance.isStateDownloaded(status) || isOnline) { + if (!CoreFileHelper.isStateDownloaded(status) || isOnline) { // Not downloaded or online, return the online URL. return fixedUrl; } else { // Outdated but offline, so we return the local URL. Use getUrlByUrl so it's added to the queue. - return CoreFilepool.instance.getUrlByUrl( + return CoreFilepool.getUrlByUrl( siteId, mainFile.fileurl, component, @@ -915,9 +915,9 @@ export class CoreCourseHelperProvider { files?: CoreCourseModuleContentFile[], siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const prefetchHandler = CoreCourseModulePrefetchDelegate.instance.getPrefetchHandlerFor(module); + const prefetchHandler = CoreCourseModulePrefetchDelegate.getPrefetchHandlerFor(module); if (prefetchHandler) { // Use the prefetch handler to download the module. @@ -931,7 +931,7 @@ export class CoreCourseHelperProvider { // There's no prefetch handler for the module, just download the files. files = files || module.contents; - await CoreFilepool.instance.downloadOrPrefetchFiles(siteId, files, false, false, component, componentId); + await CoreFilepool.downloadOrPrefetchFiles(siteId, files, false, false, component, componentId); } /** @@ -951,7 +951,7 @@ export class CoreCourseHelperProvider { invalidateCache?: boolean, component?: string, ): Promise { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); const moduleInfo = await this.getModulePrefetchInfo(module, courseId, invalidateCache, component); @@ -962,10 +962,10 @@ export class CoreCourseHelperProvider { if (moduleInfo.status != CoreConstants.NOT_DOWNLOADABLE) { // Module is downloadable, get the text to display to prefetch. if (moduleInfo.downloadTime && moduleInfo.downloadTime > 0) { - instance.prefetchText = Translate.instance.instant('core.lastdownloaded') + ': ' + moduleInfo.downloadTimeReadable; + instance.prefetchText = Translate.instant('core.lastdownloaded') + ': ' + moduleInfo.downloadTimeReadable; } else { // Module not downloaded, show a default text. - instance.prefetchText = Translate.instance.instant('core.download'); + instance.prefetchText = Translate.instant('core.download'); } } @@ -988,10 +988,10 @@ export class CoreCourseHelperProvider { if (!instance.contextFileStatusObserver && component) { // Debounce the update size function to prevent too many calls when downloading or deleting a whole activity. - const debouncedUpdateSize = CoreUtils.instance.debounce(async () => { - const moduleSize = await CoreCourseModulePrefetchDelegate.instance.getModuleStoredSize(module, courseId); + const debouncedUpdateSize = CoreUtils.debounce(async () => { + const moduleSize = await CoreCourseModulePrefetchDelegate.getModuleStoredSize(module, courseId); - instance.size = moduleSize > 0 ? CoreTextUtils.instance.bytesToSize(moduleSize, 2) : ''; + instance.size = moduleSize > 0 ? CoreTextUtils.bytesToSize(moduleSize, 2) : ''; }, 1000); instance.contextFileStatusObserver = CoreEvents.on( @@ -1002,7 +1002,7 @@ export class CoreCourseHelperProvider { return; } - if (!CoreFilepool.instance.isFileEventDownloadedOrDeleted(data)) { + if (!CoreFilepool.isFileEventDownloadedOrDeleted(data)) { return; } @@ -1025,25 +1025,25 @@ export class CoreCourseHelperProvider { courseId: number, siteId?: string, ): Promise<{ enrolled: boolean; course: CoreCourseAnyCourseData }> { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); let course: CoreCourseAnyCourseData; // Try with enrolled courses first. try { - course = await CoreCourses.instance.getUserCourse(courseId, false, siteId); + course = await CoreCourses.getUserCourse(courseId, false, siteId); return ({ enrolled: true, course: course }); } catch { // Not enrolled or an error happened. Try to use another WebService. } - const available = await CoreCourses.instance.isGetCoursesByFieldAvailableInSite(siteId); + const available = await CoreCourses.isGetCoursesByFieldAvailableInSite(siteId); if (available) { - course = await CoreCourses.instance.getCourseByField('id', courseId, siteId); + course = await CoreCourses.getCourseByField('id', courseId, siteId); } else { - course = await CoreCourses.instance.getCourse(courseId, siteId); + course = await CoreCourses.getCourse(courseId, siteId); } return ({ enrolled: false, course: course }); @@ -1059,7 +1059,7 @@ export class CoreCourseHelperProvider { * @return Promise resolved when done. */ async getAndOpenCourse(courseId: number, params?: Params, siteId?: string): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); let course: CoreCourseAnyCourseData | { id: number }; @@ -1088,7 +1088,7 @@ export class CoreCourseHelperProvider { */ async hasABlockNamed(courseId: number, name: string, siteId?: string): Promise { try { - const blocks = await CoreCourse.instance.getCourseBlocks(courseId, siteId); + const blocks = await CoreCourse.getCourseBlocks(courseId, siteId); return blocks.some((block) => block.name == name); } catch { @@ -1138,7 +1138,7 @@ export class CoreCourseHelperProvider { * @return Promise resolved when done. */ async loadOfflineCompletion(courseId: number, sections: CoreCourseSection[], siteId?: string): Promise { - const offlineCompletions = await CoreCourseOffline.instance.getCourseManualCompletions(courseId, siteId); + const offlineCompletions = await CoreCourseOffline.getCourseManualCompletions(courseId, siteId); if (!offlineCompletions || !offlineCompletions.length) { // No offline completion. @@ -1147,7 +1147,7 @@ export class CoreCourseHelperProvider { const totalOffline = offlineCompletions.length; let loaded = 0; - const offlineCompletionsMap = CoreUtils.instance.arrayToObject(offlineCompletions, 'cmid'); + const offlineCompletionsMap = CoreUtils.arrayToObject(offlineCompletions, 'cmid'); // Load the offline data in the modules. for (let i = 0; i < sections.length; i++) { const section = sections[i]; @@ -1210,7 +1210,7 @@ export class CoreCourseHelperProvider { * @return Download promise, undefined if not found. */ getCourseDownloadPromise(courseId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); return this.courseDwnPromises[siteId] && this.courseDwnPromises[siteId][courseId]; } @@ -1223,7 +1223,7 @@ export class CoreCourseHelperProvider { * @return Promise resolved with the icon name and the title key. */ async getCourseStatusIconAndTitle(courseId: number, siteId?: string): Promise { - const status = await CoreCourse.instance.getCourseStatus(courseId, siteId); + const status = await CoreCourse.getCourseStatus(courseId, siteId); return this.getCourseStatusIconAndTitleFromStatus(status); } @@ -1289,11 +1289,11 @@ export class CoreCourseHelperProvider { */ async getModuleCourseIdByInstance(id: number, module: string, siteId?: string): Promise { try { - const cm = await CoreCourse.instance.getModuleBasicInfoByInstance(id, module, siteId); + const cm = await CoreCourse.getModuleBasicInfoByInstance(id, module, siteId); return cm.course; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errorgetmodule', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); throw error; } @@ -1315,21 +1315,21 @@ export class CoreCourseHelperProvider { component?: string, ): Promise { const moduleInfo: CoreCourseModulePrefetchInfo = {}; - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); if (invalidateCache) { - CoreCourseModulePrefetchDelegate.instance.invalidateModuleStatusCache(module); + CoreCourseModulePrefetchDelegate.invalidateModuleStatusCache(module); } const results = await Promise.all([ - CoreCourseModulePrefetchDelegate.instance.getModuleStoredSize(module, courseId), - CoreCourseModulePrefetchDelegate.instance.getModuleStatus(module, courseId), - CoreUtils.instance.ignoreErrors(CoreFilepool.instance.getPackageData(siteId, component || '', module.id)), + CoreCourseModulePrefetchDelegate.getModuleStoredSize(module, courseId), + CoreCourseModulePrefetchDelegate.getModuleStatus(module, courseId), + CoreUtils.ignoreErrors(CoreFilepool.getPackageData(siteId, component || '', module.id)), ]); // Treat stored size. moduleInfo.size = results[0]; - moduleInfo.sizeReadable = CoreTextUtils.instance.bytesToSize(results[0], 2); + moduleInfo.sizeReadable = CoreTextUtils.bytesToSize(results[0], 2); // Treat module status. moduleInfo.status = results[1]; @@ -1344,7 +1344,7 @@ export class CoreCourseHelperProvider { moduleInfo.statusIcon = CoreConstants.ICON_OUTDATED; break; case CoreConstants.DOWNLOADED: - if (!CoreCourseModulePrefetchDelegate.instance.canCheckUpdates()) { + if (!CoreCourseModulePrefetchDelegate.canCheckUpdates()) { moduleInfo.statusIcon = CoreConstants.ICON_OUTDATED; } break; @@ -1354,14 +1354,14 @@ export class CoreCourseHelperProvider { } // Treat download time. - if (!results[2] || !results[2].downloadTime || !CoreFileHelper.instance.isStateDownloaded(results[2].status || '')) { + if (!results[2] || !results[2].downloadTime || !CoreFileHelper.isStateDownloaded(results[2].status || '')) { // Not downloaded. moduleInfo.downloadTime = 0; return moduleInfo; } - const now = CoreTimeUtils.instance.timestamp(); + const now = CoreTimeUtils.timestamp(); moduleInfo.downloadTime = results[2].downloadTime; if (now - results[2].downloadTime < 7 * 86400) { moduleInfo.downloadTimeReadable = moment(results[2].downloadTime * 1000).fromNow(); @@ -1405,10 +1405,10 @@ export class CoreCourseHelperProvider { modParams?: Params, ): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { - const module = await CoreCourse.instance.getModuleBasicInfoByInstance(instanceId, modName, siteId); + const module = await CoreCourse.getModuleBasicInfoByInstance(instanceId, modName, siteId); this.navigateToModule( module.id, @@ -1419,7 +1419,7 @@ export class CoreCourseHelperProvider { modParams, ); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errorgetmodule', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); } finally { // Just in case. In fact we need to dismiss the modal before showing a toast or error message. modal.dismiss(); @@ -1446,32 +1446,32 @@ export class CoreCourseHelperProvider { modName?: string, modParams?: Params, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { if (!courseId) { // We don't have courseId. - const module = await CoreCourse.instance.getModuleBasicInfo(moduleId, siteId); + const module = await CoreCourse.getModuleBasicInfo(moduleId, siteId); courseId = module.course; sectionId = module.section; } else if (!sectionId) { // We don't have sectionId but we have courseId. - sectionId = await CoreCourse.instance.getModuleSectionId(moduleId, siteId); + sectionId = await CoreCourse.getModuleSectionId(moduleId, siteId); } // Get the site. - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Get the module. const module = - await CoreCourse.instance.getModule(moduleId, courseId, sectionId, false, false, siteId, modName); + await CoreCourse.getModule(moduleId, courseId, sectionId, false, false, siteId, modName); - if (CoreSites.instance.getCurrentSiteId() == site.getId()) { + if (CoreSites.getCurrentSiteId() == site.getId()) { // Try to use the module's handler to navigate cleanly. - module.handlerData = CoreCourseModuleDelegate.instance.getModuleDataFor( + module.handlerData = CoreCourseModuleDelegate.getModuleDataFor( module.modname, module, courseId, @@ -1497,10 +1497,10 @@ export class CoreCourseHelperProvider { if (courseId == site.getSiteHomeId()) { // Check if site home is available. - const isAvailable = await CoreSiteHome.instance.isAvailable(); + const isAvailable = await CoreSiteHome.isAvailable(); if (isAvailable) { - await CoreNavigator.instance.navigateToSitePath(CoreSiteHomeHomeHandlerService.PAGE_NAME, { params, siteId }); + await CoreNavigator.navigateToSitePath(CoreSiteHomeHomeHandlerService.PAGE_NAME, { params, siteId }); return; } @@ -1510,7 +1510,7 @@ export class CoreCourseHelperProvider { await this.getAndOpenCourse(courseId, params, siteId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errorgetmodule', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); } finally { modal.dismiss(); } @@ -1527,7 +1527,7 @@ export class CoreCourseHelperProvider { */ openModule(module: CoreCourseModule, courseId: number, sectionId?: number, modParams?: Params): boolean { if (!module.handlerData) { - module.handlerData = CoreCourseModuleDelegate.instance.getModuleDataFor( + module.handlerData = CoreCourseModuleDelegate.getModuleDataFor( module.modname, module, courseId, @@ -1562,7 +1562,7 @@ export class CoreCourseHelperProvider { courseMenuHandlers: CoreCourseOptionsMenuHandlerToDisplay[], siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.courseDwnPromises[siteId] && this.courseDwnPromises[siteId][course.id]) { // There's already a download ongoing for this course, return the promise. @@ -1572,7 +1572,7 @@ export class CoreCourseHelperProvider { } // First of all, mark the course as being downloaded. - this.courseDwnPromises[siteId][course.id] = CoreCourse.instance.setCourseStatus( + this.courseDwnPromises[siteId][course.id] = CoreCourse.setCourseStatus( course.id, CoreConstants.DOWNLOADING, siteId, @@ -1600,24 +1600,24 @@ export class CoreCourseHelperProvider { }); // Prefetch other data needed to render the course. - if (CoreCourses.instance.isGetCoursesByFieldAvailable()) { - promises.push(CoreCourses.instance.getCoursesByField('id', course.id)); + if (CoreCourses.isGetCoursesByFieldAvailable()) { + promises.push(CoreCourses.getCoursesByField('id', course.id)); } const sectionWithModules = sections.find((section) => section.modules && section.modules.length > 0); if (!sectionWithModules || typeof sectionWithModules.modules[0].completion == 'undefined') { - promises.push(CoreCourse.instance.getActivitiesCompletionStatus(course.id)); + promises.push(CoreCourse.getActivitiesCompletionStatus(course.id)); } - promises.push(CoreFilterHelper.instance.getFilters('course', course.id)); + promises.push(CoreFilterHelper.getFilters('course', course.id)); - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); // Download success, mark the course as downloaded. - return CoreCourse.instance.setCourseStatus(course.id, CoreConstants.DOWNLOADED, siteId); + return CoreCourse.setCourseStatus(course.id, CoreConstants.DOWNLOADED, siteId); }).catch(async (error) => { // Error, restore previous status. - await CoreCourse.instance.setCoursePreviousStatus(course.id, siteId); + await CoreCourse.setCoursePreviousStatus(course.id, siteId); throw error; }).finally(() => { @@ -1646,14 +1646,14 @@ export class CoreCourseHelperProvider { refresh?: boolean, ): Promise { // Show confirmation if needed. - await CoreDomUtils.instance.confirmDownloadSize(size); + await CoreDomUtils.confirmDownloadSize(size); // Invalidate content if refreshing and download the data. if (refresh) { - await CoreUtils.instance.ignoreErrors(handler.invalidateContent(module.id, courseId)); + await CoreUtils.ignoreErrors(handler.invalidateContent(module.id, courseId)); } - await CoreCourseModulePrefetchDelegate.instance.prefetchModule(module, courseId, true); + await CoreCourseModulePrefetchDelegate.prefetchModule(module, courseId, true); } /** @@ -1702,16 +1702,16 @@ export class CoreCourseHelperProvider { const result = await this.calculateSectionStatus(section, courseId, false, false); // Calculate "All sections" status. - allSectionsStatus = CoreFilepool.instance.determinePackagesStatus(allSectionsStatus, result.statusData.status); + allSectionsStatus = CoreFilepool.determinePackagesStatus(allSectionsStatus, result.statusData.status); } }); try { - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); // Set "All sections" data. section.downloadStatus = allSectionsStatus; - section.canCheckUpdates = CoreCourseModulePrefetchDelegate.instance.canCheckUpdates(); + section.canCheckUpdates = CoreCourseModulePrefetchDelegate.canCheckUpdates(); section.isDownloading = allSectionsStatus === CoreConstants.DOWNLOADING; } finally { section.isDownloading = false; @@ -1732,7 +1732,7 @@ export class CoreCourseHelperProvider { } const promises: Promise[] = []; - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); section.isDownloading = true; @@ -1740,9 +1740,9 @@ export class CoreCourseHelperProvider { promises.push(this.syncModulesAndPrefetchSection(section, courseId)); // Download the files in the section description. - const introFiles = CoreFilepool.instance.extractDownloadableFilesFromHtmlAsFakeFileObjects(section.summary); - promises.push(CoreUtils.instance.ignoreErrors( - CoreFilepool.instance.addFilesToQueue(siteId, introFiles, CoreCourseProvider.COMPONENT, courseId), + const introFiles = CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(section.summary); + promises.push(CoreUtils.ignoreErrors( + CoreFilepool.addFilesToQueue(siteId, introFiles, CoreCourseProvider.COMPONENT, courseId), )); try { @@ -1761,10 +1761,10 @@ export class CoreCourseHelperProvider { */ protected async syncModulesAndPrefetchSection(section: CoreCourseSectionWithStatus, courseId: number): Promise { // Sync the modules first. - await CoreCourseModulePrefetchDelegate.instance.syncModules(section.modules, courseId); + await CoreCourseModulePrefetchDelegate.syncModules(section.modules, courseId); // Validate the section needs to be downloaded and calculate amount of modules that need to be downloaded. - const result = await CoreCourseModulePrefetchDelegate.instance.getModulesStatus(section.modules, courseId, section.id); + const result = await CoreCourseModulePrefetchDelegate.getModulesStatus(section.modules, courseId, section.id); if (result.status == CoreConstants.DOWNLOADED || result.status == CoreConstants.NOT_DOWNLOADABLE) { // Section is downloaded or not downloadable, nothing to do. @@ -1805,7 +1805,7 @@ export class CoreCourseHelperProvider { section.isDownloading = true; // Prefetch all modules to prevent incoeherences in download count and to download stale data not marked as outdated. - await CoreCourseModulePrefetchDelegate.instance.prefetchModules(downloadId, modules, courseId, (data) => { + await CoreCourseModulePrefetchDelegate.prefetchModules(downloadId, modules, courseId, (data) => { section.count = data.count; section.total = data.total; }); @@ -1840,15 +1840,15 @@ export class CoreCourseHelperProvider { * @return Promise resolved when done. */ async openCourse(course: CoreCourseAnyCourseData | { id: number }, params?: Params, siteId?: string): Promise { - if (!siteId || siteId == CoreSites.instance.getCurrentSiteId()) { + if (!siteId || siteId == CoreSites.getCurrentSiteId()) { // Current site, we can open the course. - return CoreCourse.instance.openCourse(course, params); + return CoreCourse.openCourse(course, params); } else { // We need to load the site first. params = params || {}; Object.assign(params, { course: course }); - await CoreNavigator.instance.navigateToSitePath('course', { siteId, params }); + await CoreNavigator.navigateToSitePath('course', { siteId, params }); } } @@ -1859,14 +1859,14 @@ export class CoreCourseHelperProvider { * @return Promise to be resolved once the course files are deleted. */ async deleteCourseFiles(courseId: number): Promise { - const sections = await CoreCourse.instance.getSections(courseId); + const sections = await CoreCourse.getSections(courseId); const modules = CoreArray.flatten(sections.map((section) => section.modules)); await Promise.all( modules.map((module) => this.removeModuleStoredData(module, courseId)), ); - await CoreCourse.instance.setCourseStatus(courseId, CoreConstants.NOT_DOWNLOADED); + await CoreCourse.setCourseStatus(courseId, CoreConstants.NOT_DOWNLOADED); } /** @@ -1879,10 +1879,10 @@ export class CoreCourseHelperProvider { async removeModuleStoredData(module: CoreCourseWSModule, courseId: number): Promise { const promises: Promise[] = []; - promises.push(CoreCourseModulePrefetchDelegate.instance.removeModuleFiles(module, courseId)); + promises.push(CoreCourseModulePrefetchDelegate.removeModuleFiles(module, courseId)); - const handler = CoreCourseModulePrefetchDelegate.instance.getPrefetchHandlerFor(module); - const site = CoreSites.instance.getCurrentSite(); + const handler = CoreCourseModulePrefetchDelegate.getPrefetchHandlerFor(module); + const site = CoreSites.getCurrentSite(); if (handler && site) { promises.push(site.deleteComponentFromCache(handler.component, module.id)); } @@ -1892,7 +1892,7 @@ export class CoreCourseHelperProvider { } -export class CoreCourseHelper extends makeSingleton(CoreCourseHelperProvider) {} +export const CoreCourseHelper = makeSingleton(CoreCourseHelperProvider); /** * Section with calculated data. diff --git a/src/core/features/course/services/course-offline.ts b/src/core/features/course/services/course-offline.ts index b33a12aa8..d6ae57611 100644 --- a/src/core/features/course/services/course-offline.ts +++ b/src/core/features/course/services/course-offline.ts @@ -32,7 +32,7 @@ export class CoreCourseOfflineProvider { * @return Promise resolved when done. */ async deleteManualCompletion(cmId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(MANUAL_COMPLETION_TABLE, { cmid: cmId }); } @@ -44,7 +44,7 @@ export class CoreCourseOfflineProvider { * @return Promise resolved with the list of completions. */ async getAllManualCompletions(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecords(MANUAL_COMPLETION_TABLE); } @@ -57,7 +57,7 @@ export class CoreCourseOfflineProvider { * @return Promise resolved with the list of completions. */ async getCourseManualCompletions(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecords(MANUAL_COMPLETION_TABLE, { courseid: courseId }); } @@ -70,7 +70,7 @@ export class CoreCourseOfflineProvider { * @return Promise resolved with the completion, rejected if failure or not found. */ async getManualCompletion(cmId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.getDb().getRecord(MANUAL_COMPLETION_TABLE, { cmid: cmId }); } @@ -94,7 +94,7 @@ export class CoreCourseOfflineProvider { ): Promise { // Store the offline data. - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entry: CoreCourseManualCompletionDBRecord = { cmid: cmId, completed: completed ? 1 : 0, @@ -112,4 +112,4 @@ export class CoreCourseOfflineProvider { } -export class CoreCourseOffline extends makeSingleton(CoreCourseOfflineProvider) { } +export const CoreCourseOffline = makeSingleton(CoreCourseOfflineProvider); diff --git a/src/core/features/course/services/course-options-delegate.ts b/src/core/features/course/services/course-options-delegate.ts index cfb872ad3..52fb9d3f8 100644 --- a/src/core/features/course/services/course-options-delegate.ts +++ b/src/core/features/course/services/course-options-delegate.ts @@ -285,12 +285,12 @@ export class CoreCourseOptionsDelegateService extends CoreDelegate { - if (CoreCourses.instance.canGetAdminAndNavOptions() && + if (CoreCourses.canGetAdminAndNavOptions() && (typeof course.navOptions == 'undefined' || typeof course.admOptions == 'undefined' || refresh)) { - const options = await CoreCourses.instance.getCoursesAdminAndNavOptions([course.id]); + const options = await CoreCourses.getCoursesAdminAndNavOptions([course.id]); course.navOptions = options.navOptions[course.id]; course.admOptions = options.admOptions[course.id]; } @@ -623,7 +623,7 @@ export class CoreCourseOptionsDelegateService extends CoreDelegate[] = []; const enabledForCourse: CoreCourseOptionsHandler[] = []; const enabledForCourseMenu: CoreCourseOptionsMenuHandler[] = []; - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); const now = Date.now(); this.lastUpdateHandlersForCoursesStart[courseId] = now; @@ -656,7 +656,7 @@ export class CoreCourseOptionsDelegateService extends CoreDelegate { + Platform.resume.subscribe(() => { // Run the handler the app is open to keep user in online status. setTimeout(() => { - CoreCronDelegate.instance.forceCronHandlerExecution(CoreCourseLogCronHandler.instance.name); + CoreCronDelegate.forceCronHandlerExecution(CoreCourseLogCronHandler.name); }, 1000); }); CoreEvents.on(CoreEvents.LOGIN, () => { setTimeout(() => { // Ignore errors here, since probably login is not complete: it happens on token invalid. - CoreUtils.instance.ignoreErrors( - CoreCronDelegate.instance.forceCronHandlerExecution(CoreCourseLogCronHandler.instance.name), + CoreUtils.ignoreErrors( + CoreCronDelegate.forceCronHandlerExecution(CoreCourseLogCronHandler.name), ); }, 1000); }); @@ -108,7 +108,7 @@ export class CoreCourseProvider { * @since 3.7 */ canGetCourseBlocks(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site && site.isVersionGreaterEqualThan('3.7') && site.wsAvailable('core_block_get_course_blocks'); } @@ -121,7 +121,7 @@ export class CoreCourseProvider { * @since 3.4.6, 3.5.3, 3.6 */ canRequestStealthModules(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site && site.isVersionGreaterEqualThan(['3.4.6', '3.5.3']); } @@ -148,7 +148,7 @@ export class CoreCourseProvider { * @return Promise resolved when all status are cleared. */ async clearAllCoursesStatus(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); this.logger.debug('Clear all course status for site ' + site.id); await site.getDb().deleteRecords(COURSE_STATUS_TABLE); @@ -187,7 +187,7 @@ export class CoreCourseProvider { includeOffline: boolean = true, ): Promise> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); this.logger.debug(`Getting completion status for user ${userId} in course ${courseId}`); @@ -218,14 +218,14 @@ export class CoreCourseProvider { throw Error('WS core_completion_get_activities_completion_status failed'); } - const completionStatus = CoreUtils.instance.arrayToObject(data.statuses, 'cmid'); + const completionStatus = CoreUtils.arrayToObject(data.statuses, 'cmid'); if (!includeOffline) { return completionStatus; } try { // Now get the offline completion (if any). - const offlineCompletions = await CoreCourseOffline.instance.getCourseManualCompletions(courseId, site.id); + const offlineCompletions = await CoreCourseOffline.getCourseManualCompletions(courseId, site.id); offlineCompletions.forEach((offlineCompletion) => { @@ -267,7 +267,7 @@ export class CoreCourseProvider { * @since 3.7 */ async getCourseBlocks(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreBlockGetCourseBlocksWSParams = { courseid: courseId, returncontents: true, @@ -299,7 +299,7 @@ export class CoreCourseProvider { * @return Promise resolved with the data. */ async getCourseStatusData(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entry: CoreCourseStatusDBRecord = await site.getDb().getRecord(COURSE_STATUS_TABLE, { id: courseId }); if (!entry) { throw Error('No entry found on course status table'); @@ -332,7 +332,7 @@ export class CoreCourseProvider { * @return Resolves with an array containing downloaded course ids. */ async getDownloadedCourseIds(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entries: CoreCourseStatusDBRecord[] = await site.getDb().getRecordsList( COURSE_STATUS_TABLE, 'status', @@ -368,7 +368,7 @@ export class CoreCourseProvider { siteId?: string, modName?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Helper function to do the WS request without processing the result. const doRequest = async ( @@ -420,7 +420,7 @@ export class CoreCourseProvider { return sections; } catch { // The module might still be cached by a request with different parameters. - if (!ignoreCache && !CoreApp.instance.isOnline()) { + if (!ignoreCache && !CoreApp.isOnline()) { if (includeStealth) { // Older versions didn't include the includestealthmodules option. return doRequest(site, moduleId, modName, false, true); @@ -442,7 +442,7 @@ export class CoreCourseProvider { let sections: CoreCourseWSSection[]; try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // We have courseId, we can use core_course_get_contents for compatibility. this.logger.debug(`Getting module ${moduleId} in course ${courseId}`); @@ -494,7 +494,7 @@ export class CoreCourseProvider { * @return Promise resolved with the module's info. */ async getModuleBasicInfo(moduleId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCourseGetCourseModuleWSParams = { cmid: moduleId, }; @@ -523,7 +523,7 @@ export class CoreCourseProvider { * @return Promise resolved with the module's grade info. */ async getModuleBasicGradeInfo(moduleId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (!site || !site.isVersionGreaterEqualThan('3.2')) { // On 3.1 won't get grading info and will return undefined. See check bellow. @@ -562,7 +562,7 @@ export class CoreCourseProvider { * @return Promise resolved with the module's info. */ async getModuleBasicInfoByInstance(id: number, module: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCourseGetCourseModuleByInstanceWSParams = { instance: id, module: module, @@ -702,7 +702,7 @@ export class CoreCourseProvider { includeStealthModules: boolean = true, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); preSets = preSets || {}; preSets.cacheKey = this.getSectionsCacheKey(courseId); preSets.updateFrequency = preSets.updateFrequency || CoreSite.FREQUENCY_RARELY; @@ -785,7 +785,7 @@ export class CoreCourseProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCourseBlocks(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCourseBlocksCacheKey(courseId)); } @@ -799,7 +799,7 @@ export class CoreCourseProvider { * @return Promise resolved when the data is invalidated. */ async invalidateModule(moduleId: number, siteId?: string, modName?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const promises: Promise[] = []; if (modName) { promises.push(site.invalidateWsCacheForKey(this.getModuleByModNameCacheKey(modName))); @@ -818,7 +818,7 @@ export class CoreCourseProvider { * @return Promise resolved when the data is invalidated. */ async invalidateModuleByInstance(id: number, module: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getModuleBasicInfoByInstanceCacheKey(id, module)); } @@ -832,7 +832,7 @@ export class CoreCourseProvider { * @return Promise resolved when the data is invalidated. */ async invalidateSections(courseId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const promises: Promise[] = []; const siteHomeId = site.getSiteHomeId(); userId = userId || site.getUserId(); @@ -896,8 +896,8 @@ export class CoreCourseProvider { params.sectionnumber = sectionNumber; } - const site = await CoreSites.instance.getSite(siteId); - CorePushNotifications.instance.logViewEvent(courseId, name, 'course', wsName, { sectionnumber: sectionNumber }, siteId); + const site = await CoreSites.getSite(siteId); + CorePushNotifications.logViewEvent(courseId, name, 'course', wsName, { sectionnumber: sectionNumber }, siteId); const response: CoreStatusWithWarningsWSResponse = await site.write(wsName, params); if (!response.status) { @@ -928,14 +928,14 @@ export class CoreCourseProvider { siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Convenience function to store a completion to be synchronized later. const storeOffline = (): Promise => - CoreCourseOffline.instance.markCompletedManually(cmId, completed, courseId, courseName, siteId); + CoreCourseOffline.markCompletedManually(cmId, completed, courseId, courseName, siteId); // The offline function requires a courseId and it could be missing because it's a calculated field. - if (!CoreApp.instance.isOnline() && courseId) { + if (!CoreApp.isOnline() && courseId) { // App is offline, store the action. return storeOffline(); } @@ -946,14 +946,14 @@ export class CoreCourseProvider { // Data sent to server, if there is some offline data delete it now. try { - await CoreCourseOffline.instance.deleteManualCompletion(cmId, siteId); + await CoreCourseOffline.deleteManualCompletion(cmId, siteId); } catch { // Ignore errors, shouldn't happen. } return result; } catch (error) { - if (CoreUtils.instance.isWebServiceError(error) || !courseId) { + if (CoreUtils.isWebServiceError(error) || !courseId) { // The WebService has thrown an error, this means that responses cannot be submitted. throw error; } else { @@ -976,7 +976,7 @@ export class CoreCourseProvider { completed: boolean, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCompletionUpdateActivityCompletionStatusManuallyWSParams = { cmid: cmId, completed: completed, @@ -1023,20 +1023,20 @@ export class CoreCourseProvider { * @return Promise resolved when done. */ async openCourse(course: CoreCourseAnyCourseData | { id: number }, params?: Params): Promise { - const loading = await CoreDomUtils.instance.showModalLoading(); + const loading = await CoreDomUtils.showModalLoading(); // Wait for site plugins to be fetched. // @todo await this.sitePluginsProvider.waitFetchPlugins(); if (!('format' in course) || typeof course.format == 'undefined') { - const result = await CoreCourseHelper.instance.getCourse(course.id); + const result = await CoreCourseHelper.getCourse(course.id); course = result.course; } if (course) { // @todo Replace with: if (!this.sitePluginsProvider.sitePluginPromiseExists('format_' + course.format)) { // No custom format plugin. We don't need to wait for anything. - await CoreCourseFormatDelegate.instance.openCourse( course, params); + await CoreCourseFormatDelegate.openCourse( course, params); loading.dismiss(); return; @@ -1047,27 +1047,27 @@ export class CoreCourseProvider { /* @todo await this.sitePluginsProvider.sitePluginLoaded('format_' + course.format); // The format loaded successfully, but the handlers wont be registered until all site plugins have loaded. if (this.sitePluginsProvider.sitePluginsFinishedLoading) { - return CoreCourseFormatDelegate.instance.openCourse(course, params); + return CoreCourseFormatDelegate.openCourse(course, params); }*/ // Wait for plugins to be loaded. - const deferred = CoreUtils.instance.promiseDefer(); + const deferred = CoreUtils.promiseDefer(); const observer = CoreEvents.on(CoreEvents.SITE_PLUGINS_LOADED, () => { observer?.off(); - CoreCourseFormatDelegate.instance.openCourse( course, params) + CoreCourseFormatDelegate.openCourse( course, params) .then(deferred.resolve).catch(deferred.reject); }); return deferred.promise; } catch (error) { // The site plugin failed to load. The user needs to restart the app to try loading it again. - const message = Translate.instance.instant('core.courses.errorloadplugins'); - const reload = Translate.instance.instant('core.courses.reload'); - const ignore = Translate.instance.instant('core.courses.ignore'); + const message = Translate.instant('core.courses.errorloadplugins'); + const reload = Translate.instant('core.courses.reload'); + const ignore = Translate.instant('core.courses.ignore'); - await CoreDomUtils.instance.showConfirm(message, '', reload, ignore); + await CoreDomUtils.showConfirm(message, '', reload, ignore); window.location.reload(); } } @@ -1093,11 +1093,11 @@ export class CoreCourseProvider { * @return Promise resolved when the status is changed. Resolve param: new status. */ async setCoursePreviousStatus(courseId: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); this.logger.debug(`Set previous status for course ${courseId} in site ${siteId}`); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const db = site.getDb(); const entry = await this.getCourseStatusData(courseId, siteId); @@ -1127,18 +1127,18 @@ export class CoreCourseProvider { * @return Promise resolved when the status is stored. */ async setCourseStatus(courseId: number, status: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); this.logger.debug(`Set status '${status}' for course ${courseId} in site ${siteId}`); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); let downloadTime = 0; let previousDownloadTime = 0; let previousStatus = ''; if (status == CoreConstants.DOWNLOADING) { // Set download time if course is now downloading. - downloadTime = CoreTimeUtils.instance.timestamp(); + downloadTime = CoreTimeUtils.timestamp(); } try { @@ -1186,7 +1186,7 @@ export class CoreCourseProvider { } const langKey = 'core.mod_' + moduleName; - const translated = Translate.instance.instant(langKey); + const translated = Translate.instant(langKey); return translated !== langKey ? translated : moduleName; } @@ -1207,7 +1207,7 @@ export class CoreCourseProvider { } -export class CoreCourse extends makeSingleton(CoreCourseProvider) {} +export const CoreCourse = makeSingleton(CoreCourseProvider); /** * Common options used by modules when calling a WS through CoreSite. diff --git a/src/core/features/course/services/format-delegate.ts b/src/core/features/course/services/format-delegate.ts index effa5d9a2..b2ecc2f13 100644 --- a/src/core/features/course/services/format-delegate.ts +++ b/src/core/features/course/services/format-delegate.ts @@ -375,4 +375,4 @@ export class CoreCourseFormatDelegateService extends CoreDelegate { const courseId = parseInt(coursebox.getAttribute('data-courseid') || '', 10); @@ -75,7 +75,7 @@ export class CoreCourseTagAreaHandlerService implements CoreTagAreaHandler { } -export class CoreCourseTagAreaHandler extends makeSingleton(CoreCourseTagAreaHandlerService) {} +export const CoreCourseTagAreaHandler = makeSingleton(CoreCourseTagAreaHandlerService); export type CoreCouseTagItems = { courseId: number; diff --git a/src/core/features/course/services/handlers/default-format.ts b/src/core/features/course/services/handlers/default-format.ts index 115ca52be..35c02270e 100644 --- a/src/core/features/course/services/handlers/default-format.ts +++ b/src/core/features/course/services/handlers/default-format.ts @@ -127,12 +127,12 @@ export class CoreCourseFormatDefaultHandler implements CoreCourseFormatHandler { if ('marker' in course) { // We already have it. marker = course.marker; - } else if (!CoreCourses.instance.isGetCoursesByFieldAvailable()) { + } else if (!CoreCourses.isGetCoursesByFieldAvailable()) { // Cannot get the current section, return all of them. return sections[0]; } else { // Try to retrieve the marker. - const courseData = await CoreUtils.instance.ignoreErrors(CoreCourses.instance.getCourseByField('id', course.id)); + const courseData = await CoreUtils.ignoreErrors(CoreCourses.getCourseByField('id', course.id)); marker = courseData?.marker; } @@ -159,7 +159,7 @@ export class CoreCourseFormatDefaultHandler implements CoreCourseFormatHandler { */ // eslint-disable-next-line @typescript-eslint/no-unused-vars async invalidateData(course: CoreCourseAnyCourseData, sections: CoreCourseWSSection[]): Promise { - await CoreCourses.instance.invalidateCoursesByField('id', course.id); + await CoreCourses.invalidateCoursesByField('id', course.id); } /** @@ -177,7 +177,7 @@ export class CoreCourseFormatDefaultHandler implements CoreCourseFormatHandler { Object.assign(params, { course: course }); // Don't return the .push promise, we don't want to display a loading modal during the page transition. - CoreNavigator.instance.navigateToSitePath('course', { params }); + CoreNavigator.navigateToSitePath('course', { params }); } /** diff --git a/src/core/features/course/services/handlers/default-module.ts b/src/core/features/course/services/handlers/default-module.ts index cfcda4a52..483c3cb5c 100644 --- a/src/core/features/course/services/handlers/default-module.ts +++ b/src/core/features/course/services/handlers/default-module.ts @@ -56,7 +56,7 @@ export class CoreCourseModuleDefaultHandler implements CoreCourseModuleHandler { ): CoreCourseModuleHandlerData { // Return the default data. const defaultData: CoreCourseModuleHandlerData = { - icon: CoreCourse.instance.getModuleIconSrc(module.modname, 'modicon' in module ? module.modicon : undefined), + icon: CoreCourse.getModuleIconSrc(module.modname, 'modicon' in module ? module.modicon : undefined), title: module.name, class: 'core-course-default-handler core-course-module-' + module.modname + '-handler', action: (event: Event, module: CoreCourseModule, courseId: number, options?: CoreNavigationOptions) => { @@ -66,7 +66,7 @@ export class CoreCourseModuleDefaultHandler implements CoreCourseModuleHandler { options = options || {}; options.params = { module, courseId }; - CoreNavigator.instance.navigateToSitePath('course/unsupported-module', options); + CoreNavigator.navigateToSitePath('course/unsupported-module', options); }, }; @@ -78,7 +78,7 @@ export class CoreCourseModuleDefaultHandler implements CoreCourseModuleHandler { e.preventDefault(); e.stopPropagation(); - CoreSites.instance.getCurrentSite()!.openInBrowserWithAutoLoginIfSameSite(module.url!); + CoreSites.getCurrentSite()!.openInBrowserWithAutoLoginIfSameSite(module.url!); }, }]; } diff --git a/src/core/features/course/services/handlers/log-cron.ts b/src/core/features/course/services/handlers/log-cron.ts index 9940cf672..bbcc94fba 100644 --- a/src/core/features/course/services/handlers/log-cron.ts +++ b/src/core/features/course/services/handlers/log-cron.ts @@ -37,9 +37,9 @@ export class CoreCourseLogCronHandlerService implements CoreCronHandler { */ // eslint-disable-next-line @typescript-eslint/no-unused-vars async execute(siteId?: string, force?: boolean): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - return CoreCourse.instance.logView(site.getSiteHomeId(), undefined, site.getId(), site.getInfo()?.sitename); + return CoreCourse.logView(site.getSiteHomeId(), undefined, site.getId(), site.getInfo()?.sitename); } /** @@ -62,4 +62,4 @@ export class CoreCourseLogCronHandlerService implements CoreCronHandler { } -export class CoreCourseLogCronHandler extends makeSingleton(CoreCourseLogCronHandlerService) {} +export const CoreCourseLogCronHandler = makeSingleton(CoreCourseLogCronHandlerService, ['name']); diff --git a/src/core/features/course/services/handlers/modules-tag-area.ts b/src/core/features/course/services/handlers/modules-tag-area.ts index fa488ebf7..75ee702fd 100644 --- a/src/core/features/course/services/handlers/modules-tag-area.ts +++ b/src/core/features/course/services/handlers/modules-tag-area.ts @@ -44,7 +44,7 @@ export class CoreCourseModulesTagAreaHandlerService implements CoreTagAreaHandle * @return Area items (or promise resolved with the items). */ parseContent(content: string): CoreTagFeedElement[] | Promise { - return CoreTagHelper.instance.parseFeedContent(content); + return CoreTagHelper.parseFeedContent(content); } /** @@ -58,4 +58,4 @@ export class CoreCourseModulesTagAreaHandlerService implements CoreTagAreaHandle } -export class CoreCourseModulesTagAreaHandler extends makeSingleton(CoreCourseModulesTagAreaHandlerService) {} +export const CoreCourseModulesTagAreaHandler = makeSingleton(CoreCourseModulesTagAreaHandlerService); diff --git a/src/core/features/course/services/handlers/sync-cron.ts b/src/core/features/course/services/handlers/sync-cron.ts index 39a96a82d..e5388b3ca 100644 --- a/src/core/features/course/services/handlers/sync-cron.ts +++ b/src/core/features/course/services/handlers/sync-cron.ts @@ -35,7 +35,7 @@ export class CoreCourseSyncCronHandlerService implements CoreCronHandler { * @return Promise resolved when done, rejected if failure. */ execute(siteId?: string, force?: boolean): Promise { - return CoreCourseSync.instance.syncAllCourses(siteId, force); + return CoreCourseSync.syncAllCourses(siteId, force); } /** @@ -44,9 +44,9 @@ export class CoreCourseSyncCronHandlerService implements CoreCronHandler { * @return Time between consecutive executions (in ms). */ getInterval(): number { - return CoreCourseSync.instance.syncInterval; + return CoreCourseSync.syncInterval; } } -export class CoreCourseSyncCronHandler extends makeSingleton(CoreCourseSyncCronHandlerService) {} +export const CoreCourseSyncCronHandler = makeSingleton(CoreCourseSyncCronHandlerService); diff --git a/src/core/features/course/services/log-helper.ts b/src/core/features/course/services/log-helper.ts index d75121c88..f7d8cbbc0 100644 --- a/src/core/features/course/services/log-helper.ts +++ b/src/core/features/course/services/log-helper.ts @@ -40,7 +40,7 @@ export class CoreCourseLogHelperProvider { * @return Promise resolved when deleted, rejected if failure. */ protected async deleteLogs(component: string, componentId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions: Partial = { component, @@ -60,7 +60,7 @@ export class CoreCourseLogHelperProvider { * @return Promise resolved when deleted, rejected if failure. */ protected async deleteWSLogsByComponent(component: string, componentId: number, ws: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions: Partial = { component, @@ -80,11 +80,11 @@ export class CoreCourseLogHelperProvider { * @return Promise resolved when deleted, rejected if failure. */ protected async deleteWSLogs(ws: string, data: Record, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions: Partial = { ws, - data: CoreUtils.instance.sortAndStringify(data), + data: CoreUtils.sortAndStringify(data), }; await site.getDb().deleteRecords(ACTIVITY_LOG_TABLE, conditions); @@ -97,7 +97,7 @@ export class CoreCourseLogHelperProvider { * @return Promise resolved with the list of offline logs. */ protected async getAllLogs(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getAllRecords(ACTIVITY_LOG_TABLE); } @@ -111,7 +111,7 @@ export class CoreCourseLogHelperProvider { * @return Promise resolved with the list of offline logs. */ protected async getLogs(component: string, componentId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions: Partial = { component, @@ -132,9 +132,9 @@ export class CoreCourseLogHelperProvider { * @return Promise resolved when done. */ async log(ws: string, data: Record, component: string, componentId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // App is offline, store the action. return this.storeOffline(ws, data, component, componentId, site.getId()); } @@ -142,7 +142,7 @@ export class CoreCourseLogHelperProvider { try { await this.logOnline(ws, data, site.getId()); } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // The WebService has thrown an error, this means that responses cannot be submitted. throw error; } @@ -166,7 +166,7 @@ export class CoreCourseLogHelperProvider { data: Record, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Clone to have an unmodified data object. const wsData = Object.assign({}, data); @@ -212,7 +212,7 @@ export class CoreCourseLogHelperProvider { eventData?: Record, siteId?: string, ): Promise { - CorePushNotifications.instance.logViewEvent(componentId, name, category, ws, eventData, siteId); + CorePushNotifications.logViewEvent(componentId, name, category, ws, eventData, siteId); return this.log(ws, data, component, componentId, siteId); } @@ -239,7 +239,7 @@ export class CoreCourseLogHelperProvider { eventData?: Record, siteId?: string, ): Promise { - CorePushNotifications.instance.logViewListEvent(category, ws, eventData, siteId); + CorePushNotifications.logViewListEvent(category, ws, eventData, siteId); return this.log(ws, data, component, componentId, siteId); } @@ -262,14 +262,14 @@ export class CoreCourseLogHelperProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const log: CoreCourseActivityLogDBRecord = { component, componentid: componentId, ws, - data: CoreUtils.instance.sortAndStringify(data), - time: CoreTimeUtils.instance.timestamp(), + data: CoreUtils.sortAndStringify(data), + time: CoreTimeUtils.timestamp(), }; await site.getDb().insertRecord(ACTIVITY_LOG_TABLE, log); @@ -282,7 +282,7 @@ export class CoreCourseLogHelperProvider { * @return Promise resolved when done. */ async syncSite(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); @@ -326,7 +326,7 @@ export class CoreCourseLogHelperProvider { * @return Promise resolved when done. */ async syncActivity(component: string, componentId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); @@ -356,14 +356,14 @@ export class CoreCourseLogHelperProvider { */ protected async syncLogs(logs: CoreCourseActivityLogDBRecord[], siteId: string): Promise { await Promise.all(logs.map(async (log) => { - const data = CoreTextUtils.instance.parseJSON>(log.data || '{}', {}); + const data = CoreTextUtils.parseJSON>(log.data || '{}', {}); try { await this.logOnline(log.ws, data, siteId); } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // The WebService has thrown an error, this means that responses cannot be submitted. - await CoreUtils.instance.ignoreErrors(this.deleteWSLogs(log.ws, data, siteId)); + await CoreUtils.ignoreErrors(this.deleteWSLogs(log.ws, data, siteId)); } throw error; @@ -375,4 +375,4 @@ export class CoreCourseLogHelperProvider { } -export class CoreCourseLogHelper extends makeSingleton(CoreCourseLogHelperProvider) {} +export const CoreCourseLogHelper = makeSingleton(CoreCourseLogHelperProvider); diff --git a/src/core/features/course/services/module-delegate.ts b/src/core/features/course/services/module-delegate.ts index 793fe12d1..638543dc2 100644 --- a/src/core/features/course/services/module-delegate.ts +++ b/src/core/features/course/services/module-delegate.ts @@ -290,7 +290,7 @@ export class CoreCourseModuleDelegateService extends CoreDelegate { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isModuleDisabledInSite(modname, site); } @@ -306,7 +306,7 @@ export class CoreCourseModuleDelegateService extends CoreDelegate(modname, 'getIconSrc') || - CoreCourse.instance.getModuleIconSrc(modname, modicon); + CoreCourse.getModuleIconSrc(modname, modicon); } /** @@ -368,4 +368,4 @@ export class CoreCourseModuleDelegateService extends CoreDelegate(CoreEvents.PACKAGE_STATUS_CHANGED, (data) => { this.updateStatusCache(data.status, data.component, data.componentId); - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); // If a file inside a module is downloaded/deleted, clear the corresponding cache. CoreEvents.on(CoreEvents.COMPONENT_FILE_ACTION, (data) => { - if (!CoreFilepool.instance.isFileEventDownloadedOrDeleted(data)) { + if (!CoreFilepool.isFileEventDownloadedOrDeleted(data)) { return; } - this.statusCache.invalidate(CoreFilepool.instance.getPackageId(data.component, data.componentId)); - }, CoreSites.instance.getCurrentSiteId()); + this.statusCache.invalidate(CoreFilepool.getPackageId(data.component, data.componentId)); + }, CoreSites.getCurrentSiteId()); } /** @@ -82,7 +82,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate Md5.hashAsciiStr(courseId + '#' + JSON.stringify(modules)); - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); if (this.courseUpdatesPromises[siteId] && this.courseUpdatesPromises[siteId][id]) { // There's already a get updates ongoing, return the promise. @@ -277,7 +277,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate(packageId, 'downloadSize'); if (typeof downloadSize != 'undefined') { return downloadSize; @@ -438,7 +438,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate(packageId, 'downloadedSize'); if (typeof downloadedSize != 'undefined') { return downloadedSize; @@ -454,20 +454,20 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { - const path = await CoreFilepool.instance.getFilePathByUrl(siteId, file.fileurl || ''); + const path = await CoreFilepool.getFilePathByUrl(siteId, file.fileurl || ''); try { - const fileSize = await CoreFile.instance.getFileSize(path); + const fileSize = await CoreFile.getFileSize(path); size += fileSize; } catch { // Error getting size. Check if the file is being downloaded. try { - await CoreFilepool.instance.isFileDownloadingByUrl(siteId, file.fileurl || ''); + await CoreFilepool.isFileDownloadingByUrl(siteId, file.fileurl || ''); // If downloading, count as downloaded. size += file.filesize || 0; @@ -500,7 +500,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate(packageId, 'status'); if (!refresh && typeof status != 'undefined') { @@ -612,9 +612,9 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate(packageId, 'status', true); return { @@ -736,11 +736,11 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate(packageId, 'status', true); if (typeof cacheStatus == 'undefined') { throw error; @@ -750,7 +750,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { const handler = this.getPrefetchHandlerFor(module); - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); if (!handler) { // No handler found, module not downloadable. @@ -779,10 +779,10 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate(packageId, 'status'); - if (typeof status != 'undefined' && !CoreFileHelper.instance.isStateDownloaded(status)) { + if (typeof status != 'undefined' && !CoreFileHelper.isStateDownloaded(status)) { // Module isn't downloaded, just return the status. return { status }; } @@ -794,7 +794,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data = await this.getModuleStatusAndDownloadTime(module, courseId); - if (!CoreFileHelper.instance.isStateDownloaded(data.status)) { + if (!CoreFileHelper.isStateDownloaded(data.status)) { // Not downloaded, no updates. return null; } @@ -889,7 +889,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { - const site = CoreSites.instance.getCurrentSite(); + const site = CoreSites.getCurrentSite(); if (!site) { return; } @@ -913,7 +913,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getModuleUpdatesCacheKey(courseId, moduleId)); } @@ -958,7 +958,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate(packageId, 'downloadable'); if (typeof downloadable != 'undefined') { @@ -1067,7 +1067,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); const currentPrefetchData = this.prefetchData[siteId]?.[id]; if (currentPrefetchData) { @@ -1157,7 +1157,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { const handler = this.getPrefetchHandlerFor(module); - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); if (handler?.removeFiles) { // Handler implements a method to remove the files, use it. @@ -1193,7 +1193,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { - await CoreUtils.instance.ignoreErrors(CoreFilepool.instance.removeFileByUrl(siteId, file.fileurl || '')); + await CoreUtils.ignoreErrors(CoreFilepool.removeFileByUrl(siteId, file.fileurl || '')); })); } @@ -1202,7 +1202,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { @@ -1299,7 +1299,7 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate(packageId, 'status', true); // If courseId/sectionId is set, store it. @@ -1324,13 +1324,13 @@ export class CoreCourseModulePrefetchDelegateService extends CoreDelegate { await Promise.all([ - CoreCourseLogHelper.instance.syncSite(siteId), + CoreCourseLogHelper.syncSite(siteId), this.syncCoursesCompletion(siteId, force), ]); } @@ -75,7 +75,7 @@ export class CoreCourseSyncProvider extends CoreSyncBaseProvider { - const completions = await CoreCourseOffline.instance.getAllManualCompletions(siteId); + const completions = await CoreCourseOffline.getAllManualCompletions(siteId); // Sync all courses. await Promise.all(completions.map(async (completion) => { @@ -115,7 +115,7 @@ export class CoreCourseSyncProvider extends CoreSyncBaseProvider { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.isSyncing(courseId, siteId)) { // There's already a sync ongoing for this discussion, return the promise. @@ -141,8 +141,8 @@ export class CoreCourseSyncProvider extends CoreSyncBaseProvider [], ); @@ -155,14 +155,14 @@ export class CoreCourseSyncProvider extends CoreSyncBaseProvider entry.timecompleted) { - await CoreCourseOffline.instance.deleteManualCompletion(entry.cmid, siteId); + await CoreCourseOffline.deleteManualCompletion(entry.cmid, siteId); // Completion deleted, add a warning if the completion status doesn't match. if (onlineComp.state != entry.completed) { - result.warnings.push(Translate.instance.instant('core.course.warningofflinemanualcompletiondeleted', { + result.warnings.push(Translate.instant('core.course.warningofflinemanualcompletiondeleted', { name: entry.coursename || courseId, - error: Translate.instance.instant('core.course.warningmanualcompletionmodified'), + error: Translate.instant('core.course.warningmanualcompletionmodified'), })); } @@ -191,13 +191,13 @@ export class CoreCourseSyncProvider extends CoreSyncBaseProvider { - CoreCoursesHelper.instance.loadCourseColorAndImage(this.course); + CoreCoursesHelper.loadCourseColorAndImage(this.course); // Check if the user is enrolled in the course. try { - const course = await CoreCourses.instance.getUserCourse(this.course.id); + const course = await CoreCourses.getUserCourse(this.course.id); this.course.progress = course.progress; this.course.completionusertracked = course.completionusertracked; @@ -92,9 +92,9 @@ export class CoreCoursesCourseListItemComponent implements OnInit { */ openCourse(): void { if (this.isEnrolled) { - CoreCourseHelper.instance.openCourse(this.course); + CoreCourseHelper.openCourse(this.course); } else { - CoreNavigator.instance.navigate('courses/preview', { params: { course: this.course } }); + CoreNavigator.navigate('courses/preview', { params: { course: this.course } }); } } diff --git a/src/core/features/courses/components/course-options-menu/course-options-menu.ts b/src/core/features/courses/components/course-options-menu/course-options-menu.ts index a25ffe83b..cc92a3675 100644 --- a/src/core/features/courses/components/course-options-menu/course-options-menu.ts +++ b/src/core/features/courses/components/course-options-menu/course-options-menu.ts @@ -36,7 +36,7 @@ export class CoreCoursesCourseOptionsMenuComponent implements OnInit { * Component being initialized. */ ngOnInit(): void { - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); } /** @@ -45,7 +45,7 @@ export class CoreCoursesCourseOptionsMenuComponent implements OnInit { * @param action Action name to take. */ action(action: string): void { - PopoverController.instance.dismiss(action); + PopoverController.dismiss(action); } } diff --git a/src/core/features/courses/components/course-progress/course-progress.ts b/src/core/features/courses/components/course-progress/course-progress.ts index 968fe2f80..c189a30af 100644 --- a/src/core/features/courses/components/course-progress/course-progress.ts +++ b/src/core/features/courses/components/course-progress/course-progress.ts @@ -66,7 +66,7 @@ export class CoreCoursesCourseProgressComponent implements OnInit, OnDestroy { */ ngOnInit(): void { - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); if (this.downloadCourseEnabled) { this.initPrefetchCourse(); @@ -79,13 +79,13 @@ export class CoreCoursesCourseProgressComponent implements OnInit, OnDestroy { this.siteUpdatedObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { const wasEnabled = this.downloadCourseEnabled; - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); if (!wasEnabled && this.downloadCourseEnabled) { // Download course is enabled now, initialize it. this.initPrefetchCourse(); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } /** @@ -102,27 +102,27 @@ export class CoreCoursesCourseProgressComponent implements OnInit, OnDestroy { if (data.courseId == this.course.id || data.courseId == CoreCourseProvider.ALL_COURSES_CLEARED) { this.updateCourseStatus(data.status); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); // Determine course prefetch icon. - const status = await CoreCourse.instance.getCourseStatus(this.course.id); + const status = await CoreCourse.getCourseStatus(this.course.id); - this.prefetchCourseData = CoreCourseHelper.instance.getCourseStatusIconAndTitleFromStatus(status); + this.prefetchCourseData = CoreCourseHelper.getCourseStatusIconAndTitleFromStatus(status); this.courseStatus = status; if (this.prefetchCourseData.loading) { // Course is being downloaded. Get the download promise. - const promise = CoreCourseHelper.instance.getCourseDownloadPromise(this.course.id); + const promise = CoreCourseHelper.getCourseDownloadPromise(this.course.id); if (promise) { // There is a download promise. If it fails, show an error. promise.catch((error) => { if (!this.isDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); } }); } else { // No download, this probably means that the app was closed while downloading. Set previous status. - CoreCourse.instance.setCoursePreviousStatus(this.course.id); + CoreCourse.setCoursePreviousStatus(this.course.id); } } @@ -132,7 +132,7 @@ export class CoreCoursesCourseProgressComponent implements OnInit, OnDestroy { * Open a course. */ openCourse(): void { - CoreCourseHelper.instance.openCourse(this.course); + CoreCourseHelper.openCourse(this.course); } /** @@ -145,10 +145,10 @@ export class CoreCoursesCourseProgressComponent implements OnInit, OnDestroy { e.stopPropagation(); /* @ todo try { - CoreCourseHelper.instance.confirmAndPrefetchCourse(this.prefetchCourseData, this.course); + CoreCourseHelper.confirmAndPrefetchCourse(this.prefetchCourseData, this.course); } catch (error) { if (!this.isDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); } }*/ } @@ -158,21 +158,21 @@ export class CoreCoursesCourseProgressComponent implements OnInit, OnDestroy { */ async deleteCourse(): Promise { try { - await CoreDomUtils.instance.showDeleteConfirm('core.course.confirmdeletestoreddata'); + await CoreDomUtils.showDeleteConfirm('core.course.confirmdeletestoreddata'); } catch (error) { - if (CoreDomUtils.instance.isCanceledError(error)) { + if (CoreDomUtils.isCanceledError(error)) { throw error; } return; } - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { - await CoreCourseHelper.instance.deleteCourseFiles(this.course.id); + await CoreCourseHelper.deleteCourseFiles(this.course.id); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, Translate.instance.instant('core.errordeletefile')); + CoreDomUtils.showErrorModalDefault(error, Translate.instant('core.errordeletefile')); } finally { modal.dismiss(); } @@ -184,7 +184,7 @@ export class CoreCoursesCourseProgressComponent implements OnInit, OnDestroy { * @param status Status to show. */ protected updateCourseStatus(status: string): void { - this.prefetchCourseData = CoreCourseHelper.instance.getCourseStatusIconAndTitleFromStatus(status); + this.prefetchCourseData = CoreCourseHelper.getCourseStatusIconAndTitleFromStatus(status); this.courseStatus = status; } @@ -199,7 +199,7 @@ export class CoreCoursesCourseProgressComponent implements OnInit, OnDestroy { e.preventDefault(); e.stopPropagation(); - const popover = await PopoverController.instance.create({ + const popover = await PopoverController.create({ component: CoreCoursesCourseOptionsMenuComponent, componentProps: { course: this.course, diff --git a/src/core/features/courses/components/self-enrol-password/self-enrol-password.ts b/src/core/features/courses/components/self-enrol-password/self-enrol-password.ts index d44874761..cceb77551 100644 --- a/src/core/features/courses/components/self-enrol-password/self-enrol-password.ts +++ b/src/core/features/courses/components/self-enrol-password/self-enrol-password.ts @@ -40,7 +40,7 @@ export class CoreCoursesSelfEnrolPasswordComponent { * Close help modal. */ close(): void { - CoreDomUtils.instance.triggerFormCancelledEvent(this.formElement, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); this.modalCtrl.dismiss(); } @@ -55,7 +55,7 @@ export class CoreCoursesSelfEnrolPasswordComponent { e.preventDefault(); e.stopPropagation(); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, false, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, false, CoreSites.getCurrentSiteId()); this.modalCtrl.dismiss(this.password); } diff --git a/src/core/features/courses/courses.module.ts b/src/core/features/courses/courses.module.ts index 52a5e34c8..46221b207 100644 --- a/src/core/features/courses/courses.module.ts +++ b/src/core/features/courses/courses.module.ts @@ -64,13 +64,13 @@ const mainMenuHomeSiblingRoutes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreMainMenuHomeDelegate.instance.registerHandler(CoreDashboardHomeHandler.instance); - CoreMainMenuHomeDelegate.instance.registerHandler(CoreCoursesMyCoursesHomeHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(CoreCoursesCourseLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(CoreCoursesIndexLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(CoreCoursesDashboardLinkHandler.instance); - CorePushNotificationsDelegate.instance.registerClickHandler(CoreCoursesEnrolPushClickHandler.instance); - CorePushNotificationsDelegate.instance.registerClickHandler(CoreCoursesRequestPushClickHandler.instance); + CoreMainMenuHomeDelegate.registerHandler(CoreDashboardHomeHandler.instance); + CoreMainMenuHomeDelegate.registerHandler(CoreCoursesMyCoursesHomeHandler.instance); + CoreContentLinksDelegate.registerHandler(CoreCoursesCourseLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(CoreCoursesIndexLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(CoreCoursesDashboardLinkHandler.instance); + CorePushNotificationsDelegate.registerClickHandler(CoreCoursesEnrolPushClickHandler.instance); + CorePushNotificationsDelegate.registerClickHandler(CoreCoursesRequestPushClickHandler.instance); }, }, ], diff --git a/src/core/features/courses/pages/available-courses/available-courses.ts b/src/core/features/courses/pages/available-courses/available-courses.ts index 3d7cde640..43238450d 100644 --- a/src/core/features/courses/pages/available-courses/available-courses.ts +++ b/src/core/features/courses/pages/available-courses/available-courses.ts @@ -46,14 +46,14 @@ export class CoreCoursesAvailableCoursesPage implements OnInit { * @return Promise resolved when done. */ protected async loadCourses(): Promise { - const frontpageCourseId = CoreSites.instance.getCurrentSiteHomeId(); + const frontpageCourseId = CoreSites.getCurrentSiteHomeId(); try { - const courses = await CoreCourses.instance.getCoursesByField(); + const courses = await CoreCourses.getCoursesByField(); this.courses = courses.filter((course) => course.id != frontpageCourseId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.courses.errorloadcourses', true); + CoreDomUtils.showErrorModalDefault(error, 'core.courses.errorloadcourses', true); } } @@ -65,8 +65,8 @@ export class CoreCoursesAvailableCoursesPage implements OnInit { refreshCourses(refresher: CustomEvent): void { const promises: Promise[] = []; - promises.push(CoreCourses.instance.invalidateUserCourses()); - promises.push(CoreCourses.instance.invalidateCoursesByField()); + promises.push(CoreCourses.invalidateUserCourses()); + promises.push(CoreCourses.invalidateCoursesByField()); Promise.all(promises).finally(() => { this.loadCourses().finally(() => { diff --git a/src/core/features/courses/pages/categories/categories.ts b/src/core/features/courses/pages/categories/categories.ts index 0a4de8996..1dce61f1a 100644 --- a/src/core/features/courses/pages/categories/categories.ts +++ b/src/core/features/courses/pages/categories/categories.ts @@ -39,14 +39,14 @@ export class CoreCoursesCategoriesPage implements OnInit { protected categoryId = 0; constructor() { - this.title = Translate.instance.instant('core.courses.categories'); + this.title = Translate.instant('core.courses.categories'); } /** * View loaded. */ ngOnInit(): void { - this.categoryId = CoreNavigator.instance.getRouteNumberParam('id') || 0; + this.categoryId = CoreNavigator.getRouteNumberParam('id') || 0; this.fetchCategories().finally(() => { this.categoriesLoaded = true; @@ -60,7 +60,7 @@ export class CoreCoursesCategoriesPage implements OnInit { */ protected async fetchCategories(): Promise { try{ - const categories: CoreCategoryData[] = await CoreCourses.instance.getCategories(this.categoryId, true); + const categories: CoreCategoryData[] = await CoreCourses.getCategories(this.categoryId, true); this.currentCategory = undefined; @@ -81,19 +81,19 @@ export class CoreCoursesCategoriesPage implements OnInit { return a.depth > b.depth ? 1 : -1; }); - this.categories = CoreUtils.instance.formatTree(categories, 'parent', 'id', this.categoryId); + this.categories = CoreUtils.formatTree(categories, 'parent', 'id', this.categoryId); if (this.currentCategory) { this.title = this.currentCategory.name; try { - this.courses = await CoreCourses.instance.getCoursesByField('category', this.categoryId); + this.courses = await CoreCourses.getCoursesByField('category', this.categoryId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.courses.errorloadcourses', true); + CoreDomUtils.showErrorModalDefault(error, 'core.courses.errorloadcourses', true); } } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.courses.errorloadcategories', true); + CoreDomUtils.showErrorModalDefault(error, 'core.courses.errorloadcategories', true); } } @@ -105,10 +105,10 @@ export class CoreCoursesCategoriesPage implements OnInit { refreshCategories(refresher?: CustomEvent): void { const promises: Promise[] = []; - promises.push(CoreCourses.instance.invalidateUserCourses()); - promises.push(CoreCourses.instance.invalidateCategories(this.categoryId, true)); - promises.push(CoreCourses.instance.invalidateCoursesByField('category', this.categoryId)); - promises.push(CoreSites.instance.getCurrentSite()!.invalidateConfig()); + promises.push(CoreCourses.invalidateUserCourses()); + promises.push(CoreCourses.invalidateCategories(this.categoryId, true)); + promises.push(CoreCourses.invalidateCoursesByField('category', this.categoryId)); + promises.push(CoreSites.getCurrentSite()!.invalidateConfig()); Promise.all(promises).finally(() => { this.fetchCategories().finally(() => { diff --git a/src/core/features/courses/pages/course-preview/course-preview.ts b/src/core/features/courses/pages/course-preview/course-preview.ts index c5893a08d..1bad9c1ee 100644 --- a/src/core/features/courses/pages/course-preview/course-preview.ts +++ b/src/core/features/courses/pages/course-preview/course-preview.ts @@ -79,8 +79,8 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { protected modalCtrl: ModalController, protected zone: NgZone, ) { - this.isMobile = CoreApp.instance.isMobile(); - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); + this.isMobile = CoreApp.isMobile(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); if (this.downloadCourseEnabled) { // Listen for status change in course. @@ -88,7 +88,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { if (data.courseId == this.course!.id || data.courseId == CoreCourseProvider.ALL_COURSES_CLEARED) { this.updateCourseStatus(data.status); } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } } @@ -96,22 +96,22 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { * View loaded. */ async ngOnInit(): Promise { - this.course = CoreNavigator.instance.getRouteParam('course'); - this.avoidOpenCourse = !!CoreNavigator.instance.getRouteBooleanParam('avoidOpenCourse'); + this.course = CoreNavigator.getRouteParam('course'); + this.avoidOpenCourse = !!CoreNavigator.getRouteBooleanParam('avoidOpenCourse'); if (!this.course) { - CoreNavigator.instance.back(); + CoreNavigator.back(); return; } - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); const currentSiteUrl = currentSite && currentSite.getURL(); this.paypalEnabled = this.course!.enrollmentmethods?.indexOf('paypal') > -1; - this.enrolUrl = CoreTextUtils.instance.concatenatePaths(currentSiteUrl!, 'enrol/index.php?id=' + this.course!.id); - this.courseUrl = CoreTextUtils.instance.concatenatePaths(currentSiteUrl!, 'course/view.php?id=' + this.course!.id); - this.paypalReturnUrl = CoreTextUtils.instance.concatenatePaths(currentSiteUrl!, 'enrol/paypal/return.php'); + this.enrolUrl = CoreTextUtils.concatenatePaths(currentSiteUrl!, 'enrol/index.php?id=' + this.course!.id); + this.courseUrl = CoreTextUtils.concatenatePaths(currentSiteUrl!, 'course/view.php?id=' + this.course!.id); + this.paypalReturnUrl = CoreTextUtils.concatenatePaths(currentSiteUrl!, 'enrol/paypal/return.php'); if (this.course.overviewfiles.length > 0) { this.courseImageUrl = this.course.overviewfiles[0].fileurl; } @@ -122,21 +122,21 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { if (this.downloadCourseEnabled) { // Determine course prefetch icon. - this.prefetchCourseData = await CoreCourseHelper.instance.getCourseStatusIconAndTitle(this.course!.id); + this.prefetchCourseData = await CoreCourseHelper.getCourseStatusIconAndTitle(this.course!.id); if (this.prefetchCourseData.loading) { // Course is being downloaded. Get the download promise. - const promise = CoreCourseHelper.instance.getCourseDownloadPromise(this.course!.id); + const promise = CoreCourseHelper.getCourseDownloadPromise(this.course!.id); if (promise) { // There is a download promise. If it fails, show an error. promise.catch((error) => { if (!this.pageDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); } }); } else { // No download, this probably means that the app was closed while downloading. Set previous status. - CoreCourse.instance.setCoursePreviousStatus(this.course!.id); + CoreCourse.setCoursePreviousStatus(this.course!.id); } } } @@ -159,7 +159,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { this.guestInstanceId = method?.id; if (this.guestInstanceId) { - const info = await CoreCourses.instance.getCourseGuestEnrolmentInfo(this.guestInstanceId); + const info = await CoreCourses.getCourseGuestEnrolmentInfo(this.guestInstanceId); if (!info.status) { // Not active, reject. throw Error('Guest access is not enabled.'); @@ -179,7 +179,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { this.selfEnrolInstances = []; try { - this.enrolmentMethods = await CoreCourses.instance.getCourseEnrolmentMethods(this.course!.id); + this.enrolmentMethods = await CoreCourses.getCourseEnrolmentMethods(this.course!.id); this.enrolmentMethods.forEach((method) => { if (method.type === 'self') { @@ -189,7 +189,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { } }); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting enrolment data'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting enrolment data'); } try { @@ -197,13 +197,13 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { // Check if user is enrolled in the course. try { - course = await CoreCourses.instance.getUserCourse(this.course!.id); + course = await CoreCourses.getUserCourse(this.course!.id); this.isEnrolled = true; } catch { // The user is not enrolled in the course. Use getCourses to see if it's an admin/manager and can see the course. this.isEnrolled = false; - course = await CoreCourses.instance.getCourse(this.course!.id); + course = await CoreCourses.getCourse(this.course!.id); } // Success retrieving the course, we can assume the user has permissions to view it. @@ -219,11 +219,11 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { } } - if (!CoreSites.instance.getCurrentSite()?.isVersionGreaterEqualThan('3.7')) { + if (!CoreSites.getCurrentSite()?.isVersionGreaterEqualThan('3.7')) { try { - const available = await CoreCourses.instance.isGetCoursesByFieldAvailableInSite(); + const available = await CoreCourses.isGetCoursesByFieldAvailableInSite(); if (available) { - const course = await CoreCourses.instance.getCourseByField('id', this.course!.id); + const course = await CoreCourses.getCourseByField('id', this.course!.id); this.course!.customfields = course.customfields; } @@ -244,7 +244,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { return; } - CoreCourseHelper.instance.openCourse(this.course!); + CoreCourseHelper.openCourse(this.course!); } /** @@ -252,7 +252,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { */ async paypalEnrol(): Promise { // We cannot control browser in browser. - if (!this.isMobile || !CoreSites.instance.getCurrentSite()) { + if (!this.isMobile || !CoreSites.getCurrentSite()) { return; } @@ -283,7 +283,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { }; // Open the enrolment page in InAppBrowser. - const window = await CoreSites.instance.getCurrentSite()!.openInAppWithAutoLogin(this.enrolUrl); + const window = await CoreSites.getCurrentSite()!.openInAppWithAutoLogin(this.enrolUrl); // Observe loaded pages in the InAppBrowser to check if the enrol process has ended. const inAppLoadSubscription = window.on('loadstart').subscribe((event) => { @@ -304,7 +304,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { */ async selfEnrolClicked(instanceId: number): Promise { try { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.courses.confirmselfenrol')); + await CoreDomUtils.showConfirm(Translate.instant('core.courses.confirmselfenrol')); this.selfEnrolInCourse('', instanceId); } catch { @@ -320,10 +320,10 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { * @return Promise resolved when self enrolled. */ async selfEnrolInCourse(password: string, instanceId: number): Promise { - const modal = await CoreDomUtils.instance.showModalLoading('core.loading', true); + const modal = await CoreDomUtils.showModalLoading('core.loading', true); try { - await CoreCourses.instance.selfEnrol(this.course!.id, password, instanceId); + await CoreCourses.selfEnrol(this.course!.id, password, instanceId); // Close modal and refresh data. this.isEnrolled = true; @@ -338,7 +338,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { courseId: this.course!.id, course: this.course, action: CoreCoursesProvider.ACTION_ENROL, - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); }); modal?.dismiss(); @@ -370,7 +370,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { } } - CoreDomUtils.instance.showErrorModalDefault(error, 'core.courses.errorselfenrol', true); + CoreDomUtils.showErrorModalDefault(error, 'core.courses.errorselfenrol', true); } } @@ -382,15 +382,15 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { async refreshData(refresher?: CustomEvent): Promise { const promises: Promise[] = []; - promises.push(CoreCourses.instance.invalidateUserCourses()); - promises.push(CoreCourses.instance.invalidateCourse(this.course!.id)); - promises.push(CoreCourses.instance.invalidateCourseEnrolmentMethods(this.course!.id)); - promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions(this.course!.id)); - if (CoreSites.instance.getCurrentSite() && !CoreSites.instance.getCurrentSite()!.isVersionGreaterEqualThan('3.7')) { - promises.push(CoreCourses.instance.invalidateCoursesByField('id', this.course!.id)); + promises.push(CoreCourses.invalidateUserCourses()); + promises.push(CoreCourses.invalidateCourse(this.course!.id)); + promises.push(CoreCourses.invalidateCourseEnrolmentMethods(this.course!.id)); + promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions(this.course!.id)); + if (CoreSites.getCurrentSite() && !CoreSites.getCurrentSite()!.isVersionGreaterEqualThan('3.7')) { + promises.push(CoreCourses.invalidateCoursesByField('id', this.course!.id)); } if (this.guestInstanceId) { - promises.push(CoreCourses.instance.invalidateCourseGuestEnrolmentInfo(this.guestInstanceId)); + promises.push(CoreCourses.invalidateCourseGuestEnrolmentInfo(this.guestInstanceId)); } await Promise.all(promises).finally(() => this.getCourse()).finally(() => { @@ -404,7 +404,7 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { * @param status Status to show. */ protected updateCourseStatus(status: string): void { - this.prefetchCourseData = CoreCourseHelper.instance.getCourseStatusIconAndTitleFromStatus(status); + this.prefetchCourseData = CoreCourseHelper.getCourseStatusIconAndTitleFromStatus(status); } /** @@ -420,13 +420,13 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { // Check if user is enrolled in the course. try { - CoreCourses.instance.invalidateUserCourses(); + CoreCourses.invalidateUserCourses(); } catch { // Ignore errors. } try { - CoreCourses.instance.getUserCourse(this.course!.id); + CoreCourses.getUserCourse(this.course!.id); } catch { // Not enrolled, wait a bit and try again. if (this.pageDestroyed || (Date.now() - this.waitStart > 60000)) { @@ -450,9 +450,9 @@ export class CoreCoursesCoursePreviewPage implements OnInit, OnDestroy { * Prefetch the course. */ prefetchCourse(): void { - /* @todo CoreCourseHelper.instance.confirmAndPrefetchCourse(this.prefetchCourseData, this.course).catch((error) => { + /* @todo CoreCourseHelper.confirmAndPrefetchCourse(this.prefetchCourseData, this.course).catch((error) => { if (!this.pageDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); } });*/ } diff --git a/src/core/features/courses/pages/dashboard/dashboard.ts b/src/core/features/courses/pages/dashboard/dashboard.ts index 26514f819..c8f13330d 100644 --- a/src/core/features/courses/pages/dashboard/dashboard.ts +++ b/src/core/features/courses/pages/dashboard/dashboard.ts @@ -51,18 +51,18 @@ export class CoreCoursesDashboardPage implements OnInit, OnDestroy { * Initialize the component. */ ngOnInit(): void { - this.searchEnabled = !CoreCourses.instance.isSearchCoursesDisabledInSite(); - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.searchEnabled = !CoreCourses.isSearchCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); // Refresh the enabled flags if site is updated. this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { - this.searchEnabled = !CoreCourses.instance.isSearchCoursesDisabledInSite(); - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.searchEnabled = !CoreCourses.isSearchCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); this.switchDownload(this.downloadEnabled && this.downloadCourseEnabled && this.downloadCoursesEnabled); - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); this.loadContent(); } @@ -73,20 +73,20 @@ export class CoreCoursesDashboardPage implements OnInit, OnDestroy { * @return Promise resolved when done. */ protected async loadContent(): Promise { - const available = await CoreCoursesDashboard.instance.isAvailable(); + const available = await CoreCoursesDashboard.isAvailable(); if (available) { - this.userId = CoreSites.instance.getCurrentSiteUserId(); + this.userId = CoreSites.getCurrentSiteUserId(); try { - this.blocks = await CoreCoursesDashboard.instance.getDashboardBlocks(); + this.blocks = await CoreCoursesDashboard.getDashboardBlocks(); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); // Cannot get the blocks, just show dashboard if needed. this.loadFallbackBlocks(); } - } else if (!CoreCoursesDashboard.instance.isDisabledInSite()) { + } else if (!CoreCoursesDashboard.isDisabledInSite()) { // Not available, but not disabled either. Use fallback. this.loadFallbackBlocks(); } else { @@ -122,7 +122,7 @@ export class CoreCoursesDashboardPage implements OnInit, OnDestroy { refreshDashboard(refresher: CustomEvent): void { const promises: Promise[] = []; - promises.push(CoreCoursesDashboard.instance.invalidateDashboardBlocks()); + promises.push(CoreCoursesDashboard.invalidateDashboardBlocks()); // Invalidate the blocks. this.blocksComponents?.forEach((blockComponent) => { @@ -169,7 +169,7 @@ export class CoreCoursesDashboardPage implements OnInit, OnDestroy { * Go to search courses. */ async openSearch(): Promise { - CoreNavigator.instance.navigateToSitePath('/courses/search'); + CoreNavigator.navigateToSitePath('/courses/search'); } /** diff --git a/src/core/features/courses/pages/my-courses/my-courses.ts b/src/core/features/courses/pages/my-courses/my-courses.ts index 3f3b95fbd..d09a985fc 100644 --- a/src/core/features/courses/pages/my-courses/my-courses.ts +++ b/src/core/features/courses/pages/my-courses/my-courses.ts @@ -66,22 +66,22 @@ export class CoreCoursesMyCoursesPage implements OnInit, OnDestroy { } }, - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); // Refresh the enabled flags if site is updated. this.siteUpdatedObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { - this.searchEnabled = !CoreCourses.instance.isSearchCoursesDisabledInSite(); - this.downloadAllCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); - }, CoreSites.instance.getCurrentSiteId()); + this.searchEnabled = !CoreCourses.isSearchCoursesDisabledInSite(); + this.downloadAllCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); + }, CoreSites.getCurrentSiteId()); } /** * Component being initialized. */ ngOnInit(): void { - this.searchEnabled = !CoreCourses.instance.isSearchCoursesDisabledInSite(); - this.downloadAllCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.searchEnabled = !CoreCourses.isSearchCoursesDisabledInSite(); + this.downloadAllCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); this.fetchCourses().finally(() => { this.coursesLoaded = true; @@ -95,15 +95,15 @@ export class CoreCoursesMyCoursesPage implements OnInit, OnDestroy { */ protected async fetchCourses(): Promise { try { - const courses: CoreEnrolledCourseDataWithExtraInfoAndOptions[] = await CoreCourses.instance.getUserCourses(); + const courses: CoreEnrolledCourseDataWithExtraInfoAndOptions[] = await CoreCourses.getUserCourses(); const courseIds = courses.map((course) => course.id); this.courseIds = courseIds.join(','); - await CoreCoursesHelper.instance.loadCoursesExtraInfo(courses); + await CoreCoursesHelper.loadCoursesExtraInfo(courses); - if (CoreCourses.instance.canGetAdminAndNavOptions()) { - const options = await CoreCourses.instance.getCoursesAdminAndNavOptions(courseIds); + if (CoreCourses.canGetAdminAndNavOptions()) { + const options = await CoreCourses.getCoursesAdminAndNavOptions(courseIds); courses.forEach((course) => { course.navOptions = options.navOptions[course.id]; course.admOptions = options.admOptions[course.id]; @@ -114,7 +114,7 @@ export class CoreCoursesMyCoursesPage implements OnInit, OnDestroy { this.filteredCourses = this.courses; this.filter = ''; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.courses.errorloadcourses', true); + CoreDomUtils.showErrorModalDefault(error, 'core.courses.errorloadcourses', true); } } @@ -126,10 +126,10 @@ export class CoreCoursesMyCoursesPage implements OnInit, OnDestroy { refreshCourses(refresher: CustomEvent): void { const promises: Promise[] = []; - promises.push(CoreCourses.instance.invalidateUserCourses()); - promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions()); + promises.push(CoreCourses.invalidateUserCourses()); + promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions()); if (this.courseIds) { - promises.push(CoreCourses.instance.invalidateCoursesByField('ids', this.courseIds)); + promises.push(CoreCourses.invalidateCoursesByField('ids', this.courseIds)); } Promise.all(promises).finally(() => { @@ -182,12 +182,12 @@ export class CoreCoursesMyCoursesPage implements OnInit, OnDestroy { this.downloadAllCoursesLoading = true; try { - await CoreCourseHelper.instance.confirmAndPrefetchCourses(this.courses, (progress) => { + await CoreCourseHelper.confirmAndPrefetchCourses(this.courses, (progress) => { this.downloadAllCoursesBadge = progress.count + ' / ' + progress.total; }); } catch (error) { if (!this.isDestroyed) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); } } @@ -199,7 +199,7 @@ export class CoreCoursesMyCoursesPage implements OnInit, OnDestroy { * Go to search courses. */ openSearch(): void { - CoreNavigator.instance.navigate('courses/search'); + CoreNavigator.navigate('courses/search'); } /** diff --git a/src/core/features/courses/pages/search/search.ts b/src/core/features/courses/pages/search/search.ts index 57c04555e..651aee76f 100644 --- a/src/core/features/courses/pages/search/search.ts +++ b/src/core/features/courses/pages/search/search.ts @@ -44,7 +44,7 @@ export class CoreCoursesSearchPage { this.page = 0; this.total = 0; - const modal = await CoreDomUtils.instance.showModalLoading('core.searching', true); + const modal = await CoreDomUtils.showModalLoading('core.searching', true); this.searchCourses().finally(() => { modal.dismiss(); }); @@ -80,7 +80,7 @@ export class CoreCoursesSearchPage { this.loadMoreError = false; try { - const response = await CoreCourses.instance.search(this.currentSearch, this.page); + const response = await CoreCourses.search(this.currentSearch, this.page); if (this.page === 0) { this.courses = response.courses; @@ -93,7 +93,7 @@ export class CoreCoursesSearchPage { this.canLoadMore = this.courses.length < this.total; } catch (error) { this.loadMoreError = true; // Set to prevent infinite calls with infinite-loading. - CoreDomUtils.instance.showErrorModalDefault(error, 'core.courses.errorsearching', true); + CoreDomUtils.showErrorModalDefault(error, 'core.courses.errorsearching', true); } } diff --git a/src/core/features/courses/services/courses-helper.ts b/src/core/features/courses/services/courses-helper.ts index b0b826698..158cf018d 100644 --- a/src/core/features/courses/services/courses-helper.ts +++ b/src/core/features/courses/services/courses-helper.ts @@ -33,12 +33,12 @@ export class CoreCoursesHelperProvider { * @return Promise resolved with the list of courses and the category. */ async getCoursesForPopover(courseId?: number): Promise<{courses: Partial[]; categoryId?: number}> { - const courses: Partial[] = await CoreCourses.instance.getUserCourses(false); + const courses: Partial[] = await CoreCourses.getUserCourses(false); // Add "All courses". courses.unshift({ id: -1, - fullname: Translate.instance.instant('core.fulllistofcourses'), + fullname: Translate.instant('core.fulllistofcourses'), categoryid: -1, }); @@ -109,15 +109,15 @@ export class CoreCoursesHelperProvider { return; })); - if (CoreCourses.instance.isGetCoursesByFieldAvailable() && (loadCategoryNames || + if (CoreCourses.isGetCoursesByFieldAvailable() && (loadCategoryNames || (typeof courses[0].overviewfiles == 'undefined' && typeof courses[0].displayname == 'undefined'))) { const courseIds = courses.map((course) => course.id).join(','); courseInfoAvailable = true; // Get the extra data for the courses. - promises.push(CoreCourses.instance.getCoursesByField('ids', courseIds).then((coursesInfos) => { - coursesInfo = CoreUtils.instance.arrayToObject(coursesInfos, 'id'); + promises.push(CoreCourses.getCoursesByField('ids', courseIds).then((coursesInfos) => { + coursesInfo = CoreUtils.arrayToObject(coursesInfos, 'id'); return; })); @@ -136,7 +136,7 @@ export class CoreCoursesHelperProvider { * @return course colors RGB. */ protected async loadCourseSiteColors(): Promise<(string | undefined)[]> { - const site = CoreSites.instance.getCurrentSite(); + const site = CoreSites.getCurrentSite(); const colors: (string | undefined)[] = []; if (site?.isVersionGreaterEqualThan('3.8')) { @@ -188,7 +188,7 @@ export class CoreCoursesHelperProvider { loadCategoryNames: boolean = false, ): Promise { - let courses: CoreEnrolledCourseDataWithOptions[] = await CoreCourses.instance.getUserCourses(); + let courses: CoreEnrolledCourseDataWithOptions[] = await CoreCourses.getUserCourses(); if (courses.length <= 0) { return []; } @@ -196,9 +196,9 @@ export class CoreCoursesHelperProvider { const promises: Promise[] = []; const courseIds = courses.map((course) => course.id); - if (CoreCourses.instance.canGetAdminAndNavOptions()) { + if (CoreCourses.canGetAdminAndNavOptions()) { // Load course options of the course. - promises.push(CoreCourses.instance.getCoursesAdminAndNavOptions(courseIds).then((options) => { + promises.push(CoreCourses.getCoursesAdminAndNavOptions(courseIds).then((options) => { courses.forEach((course) => { course.navOptions = options.navOptions[course.id]; course.admOptions = options.admOptions[course.id]; @@ -262,7 +262,7 @@ export class CoreCoursesHelperProvider { } try { - const completion = await AddonCourseCompletion.instance.getCompletion(course.id); + const completion = await AddonCourseCompletion.getCompletion(course.id); course.completed = completion?.completed; } catch { @@ -276,7 +276,7 @@ export class CoreCoursesHelperProvider { } -export class CoreCoursesHelper extends makeSingleton(CoreCoursesHelperProvider) { } +export const CoreCoursesHelper = makeSingleton(CoreCoursesHelperProvider); /** * Course with colors info and course image. diff --git a/src/core/features/courses/services/courses.ts b/src/core/features/courses/services/courses.ts index 28cdf1e72..f61ba2376 100644 --- a/src/core/features/courses/services/courses.ts +++ b/src/core/features/courses/services/courses.ts @@ -59,8 +59,8 @@ export class CoreCoursesProvider { * @return Whether current site supports getting course options. */ canGetAdminAndNavOptions(): boolean { - return CoreSites.instance.wsAvailableInCurrentSite('core_course_get_user_navigation_options') && - CoreSites.instance.wsAvailableInCurrentSite('core_course_get_user_administration_options'); + return CoreSites.wsAvailableInCurrentSite('core_course_get_user_navigation_options') && + CoreSites.wsAvailableInCurrentSite('core_course_get_user_administration_options'); } /** @@ -76,7 +76,7 @@ export class CoreCoursesProvider { addSubcategories: boolean = false, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Get parent when id is the root category. const criteriaKey = categoryId == 0 ? 'parent' : 'id'; @@ -117,7 +117,7 @@ export class CoreCoursesProvider { * @return Promise resolved with the list of course IDs. */ protected async getCourseIdsForAdminAndNavOptions(courseIds: number[], siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const siteHomeId = site.getSiteHomeId(); if (courseIds.length == 1) { @@ -144,7 +144,7 @@ export class CoreCoursesProvider { * @return Promise resolved with the list of course IDs. */ async getCourseIdsIfEnrolled(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const siteHomeId = site.getSiteHomeId(); try { @@ -185,7 +185,7 @@ export class CoreCoursesProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isDownloadCourseDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isDownloadCoursesDisabledInSite(site); } @@ -197,7 +197,7 @@ export class CoreCoursesProvider { * @return Whether it's disabled. */ isDownloadCourseDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !site || site.isOfflineDisabled() || site.isFeatureDisabled('NoDelegate_CoreCourseDownload'); } @@ -209,7 +209,7 @@ export class CoreCoursesProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isDownloadCoursesDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isDownloadCoursesDisabledInSite(site); } @@ -221,7 +221,7 @@ export class CoreCoursesProvider { * @return Whether it's disabled. */ isDownloadCoursesDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !site || site.isOfflineDisabled() || site.isFeatureDisabled('NoDelegate_CoreCoursesDownload'); } @@ -233,7 +233,7 @@ export class CoreCoursesProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isMyCoursesDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isMyCoursesDisabledInSite(site); } @@ -245,7 +245,7 @@ export class CoreCoursesProvider { * @return Whether it's disabled. */ isMyCoursesDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !site || site.isFeatureDisabled('CoreMainMenuDelegate_CoreCourses'); } @@ -257,7 +257,7 @@ export class CoreCoursesProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isSearchCoursesDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isSearchCoursesDisabledInSite(site); } @@ -269,7 +269,7 @@ export class CoreCoursesProvider { * @return Whether it's disabled. */ isSearchCoursesDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !site || site.isFeatureDisabled('CoreCourseOptionsDelegate_search'); } @@ -299,7 +299,7 @@ export class CoreCoursesProvider { * @return Promise resolved with the methods. */ async getCourseEnrolmentMethods(id: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreEnrolGetCourseEnrolmentMethodsWSParams = { courseid: id, @@ -330,7 +330,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the info is retrieved. */ async getCourseGuestEnrolmentInfo(instanceId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: EnrolGuestGetInstanceInfoWSParams = { instanceid: instanceId, }; @@ -371,7 +371,7 @@ export class CoreCoursesProvider { return []; } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCourseGetCoursesWSParams = { options: { @@ -477,11 +477,11 @@ export class CoreCoursesProvider { value: string | number = '', siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const originalValue = value; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const fieldParams = await this.fixCoursesByFieldParams(field, value, siteId); @@ -554,7 +554,7 @@ export class CoreCoursesProvider { customFieldValue: string, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCourseGetEnrolledCoursesByTimelineClassificationWSParams = { classification: 'customfield', customfieldname: customFieldName, @@ -583,7 +583,7 @@ export class CoreCoursesProvider { * @since 3.2 */ isGetCoursesByFieldAvailable(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site && site.wsAvailable('core_course_get_courses_by_field'); } @@ -596,7 +596,7 @@ export class CoreCoursesProvider { * @since 3.2 */ async isGetCoursesByFieldAvailableInSite(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isGetCoursesByFieldAvailable(site); } @@ -615,7 +615,7 @@ export class CoreCoursesProvider { navOptions: CoreCourseUserAdminOrNavOptionCourseIndexed; admOptions: CoreCourseUserAdminOrNavOptionCourseIndexed; }> { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Get the list of courseIds to use based on the param. courseIds = await this.getCourseIdsForAdminAndNavOptions(courseIds, siteId); @@ -672,7 +672,7 @@ export class CoreCoursesProvider { return {}; } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCourseGetUserAdminOrNavOptionsWSParams = { courseids: courseIds, @@ -720,7 +720,7 @@ export class CoreCoursesProvider { return {}; } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCourseGetUserAdminOrNavOptionsWSParams = { courseids: courseIds, @@ -798,14 +798,14 @@ export class CoreCoursesProvider { siteId?: string, strategy?: CoreSitesReadingStrategy, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const userId = site.getUserId(); const wsParams: CoreEnrolGetUsersCoursesWSParams = { userid: userId, }; const strategyPreSets = strategy - ? CoreSites.instance.getReadingStrategyPreSets(strategy) + ? CoreSites.getReadingStrategyPreSets(strategy) : { omitExpires: !!preferCache }; const preSets = { @@ -894,7 +894,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCategories(categoryId: number, addSubcategories?: boolean, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCategoriesCacheKey(categoryId, addSubcategories)); } @@ -918,7 +918,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCourseEnrolmentMethods(id: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCourseEnrolmentMethodsCacheKey(id)); } @@ -931,7 +931,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCourseGuestEnrolmentInfo(instanceId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCourseGuestEnrolmentInfoCacheKey(instanceId)); } @@ -944,7 +944,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCoursesAdminAndNavOptions(courseIds: number[], siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const ids = await this.getCourseIdsForAdminAndNavOptions(courseIds, siteId); @@ -963,7 +963,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCourses(ids: number[], siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getCoursesCacheKey(ids)); } @@ -977,13 +977,13 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateCoursesByField(field: string = '', value: number | string = '', siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const result = await this.fixCoursesByFieldParams(field, value, siteId); field = result.field; value = result.value; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.invalidateWsCacheForKey(this.getCoursesByFieldCacheKey(field, value)); } @@ -995,7 +995,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserAdministrationOptions(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUserAdministrationOptionsCommonCacheKey()); } @@ -1008,7 +1008,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserAdministrationOptionsForCourses(courseIds: number[], siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserAdministrationOptionsCacheKey(courseIds)); } @@ -1020,7 +1020,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserCourses(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserCoursesCacheKey()); } @@ -1032,7 +1032,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserNavigationOptions(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUserNavigationOptionsCommonCacheKey()); } @@ -1045,7 +1045,7 @@ export class CoreCoursesProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserNavigationOptionsForCourses(courseIds: number[], siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserNavigationOptionsCacheKey(courseIds)); } @@ -1076,7 +1076,7 @@ export class CoreCoursesProvider { perPage: number = CoreCoursesProvider.SEARCH_PER_PAGE, siteId?: string, ): Promise<{ total: number; courses: CoreCourseBasicSearchedData[] }> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCourseSearchCoursesWSParams = { criterianame: 'search', criteriavalue: text, @@ -1104,7 +1104,7 @@ export class CoreCoursesProvider { */ async selfEnrol(courseId: number, password: string = '', instanceId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: EnrolSelfEnrolUserWSParams = { courseid: courseId, @@ -1148,7 +1148,7 @@ export class CoreCoursesProvider { * @return Promise resolved when done. */ async setFavouriteCourse(courseId: number, favourite: boolean, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreCourseSetFavouriteCoursesWSParams = { courses: [ @@ -1164,7 +1164,7 @@ export class CoreCoursesProvider { } -export class CoreCourses extends makeSingleton(CoreCoursesProvider) {} +export const CoreCourses = makeSingleton(CoreCoursesProvider); /** * Data sent to the EVENT_MY_COURSES_UPDATED. diff --git a/src/core/features/courses/services/dashboard.ts b/src/core/features/courses/services/dashboard.ts index fbf19c3d7..fd13fa7d1 100644 --- a/src/core/features/courses/services/dashboard.ts +++ b/src/core/features/courses/services/dashboard.ts @@ -46,7 +46,7 @@ export class CoreCoursesDashboardProvider { * @since 3.6 */ async getDashboardBlocks(userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreBlockGetDashboardBlocksWSParams = { returncontents: true, @@ -71,7 +71,7 @@ export class CoreCoursesDashboardProvider { * @return Promise resolved when the data is invalidated. */ async invalidateDashboardBlocks(userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return await site.invalidateWsCacheForKey(this.getDashboardBlocksCacheKey(userId)); } @@ -84,7 +84,7 @@ export class CoreCoursesDashboardProvider { * @since 3.6 */ async isAvailable(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // First check if it's disabled. if (this.isDisabledInSite(site)) { @@ -101,7 +101,7 @@ export class CoreCoursesDashboardProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isDisabledInSite(site); } @@ -113,14 +113,14 @@ export class CoreCoursesDashboardProvider { * @return Whether it's disabled. */ isDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('CoreMainMenuDelegate_CoreCoursesDashboard'); } } -export class CoreCoursesDashboard extends makeSingleton(CoreCoursesDashboardProvider) {} +export const CoreCoursesDashboard = makeSingleton(CoreCoursesDashboardProvider); /** diff --git a/src/core/features/courses/services/handlers/course-link.ts b/src/core/features/courses/services/handlers/course-link.ts index bd58a16bf..692ec547b 100644 --- a/src/core/features/courses/services/handlers/course-link.ts +++ b/src/core/features/courses/services/handlers/course-link.ts @@ -81,12 +81,12 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler return [{ action: (siteId): void => { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); - if (siteId == CoreSites.instance.getCurrentSiteId()) { + siteId = siteId || CoreSites.getCurrentSiteId(); + if (siteId == CoreSites.getCurrentSiteId()) { // Check if we already are in the course index page. - if (CoreCourse.instance.currentViewIsCourse(courseId)) { + if (CoreCourse.currentViewIsCourse(courseId)) { // Current view is this course, just select the contents tab. - CoreCourse.instance.selectCourseTab('', pageParams); + CoreCourse.selectCourseTab('', pageParams); return; } else { @@ -96,7 +96,7 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler } } else { // Make the course the new history root (to avoid "loops" in history). - CoreCourseHelper.instance.getAndOpenCourse(courseId, pageParams, siteId); + CoreCourseHelper.getAndOpenCourse(courseId, pageParams, siteId); } }, }]; @@ -120,7 +120,7 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler } // Get the course id of Site Home. - return CoreSites.instance.getSiteHomeId(siteId).then((siteHomeId) => courseId != siteHomeId); + return CoreSites.getSiteHomeId(siteId).then((siteHomeId) => courseId != siteHomeId); } /** @@ -132,12 +132,12 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler * @return Promise resolved when done. */ protected async actionEnrol(courseId: number, url: string, pageParams: Params): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); let course: CoreCourseAnyCourseData | { id: number } | undefined; // Check if user is enrolled in the course. try { - course = await CoreCourses.instance.getUserCourse(courseId); + course = await CoreCourses.getUserCourse(courseId); } catch { course = await this.checkSelfUserCanSelfEnrolOrAccess(courseId, url, modal); } @@ -145,7 +145,7 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler // Check if we need to retrieve the course. if (!course) { try { - const data = await CoreCourseHelper.instance.getCourse(courseId); + const data = await CoreCourseHelper.getCourse(courseId); course = data.course; } catch { // Cannot get course, return a "fake". @@ -156,7 +156,7 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler modal.dismiss(); // Now open the course. - CoreCourseHelper.instance.openCourse(course, pageParams); + CoreCourseHelper.openCourse(course, pageParams); } /** @@ -181,10 +181,10 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler // The user can self enrol. If it's not a enrolment URL we'll ask for confirmation. if (!isEnrolUrl) { try { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.courses.confirmselfenrol')); + await CoreDomUtils.showConfirm(Translate.instant('core.courses.confirmselfenrol')); } catch { // User cancelled. Check if the user can view the course contents (guest access or similar). - await CoreCourse.instance.getSections(courseId, false, true); + await CoreCourse.getSections(courseId, false, true); return; } @@ -195,7 +195,7 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler return this.selfEnrol(courseId); } catch (error) { if (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } throw error; @@ -203,26 +203,26 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler }, async (error) => { // Can't self enrol. Check if the user can view the course contents (guest access or similar). try { - await CoreCourse.instance.getSections(courseId, false, true); + await CoreCourse.getSections(courseId, false, true); } catch { // Error. Show error message and allow the user to open the link in browser. modal.dismiss(); if (error) { - error = CoreTextUtils.instance.getErrorMessageFromError(error) || error; + error = CoreTextUtils.getErrorMessageFromError(error) || error; } if (!error) { - error = Translate.instance.instant('core.courses.notenroled'); + error = Translate.instant('core.courses.notenroled'); } - const body = CoreTextUtils.instance.buildSeveralParagraphsMessage( - [error, Translate.instance.instant('core.confirmopeninbrowser')], + const body = CoreTextUtils.buildSeveralParagraphsMessage( + [error, Translate.instant('core.confirmopeninbrowser')], ); try { - await CoreDomUtils.instance.showConfirm(body); + await CoreDomUtils.showConfirm(body); - CoreSites.instance.getCurrentSite()?.openInBrowserWithAutoLogin(url); + CoreSites.getCurrentSite()?.openInBrowserWithAutoLogin(url); } catch { // User cancelled. }; @@ -243,7 +243,7 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler protected async canSelfEnrol(courseId: number): Promise { // Check that the course has self enrolment enabled. - const methods = await CoreCourses.instance.getCourseEnrolmentMethods(courseId); + const methods = await CoreCourses.getCourseEnrolmentMethods(courseId); let isSelfEnrolEnabled = false; let instances = 0; methods.forEach((method) => { @@ -267,13 +267,13 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler * @return Promise resolved when the user is enrolled, rejected otherwise. */ protected async selfEnrol(courseId: number, password?: string): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { - await CoreCourses.instance.selfEnrol(courseId, password); + await CoreCourses.selfEnrol(courseId, password); // Success self enrolling the user, invalidate the courses list. - await CoreUtils.instance.ignoreErrors(CoreCourses.instance.invalidateUserCourses()); + await CoreUtils.ignoreErrors(CoreCourses.invalidateUserCourses()); try { // Sometimes the list of enrolled courses takes a while to be updated. Wait for it. @@ -286,16 +286,16 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler if (error && error.code === CoreCoursesProvider.ENROL_INVALID_KEY) { // Invalid password. Allow the user to input password. - const title = Translate.instance.instant('core.courses.selfenrolment'); + const title = Translate.instant('core.courses.selfenrolment'); const body = ' '; // Empty message. - const placeholder = Translate.instance.instant('core.courses.password'); + const placeholder = Translate.instant('core.courses.password'); if (typeof password != 'undefined') { // The user attempted a password. Show an error message. - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } - password = await CoreDomUtils.instance.showPrompt(body, title, placeholder); + password = await CoreDomUtils.showPrompt(body, title, placeholder); return this.selfEnrol(courseId, password); } else { @@ -317,9 +317,9 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler } // Check if user is enrolled in the course. - await CoreUtils.instance.ignoreErrors(CoreCourses.instance.invalidateUserCourses()); + await CoreUtils.ignoreErrors(CoreCourses.invalidateUserCourses()); try { - return CoreCourses.instance.getUserCourse(courseId); + return CoreCourses.getUserCourse(courseId); } catch { // Not enrolled, wait a bit and try again. @@ -339,4 +339,4 @@ export class CoreCoursesCourseLinkHandlerService extends CoreContentLinksHandler } -export class CoreCoursesCourseLinkHandler extends makeSingleton(CoreCoursesCourseLinkHandlerService) {} +export const CoreCoursesCourseLinkHandler = makeSingleton(CoreCoursesCourseLinkHandlerService); diff --git a/src/core/features/courses/services/handlers/courses-index-link.ts b/src/core/features/courses/services/handlers/courses-index-link.ts index 52179a846..1f273fa87 100644 --- a/src/core/features/courses/services/handlers/courses-index-link.ts +++ b/src/core/features/courses/services/handlers/courses-index-link.ts @@ -44,7 +44,7 @@ export class CoreCoursesIndexLinkHandlerService extends CoreContentLinksHandlerB action: (siteId): void => { let pageName = CoreCoursesMyCoursesHomeHandlerService.PAGE_NAME; - if (CoreCourses.instance.isGetCoursesByFieldAvailable()) { + if (CoreCourses.isGetCoursesByFieldAvailable()) { if (params.categoryid) { pageName += '/categories/' + params.categoryid; } else { @@ -55,11 +55,11 @@ export class CoreCoursesIndexLinkHandlerService extends CoreContentLinksHandlerB pageName += '/my'; } - CoreNavigator.instance.navigateToSitePath(pageName, { siteId }); + CoreNavigator.navigateToSitePath(pageName, { siteId }); }, }]; } } -export class CoreCoursesIndexLinkHandler extends makeSingleton(CoreCoursesIndexLinkHandlerService) {} +export const CoreCoursesIndexLinkHandler = makeSingleton(CoreCoursesIndexLinkHandlerService); diff --git a/src/core/features/courses/services/handlers/dashboard-home.ts b/src/core/features/courses/services/handlers/dashboard-home.ts index b4f4e8ce0..998a6fac7 100644 --- a/src/core/features/courses/services/handlers/dashboard-home.ts +++ b/src/core/features/courses/services/handlers/dashboard-home.ts @@ -51,13 +51,13 @@ export class CoreDashboardHomeHandlerService implements CoreMainMenuHomeHandler let dashboardAvailable = false; // Check if blocks and 3.6 dashboard is enabled. - promises.push(CoreBlockDelegate.instance.areBlocksDisabled(siteId).then((disabled) => { + promises.push(CoreBlockDelegate.areBlocksDisabled(siteId).then((disabled) => { blocksEnabled = !disabled; return; })); - promises.push(CoreCoursesDashboard.instance.isAvailable().then((available) => { + promises.push(CoreCoursesDashboard.isAvailable().then((available) => { dashboardAvailable = available; return; @@ -66,13 +66,13 @@ export class CoreDashboardHomeHandlerService implements CoreMainMenuHomeHandler await Promise.all(promises); if (dashboardAvailable && blocksEnabled) { - const blocks = await CoreCoursesDashboard.instance.getDashboardBlocks(undefined, siteId); + const blocks = await CoreCoursesDashboard.getDashboardBlocks(undefined, siteId); - return CoreBlockDelegate.instance.hasSupportedBlock(blocks); + return CoreBlockDelegate.hasSupportedBlock(blocks); } // Check if my overview is enabled. If it's enabled we will fake enabled blocks. - const timelineEnabled = await AddonBlockTimeline.instance.isAvailable(); + const timelineEnabled = await AddonBlockTimeline.isAvailable(); return timelineEnabled && blocksEnabled; } @@ -94,4 +94,4 @@ export class CoreDashboardHomeHandlerService implements CoreMainMenuHomeHandler } -export class CoreDashboardHomeHandler extends makeSingleton(CoreDashboardHomeHandlerService) {} +export const CoreDashboardHomeHandler = makeSingleton(CoreDashboardHomeHandlerService); diff --git a/src/core/features/courses/services/handlers/dashboard-link.ts b/src/core/features/courses/services/handlers/dashboard-link.ts index 571de7db8..b506909cc 100644 --- a/src/core/features/courses/services/handlers/dashboard-link.ts +++ b/src/core/features/courses/services/handlers/dashboard-link.ts @@ -37,7 +37,7 @@ export class CoreCoursesDashboardLinkHandlerService extends CoreContentLinksHand return [{ action: (siteId): void => { // Use redirect to select the tab. - CoreNavigator.instance.navigateToSitePath(CoreDashboardHomeHandlerService.PAGE_NAME, { siteId }); + CoreNavigator.navigateToSitePath(CoreDashboardHomeHandlerService.PAGE_NAME, { siteId }); }, }]; } @@ -49,9 +49,9 @@ export class CoreCoursesDashboardLinkHandlerService extends CoreContentLinksHand * @return Whether the handler is enabled for the URL and site. */ async isEnabled(siteId: string): Promise { - return CoreDashboardHomeHandler.instance.isEnabledForSite(siteId); + return CoreDashboardHomeHandler.isEnabledForSite(siteId); } } -export class CoreCoursesDashboardLinkHandler extends makeSingleton(CoreCoursesDashboardLinkHandlerService) {} +export const CoreCoursesDashboardLinkHandler = makeSingleton(CoreCoursesDashboardLinkHandlerService); diff --git a/src/core/features/courses/services/handlers/enrol-push-click.ts b/src/core/features/courses/services/handlers/enrol-push-click.ts index e141ad109..0731e2463 100644 --- a/src/core/features/courses/services/handlers/enrol-push-click.ts +++ b/src/core/features/courses/services/handlers/enrol-push-click.ts @@ -38,7 +38,7 @@ export class CoreCoursesEnrolPushClickHandlerService implements CorePushNotifica * @return Whether the notification click is handled by this handler */ async handles(notification: CorePushNotificationsNotificationBasicData): Promise { - return CoreUtils.instance.isTrueOrOne(notification.notif) && notification.moodlecomponent?.indexOf('enrol_') === 0 && + return CoreUtils.isTrueOrOne(notification.notif) && notification.moodlecomponent?.indexOf('enrol_') === 0 && notification.name == 'expiry_notification'; } @@ -51,10 +51,10 @@ export class CoreCoursesEnrolPushClickHandlerService implements CorePushNotifica async handleClick(notification: CoreCoursesEnrolNotificationData): Promise { const courseId = notification.courseid; - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { - const result = await CoreCourseHelper.instance.getCourse(courseId, notification.site); + const result = await CoreCourseHelper.getCourse(courseId, notification.site); const params: Params = { course: result.course, @@ -73,9 +73,9 @@ export class CoreCoursesEnrolPushClickHandlerService implements CorePushNotifica page = 'courses/preview';; } - await CoreNavigator.instance.navigateToSitePath(page, { params, siteId: notification.site }); + await CoreNavigator.navigateToSitePath(page, { params, siteId: notification.site }); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting course.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting course.'); } finally { modal.dismiss(); } @@ -83,7 +83,7 @@ export class CoreCoursesEnrolPushClickHandlerService implements CorePushNotifica } -export class CoreCoursesEnrolPushClickHandler extends makeSingleton(CoreCoursesEnrolPushClickHandlerService) {} +export const CoreCoursesEnrolPushClickHandler = makeSingleton(CoreCoursesEnrolPushClickHandlerService); type CoreCoursesEnrolNotificationData = CorePushNotificationsNotificationBasicData & { courseid: number; // Course ID related to the notification. diff --git a/src/core/features/courses/services/handlers/my-courses-home.ts b/src/core/features/courses/services/handlers/my-courses-home.ts index 4cfd9a9a4..f1f134a6c 100644 --- a/src/core/features/courses/services/handlers/my-courses-home.ts +++ b/src/core/features/courses/services/handlers/my-courses-home.ts @@ -47,15 +47,15 @@ export class CoreCoursesMyCoursesHomeHandlerService implements CoreMainMenuHomeH * @return Whether or not the handler is enabled on a site level. */ async isEnabledForSite(siteId?: string): Promise { - const disabled = await CoreCourses.instance.isMyCoursesDisabled(siteId); + const disabled = await CoreCourses.isMyCoursesDisabled(siteId); if (disabled) { return false; } - const blocks = await CoreCoursesDashboard.instance.getDashboardBlocks(undefined, siteId); + const blocks = await CoreCoursesDashboard.getDashboardBlocks(undefined, siteId); - return !CoreBlockDelegate.instance.hasSupportedBlock(blocks)&& !CoreSiteHome.instance.isAvailable(siteId); + return !CoreBlockDelegate.hasSupportedBlock(blocks)&& !CoreSiteHome.isAvailable(siteId); } /** @@ -75,4 +75,4 @@ export class CoreCoursesMyCoursesHomeHandlerService implements CoreMainMenuHomeH } -export class CoreCoursesMyCoursesHomeHandler extends makeSingleton(CoreCoursesMyCoursesHomeHandlerService) {} +export const CoreCoursesMyCoursesHomeHandler = makeSingleton(CoreCoursesMyCoursesHomeHandlerService); diff --git a/src/core/features/courses/services/handlers/request-push-click.ts b/src/core/features/courses/services/handlers/request-push-click.ts index 237573dbd..523f8135d 100644 --- a/src/core/features/courses/services/handlers/request-push-click.ts +++ b/src/core/features/courses/services/handlers/request-push-click.ts @@ -43,7 +43,7 @@ export class CoreCoursesRequestPushClickHandlerService implements CorePushNotifi */ async handles(notification: CorePushNotificationsNotificationBasicData): Promise { // Don't support 'courserequestrejected', that way the app will open the notifications page. - return CoreUtils.instance.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'moodle' && + return CoreUtils.isTrueOrOne(notification.notif) && notification.moodlecomponent == 'moodle' && (notification.name == 'courserequested' || notification.name == 'courserequestapproved'); } @@ -58,8 +58,8 @@ export class CoreCoursesRequestPushClickHandlerService implements CorePushNotifi if (notification.name == 'courserequested') { // Feature not supported in the app, open in browser. - const site = await CoreSites.instance.getSite(notification.site); - const url = CoreTextUtils.instance.concatenatePaths(site.getURL(), 'course/pending.php'); + const site = await CoreSites.getSite(notification.site); + const url = CoreTextUtils.concatenatePaths(site.getURL(), 'course/pending.php'); await site.openInBrowserWithAutoLogin(url); @@ -67,12 +67,12 @@ export class CoreCoursesRequestPushClickHandlerService implements CorePushNotifi } // Open the course. - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); - await CoreUtils.instance.ignoreErrors(CoreCourses.instance.invalidateUserCourses(notification.site)); + await CoreUtils.ignoreErrors(CoreCourses.invalidateUserCourses(notification.site)); try { - const result = await CoreCourseHelper.instance.getCourse(courseId, notification.site); + const result = await CoreCourseHelper.getCourse(courseId, notification.site); const params: Params = { course: result.course, }; @@ -86,9 +86,9 @@ export class CoreCoursesRequestPushClickHandlerService implements CorePushNotifi page = 'courses/preview'; } - await CoreNavigator.instance.navigateToSitePath(page, { params, siteId: notification.site }); + await CoreNavigator.navigateToSitePath(page, { params, siteId: notification.site }); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting course.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting course.'); } finally { modal.dismiss(); } @@ -96,7 +96,7 @@ export class CoreCoursesRequestPushClickHandlerService implements CorePushNotifi } -export class CoreCoursesRequestPushClickHandler extends makeSingleton(CoreCoursesRequestPushClickHandlerService) {} +export const CoreCoursesRequestPushClickHandler = makeSingleton(CoreCoursesRequestPushClickHandlerService); type CoreCoursesRequestNotificationData = CorePushNotificationsNotificationBasicData & { courseid: number; // Course ID related to the notification. diff --git a/src/core/features/editor/components/rich-text-editor/rich-text-editor.ts b/src/core/features/editor/components/rich-text-editor/rich-text-editor.ts index ac8e1a15b..31024970e 100644 --- a/src/core/features/editor/components/rich-text-editor/rich-text-editor.ts +++ b/src/core/features/editor/components/rich-text-editor/rich-text-editor.ts @@ -141,17 +141,17 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn * Component being initialized. */ ngOnInit(): void { - this.canScanQR = CoreUtils.instance.canScanQR(); - this.isPhone = Platform.instance.is('mobile') && !Platform.instance.is('tablet'); + this.canScanQR = CoreUtils.canScanQR(); + this.isPhone = Platform.is('mobile') && !Platform.is('tablet'); this.toolbarHidden = this.isPhone; - this.direction = Platform.instance.isRTL ? 'rtl' : 'ltr'; + this.direction = Platform.isRTL ? 'rtl' : 'ltr'; } /** * Init editor. */ async ngAfterContentInit(): Promise { - this.rteEnabled = await CoreDomUtils.instance.isRichTextEditorEnabled(); + this.rteEnabled = await CoreDomUtils.isRichTextEditorEnabled(); // Setup the editor. this.editorElement = this.editor?.nativeElement as HTMLDivElement; @@ -218,7 +218,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn // Save a draft so the original content is saved. this.lastDraft = newValue; - CoreEditorOffline.instance.saveDraft( + CoreEditorOffline.saveDraft( this.contextLevel || '', this.contextInstanceId || 0, this.elementId || '', @@ -240,9 +240,9 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn }); // Change the side when the language changes. - this.languageChangedSubscription = Translate.instance.onLangChange.subscribe(() => { + this.languageChangedSubscription = Translate.onLangChange.subscribe(() => { setTimeout(() => { - this.direction = Platform.instance.isRTL ? 'rtl' : 'ltr'; + this.direction = Platform.isRTL ? 'rtl' : 'ltr'; }); }); } @@ -255,11 +255,11 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn protected maximizeEditorSize(): Promise { // this.content.resize(); - const deferred = CoreUtils.instance.promiseDefer(); + const deferred = CoreUtils.promiseDefer(); setTimeout(async () => { - let contentVisibleHeight = await CoreDomUtils.instance.getContentHeight(this.content); - if (!CoreApp.instance.isAndroid()) { + let contentVisibleHeight = await CoreDomUtils.getContentHeight(this.content); + if (!CoreApp.isAndroid()) { // In Android we ignore the keyboard height because it is not part of the web view. contentVisibleHeight -= this.kbHeight; } @@ -274,11 +274,11 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn // Editor is ready, adjust Height if needed. let height; - if (CoreApp.instance.isAndroid()) { + if (CoreApp.isAndroid()) { // In Android we ignore the keyboard height because it is not part of the web view. - const contentHeight = await CoreDomUtils.instance.getContentHeight(this.content); + const contentHeight = await CoreDomUtils.getContentHeight(this.content); height = contentHeight - this.getSurroundingHeight(this.element); - } else if (CoreApp.instance.isIOS() && this.kbHeight > 0 && CoreApp.instance.getPlatformMajorVersion() < 12) { + } else if (CoreApp.isIOS() && this.kbHeight > 0 && CoreApp.getPlatformMajorVersion() < 12) { // Keyboard open in iOS 11 or previous. The window height changes when the keyboard is open. height = window.innerHeight - this.getSurroundingHeight(this.element); @@ -289,12 +289,12 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn } else { // Header is fixed, use the content to calculate the editor height. - const contentHeight = await CoreDomUtils.instance.getContentHeight(this.content); + const contentHeight = await CoreDomUtils.getContentHeight(this.content); height = contentHeight - this.kbHeight - this.getSurroundingHeight(this.element); } if (height > this.minHeight) { - this.element.style.height = CoreDomUtils.instance.formatPixelsSize(height - 1); + this.element.style.height = CoreDomUtils.formatPixelsSize(height - 1); } else { this.element.style.height = ''; } @@ -321,7 +321,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn for (let x = 0; x < parent.children.length; x++) { const child = parent.children[x]; if (child.tagName && child != element) { - height += CoreDomUtils.instance.getElementHeight(child, false, true, true); + height += CoreDomUtils.getElementHeight(child, false, true, true); } } } @@ -329,14 +329,14 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn } const computedStyle = getComputedStyle(element); - height += CoreDomUtils.instance.getComputedStyleMeasure(computedStyle, 'paddingTop') + - CoreDomUtils.instance.getComputedStyleMeasure(computedStyle, 'paddingBottom'); + height += CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingTop') + + CoreDomUtils.getComputedStyleMeasure(computedStyle, 'paddingBottom'); if (element.parentElement?.tagName == 'ION-CONTENT') { const cs2 = getComputedStyle(element); - height -= CoreDomUtils.instance.getComputedStyleMeasure(cs2, 'paddingTop') + - CoreDomUtils.instance.getComputedStyleMeasure(cs2, 'paddingBottom'); + height -= CoreDomUtils.getComputedStyleMeasure(cs2, 'paddingTop') + + CoreDomUtils.getComputedStyleMeasure(cs2, 'paddingBottom'); } return height; @@ -540,14 +540,14 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn * Treating videos and audios in here is complex, so if a user manually adds one he won't be able to play it in the editor. */ protected treatExternalContent(): void { - if (!CoreSites.instance.isLoggedIn() || !this.editorElement) { + if (!CoreSites.isLoggedIn() || !this.editorElement) { // Only treat external content if the user is logged in. return; } const elements = Array.from(this.editorElement.querySelectorAll('img')); - const siteId = CoreSites.instance.getCurrentSiteId(); - const canDownloadFiles = CoreSites.instance.getCurrentSite()!.canDownloadFiles(); + const siteId = CoreSites.getCurrentSiteId(); + const canDownloadFiles = CoreSites.getCurrentSite()!.canDownloadFiles(); elements.forEach(async (el) => { if (el.getAttribute('data-original-src')) { // Already treated. @@ -556,14 +556,14 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn const url = el.src; - if (!url || !CoreUrlUtils.instance.isDownloadableUrl(url) || - (!canDownloadFiles && CoreUrlUtils.instance.isPluginFileUrl(url))) { + if (!url || !CoreUrlUtils.isDownloadableUrl(url) || + (!canDownloadFiles && CoreUrlUtils.isPluginFileUrl(url))) { // Nothing to treat. return; } // Check if it's downloaded. - const finalUrl = await CoreFilepool.instance.getSrcByUrl(siteId, url, this.component, this.componentId); + const finalUrl = await CoreFilepool.getSrcByUrl(siteId, url, this.component, this.componentId); // Check again if it's already treated, this function can be called concurrently more than once. if (!el.getAttribute('data-original-src')) { @@ -760,7 +760,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn const selection = window.getSelection()?.toString(); // When RTE is focused with a whole paragraph in desktop the stopBubble will not fire click. - if (CoreApp.instance.isMobile() || !this.rteEnabled || document.activeElement != this.editorElement || selection == '') { + if (CoreApp.isMobile() || !this.rteEnabled || document.activeElement != this.editorElement || selection == '') { this.stopBubble(event); } } @@ -804,7 +804,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn const length = await this.toolbarSlides.length(); - const width = CoreDomUtils.instance.getElementWidth(this.toolbar.nativeElement); + const width = CoreDomUtils.getElementWidth(this.toolbar.nativeElement); if (!width) { // Width is not available yet, try later. @@ -876,8 +876,8 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn * @return {boolean} Whether it should auto save drafts. */ protected shouldAutoSaveDrafts(): boolean { - return !!CoreSites.instance.getCurrentSite() && - (typeof this.autoSave == 'undefined' || CoreUtils.instance.isTrueOrOne(this.autoSave)) && + return !!CoreSites.getCurrentSite() && + (typeof this.autoSave == 'undefined' || CoreUtils.isTrueOrOne(this.autoSave)) && typeof this.contextLevel != 'undefined' && typeof this.contextInstanceId != 'undefined' && typeof this.elementId != 'undefined'; @@ -890,7 +890,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn */ protected async restoreDraft(): Promise { try { - const entry = await CoreEditorOffline.instance.resumeDraft( + const entry = await CoreEditorOffline.resumeDraft( this.contextLevel || '', this.contextInstanceId || 0, this.elementId || '', @@ -947,7 +947,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn } try { - await CoreEditorOffline.instance.saveDraft( + await CoreEditorOffline.saveDraft( this.contextLevel || '', this.contextInstanceId || 0, this.elementId || '', @@ -975,7 +975,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn if (data.form && form && data.form == form) { try { - await CoreEditorOffline.instance.deleteDraft( + await CoreEditorOffline.deleteDraft( this.contextLevel || '', this.contextInstanceId || 0, this.elementId || '', @@ -985,7 +985,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn // Error deleting draft. Shouldn't happen. } } - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } /** @@ -1015,7 +1015,7 @@ export class CoreEditorRichTextEditorComponent implements OnInit, AfterContentIn this.stopBubble(event); // Scan for a QR code. - const text = await CoreUtils.instance.scanQR(); + const text = await CoreUtils.scanQR(); if (text) { document.execCommand('insertText', false, text); diff --git a/src/core/features/editor/services/editor-offline.ts b/src/core/features/editor/services/editor-offline.ts index f9dda9ea3..810893090 100644 --- a/src/core/features/editor/services/editor-offline.ts +++ b/src/core/features/editor/services/editor-offline.ts @@ -51,7 +51,7 @@ export class CoreEditorOfflineProvider { siteId?: string, ): Promise { try { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const params = this.fixDraftPrimaryData(contextLevel, contextInstanceId, elementId, extraParams); @@ -81,7 +81,7 @@ export class CoreEditorOfflineProvider { contextlevel: contextLevel, contextinstanceid: contextInstanceId, elementid: elementId, - extraparams: CoreUtils.instance.sortAndStringify(extraParams || {}), + extraparams: CoreUtils.sortAndStringify(extraParams || {}), }; } @@ -103,7 +103,7 @@ export class CoreEditorOfflineProvider { siteId?: string, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const params = this.fixDraftPrimaryData(contextLevel, contextInstanceId, elementId, extraParams); @@ -138,7 +138,7 @@ export class CoreEditorOfflineProvider { // There is a draft stored. Update its page instance. try { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); entry.pageinstance = pageInstance; entry.timemodified = Date.now(); @@ -219,7 +219,7 @@ export class CoreEditorOfflineProvider { } } - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const data: CoreEditorDraft = this.fixDraftPrimaryData(contextLevel, contextInstanceId, elementId, extraParams); @@ -236,4 +236,4 @@ export class CoreEditorOfflineProvider { } -export class CoreEditorOffline extends makeSingleton(CoreEditorOfflineProvider) {} +export const CoreEditorOffline = makeSingleton(CoreEditorOfflineProvider); diff --git a/src/core/features/emulator/components/capture-media/capture-media.ts b/src/core/features/emulator/components/capture-media/capture-media.ts index a096932cb..10efb2035 100644 --- a/src/core/features/emulator/components/capture-media/capture-media.ts +++ b/src/core/features/emulator/components/capture-media/capture-media.ts @@ -116,10 +116,10 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { this.title = 'core.captureimage'; } - this.isCordovaAudioCapture = CoreApp.instance.isMobile() && this.isAudio; + this.isCordovaAudioCapture = CoreApp.isMobile() && this.isAudio; if (this.isCordovaAudioCapture) { - this.extension = Platform.instance.is('ios') ? 'wav' : 'aac'; + this.extension = Platform.is('ios') ? 'wav' : 'aac'; this.returnDataUrl = false; } } @@ -131,19 +131,19 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { */ protected async initCordovaMediaPlugin(): Promise { this.filePath = this.getFilePath(); - let absolutePath = CoreTextUtils.instance.concatenatePaths(CoreFile.instance.getBasePathInstant(), this.filePath); + let absolutePath = CoreTextUtils.concatenatePaths(CoreFile.getBasePathInstant(), this.filePath); - if (Platform.instance.is('ios')) { + if (Platform.is('ios')) { // In iOS we need to remove the file:// part. absolutePath = absolutePath.replace(/^file:\/\//, ''); } try { // First create the file. - this.fileEntry = await CoreFile.instance.createFile(this.filePath); + this.fileEntry = await CoreFile.createFile(this.filePath); // Now create the media instance. - this.mediaFile = Media.instance.create(absolutePath); + this.mediaFile = Media.create(absolutePath); this.readyToCapture = true; this.previewMedia = this.previewAudio?.nativeElement; } catch (error) { @@ -368,7 +368,7 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { // Get the image from the video and set it to the canvas, using video width/height. const width = this.streamVideo?.nativeElement.videoWidth; const height = this.streamVideo?.nativeElement.videoHeight; - const loadingModal = await CoreDomUtils.instance.showModalLoading(); + const loadingModal = await CoreDomUtils.showModalLoading(); this.imgCanvas.nativeElement.width = width; @@ -392,7 +392,7 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { async cancel(): Promise { if (this.hasCaptured) { try { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.confirmcanceledit')); + await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); } catch { // Canceled. return; @@ -404,7 +404,7 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { if (this.isCordovaAudioCapture && this.filePath) { // Delete the tmp file. - CoreFile.instance.removeFile(this.filePath); + CoreFile.removeFile(this.filePath); } } @@ -429,7 +429,7 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { * @param data Data to return. */ dismissWithData(data?: [MediaFile] | string): void { - ModalController.instance.dismiss(data, 'success'); + ModalController.dismiss(data, 'success'); } /** @@ -443,7 +443,7 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { const isCamera = this.isImage && !this.isCaptureImage; const error = isCamera ? new CoreCanceledError(cameraMessage || message) : new CoreCaptureError(3, message); - ModalController.instance.dismiss(error, 'error'); + ModalController.dismiss(error, 'error'); } /** @@ -457,7 +457,7 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { const isCamera = this.isImage && !this.isCaptureImage; const error = isCamera ? new CoreError(cameraMessage || message) : new CoreCaptureError(code, message); - ModalController.instance.dismiss(error, 'error'); + ModalController.dismiss(error, 'error'); } /** @@ -473,13 +473,13 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { if (!this.mediaBlob && !this.isCordovaAudioCapture) { // Shouldn't happen. - CoreDomUtils.instance.showErrorModal('Please capture the media first.'); + CoreDomUtils.showErrorModal('Please capture the media first.'); return; } let fileEntry = this.fileEntry; - const loadingModal = await CoreDomUtils.instance.showModalLoading(); + const loadingModal = await CoreDomUtils.showModalLoading(); try { if (!this.isCordovaAudioCapture) { @@ -489,7 +489,7 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { throw new Error('Please capture the media first.'); } - fileEntry = await CoreFile.instance.writeFile(this.getFilePath(), this.mediaBlob); + fileEntry = await CoreFile.writeFile(this.getFilePath(), this.mediaBlob); } if (!fileEntry) { @@ -500,11 +500,11 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { this.dismissWithData(fileEntry.toURL()); } else { // The capture plugin should return a MediaFile, not a FileEntry. Convert it. - const metadata = await CoreFile.instance.getMetadata(fileEntry); + const metadata = await CoreFile.getMetadata(fileEntry); let mimetype: string | undefined; if (this.extension) { - mimetype = CoreMimetypeUtils.instance.getMimeType(this.extension); + mimetype = CoreMimetypeUtils.getMimeType(this.extension); } const mediaFile: MediaFile = { @@ -521,7 +521,7 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { this.dismissWithData([mediaFile]); } } catch (err) { - CoreDomUtils.instance.showErrorModal(err); + CoreDomUtils.showErrorModal(err); } finally { loadingModal.dismiss(); } @@ -533,9 +533,9 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { * @return Path. */ protected getFilePath(): string { - const fileName = this.type + '_' + CoreTimeUtils.instance.readableTimestamp() + '.' + this.extension; + const fileName = this.type + '_' + CoreTimeUtils.readableTimestamp() + '.' + this.extension; - return CoreTextUtils.instance.concatenatePaths(CoreFileProvider.TMPFOLDER, 'media/' + fileName); + return CoreTextUtils.concatenatePaths(CoreFileProvider.TMPFOLDER, 'media/' + fileName); } /** @@ -548,7 +548,7 @@ export class CoreEmulatorCaptureMediaComponent implements OnInit, OnDestroy { if (this.isCordovaAudioCapture) { this.mediaFile?.stopRecord(); if (this.previewMedia && this.fileEntry) { - this.previewMedia.src = CoreFile.instance.convertFileSrc(this.fileEntry.toURL()); + this.previewMedia.src = CoreFile.convertFileSrc(this.fileEntry.toURL()); } } else { this.streamVideo && this.streamVideo.nativeElement.pause(); diff --git a/src/core/features/emulator/services/camera.ts b/src/core/features/emulator/services/camera.ts index 39ee962ba..1aa4114e2 100644 --- a/src/core/features/emulator/services/camera.ts +++ b/src/core/features/emulator/services/camera.ts @@ -41,7 +41,7 @@ export class CameraMock extends Camera { * @return Promise resolved when captured. */ getPicture(options: CameraOptions): Promise { - return CoreEmulatorCaptureHelper.instance.captureMedia('image', options); + return CoreEmulatorCaptureHelper.captureMedia('image', options); } } diff --git a/src/core/features/emulator/services/capture-helper.ts b/src/core/features/emulator/services/capture-helper.ts index 7b9079727..daee4b3d7 100644 --- a/src/core/features/emulator/services/capture-helper.ts +++ b/src/core/features/emulator/services/capture-helper.ts @@ -101,7 +101,7 @@ export class CoreEmulatorCaptureHelperProvider { params.maxTime = options.duration * 1000; } - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: CoreEmulatorCaptureMediaComponent, cssClass: 'core-modal-fullscreen', componentProps: params, @@ -143,7 +143,7 @@ export class CoreEmulatorCaptureHelperProvider { if (result.mimetype) { // Found a supported mimetype in the mimetypes array, get the extension. - result.extension = CoreMimetypeUtils.instance.getExtension(result.mimetype); + result.extension = CoreMimetypeUtils.getExtension(result.mimetype); } else if (type == 'video') { // No mimetype found, use default extension. result.mimetype = this.videoMimeType; @@ -201,7 +201,7 @@ export class CoreEmulatorCaptureHelperProvider { } -export class CoreEmulatorCaptureHelper extends makeSingleton(CoreEmulatorCaptureHelperProvider) {} +export const CoreEmulatorCaptureHelper = makeSingleton(CoreEmulatorCaptureHelperProvider); export interface MockCameraOptions extends CameraOptions { mimetypes?: string[]; // Allowed mimetypes. diff --git a/src/core/features/emulator/services/emulator-helper.ts b/src/core/features/emulator/services/emulator-helper.ts index 618bc896a..70904d243 100644 --- a/src/core/features/emulator/services/emulator-helper.ts +++ b/src/core/features/emulator/services/emulator-helper.ts @@ -46,13 +46,13 @@ export class CoreEmulatorHelperProvider { window.FileTransferError = FileTransferErrorMock; promises.push(( this.file).load().then((basePath: string) => { - CoreFile.instance.setHTMLBasePath(basePath); + CoreFile.setHTMLBasePath(basePath); return; })); - return CoreUtils.instance.allPromises(promises); + return CoreUtils.allPromises(promises); } } diff --git a/src/core/features/emulator/services/file-opener.ts b/src/core/features/emulator/services/file-opener.ts index 94d5397f3..5c2c7c0b2 100644 --- a/src/core/features/emulator/services/file-opener.ts +++ b/src/core/features/emulator/services/file-opener.ts @@ -51,9 +51,9 @@ export class FileOpenerMock extends FileOpener { try { // Opening local files in browser just display a blank page. Convert the path to an object URL. - const fileEntry = await CoreFile.instance.getExternalFile(filePath); + const fileEntry = await CoreFile.getExternalFile(filePath); - const file = await CoreFile.instance.getFileObjectFromFileEntry(fileEntry); + const file = await CoreFile.getFileObjectFromFileEntry(fileEntry); window.open(window.URL.createObjectURL(file), '_blank'); } catch (error) { diff --git a/src/core/features/emulator/services/file-transfer.ts b/src/core/features/emulator/services/file-transfer.ts index da4e1bc34..5a6d40e9d 100644 --- a/src/core/features/emulator/services/file-transfer.ts +++ b/src/core/features/emulator/services/file-transfer.ts @@ -146,12 +146,12 @@ export class FileTransferObjectMock extends FileTransferObject { return; } - const basePath = CoreFile.instance.getBasePathInstant(); + const basePath = CoreFile.getBasePathInstant(); target = target.replace(basePath, ''); // Remove basePath from the target. target = target.replace(/%20/g, ' '); // Replace all %20 with spaces. // eslint-disable-next-line promise/catch-or-return - CoreFile.instance.writeFile(target, response).then(resolve, reject); + CoreFile.writeFile(target, response).then(resolve, reject); }; xhr.send(); @@ -254,7 +254,7 @@ export class FileTransferObjectMock extends FileTransferObject { responseText = response; } - return CoreTextUtils.instance.parseJSON(responseText, ''); + return CoreTextUtils.parseJSON(responseText, ''); } /** @@ -325,8 +325,8 @@ export class FileTransferObjectMock extends FileTransferObject { delete headers['Content-Type']; // Get the file to upload. - CoreFile.instance.getFile(fileUrl).then((fileEntry) => - CoreFile.instance.getFileObjectFromFileEntry(fileEntry)).then((file) => { + CoreFile.getFile(fileUrl).then((fileEntry) => + CoreFile.getFileObjectFromFileEntry(fileEntry)).then((file) => { // Use XMLHttpRequest instead of HttpClient to support onprogress and abort. const xhr = new XMLHttpRequest(); xhr.open(httpMethod || 'POST', url); diff --git a/src/core/features/emulator/services/file.ts b/src/core/features/emulator/services/file.ts index 1d8356936..bde3461bd 100644 --- a/src/core/features/emulator/services/file.ts +++ b/src/core/features/emulator/services/file.ts @@ -58,7 +58,7 @@ export class FileMock extends File { * @return Returns a Promise that resolves to true if the directory exists or rejects with an error. */ async checkDir(path: string, dir: string): Promise { - const fullPath = CoreTextUtils.instance.concatenatePaths(path, dir); + const fullPath = CoreTextUtils.concatenatePaths(path, dir); await this.resolveDirectoryUrl(fullPath); @@ -73,7 +73,7 @@ export class FileMock extends File { * @return Returns a Promise that resolves with a boolean or rejects with an error. */ async checkFile(path: string, file: string): Promise { - const entry = await this.resolveLocalFilesystemUrl(CoreTextUtils.instance.concatenatePaths(path, file)); + const entry = await this.resolveLocalFilesystemUrl(CoreTextUtils.concatenatePaths(path, file)); if (entry.isFile) { return true; @@ -144,7 +144,7 @@ export class FileMock extends File { async copyFileOrDir(sourcePath: string, sourceName: string, destPath: string, destName: string): Promise { const destFixed = this.fixPathAndName(destPath, destName); - const source = await this.resolveLocalFilesystemUrl(CoreTextUtils.instance.concatenatePaths(sourcePath, sourceName)); + const source = await this.resolveLocalFilesystemUrl(CoreTextUtils.concatenatePaths(sourcePath, sourceName)); const destParentDir = await this.resolveDirectoryUrl(destFixed.path); @@ -424,7 +424,7 @@ export class FileMock extends File { async moveFileOrDir(sourcePath: string, sourceName: string, destPath: string, destName: string): Promise { const destFixed = this.fixPathAndName(destPath, destName); - const source = await this.resolveLocalFilesystemUrl(CoreTextUtils.instance.concatenatePaths(sourcePath, sourceName)); + const source = await this.resolveLocalFilesystemUrl(CoreTextUtils.concatenatePaths(sourcePath, sourceName)); const destParentDir = await this.resolveDirectoryUrl(destFixed.path); @@ -440,7 +440,7 @@ export class FileMock extends File { */ protected fixPathAndName(path: string, name: string): {path: string; name: string} { - const fullPath = CoreTextUtils.instance.concatenatePaths(path, name); + const fullPath = CoreTextUtils.concatenatePaths(path, name); return { path: fullPath.substring(0, fullPath.lastIndexOf('/')), diff --git a/src/core/features/emulator/services/media-capture.ts b/src/core/features/emulator/services/media-capture.ts index b981ffbe0..213fa10d4 100644 --- a/src/core/features/emulator/services/media-capture.ts +++ b/src/core/features/emulator/services/media-capture.ts @@ -36,7 +36,7 @@ export class MediaCaptureMock extends MediaCapture { * @return Promise resolved when captured. */ captureAudio(options: CaptureAudioOptions): Promise { - return CoreEmulatorCaptureHelper.instance.captureMedia('audio', options); + return CoreEmulatorCaptureHelper.captureMedia('audio', options); } /** @@ -46,7 +46,7 @@ export class MediaCaptureMock extends MediaCapture { * @return Promise resolved when captured. */ captureImage(options: CaptureImageOptions): Promise { - return CoreEmulatorCaptureHelper.instance.captureMedia('captureimage', options); + return CoreEmulatorCaptureHelper.captureMedia('captureimage', options); } /** @@ -56,7 +56,7 @@ export class MediaCaptureMock extends MediaCapture { * @return Promise resolved when captured. */ captureVideo(options: CaptureVideoOptions): Promise { - return CoreEmulatorCaptureHelper.instance.captureMedia('video', options); + return CoreEmulatorCaptureHelper.captureMedia('video', options); } } diff --git a/src/core/features/emulator/services/zip.ts b/src/core/features/emulator/services/zip.ts index d81398d1a..0f2d24195 100644 --- a/src/core/features/emulator/services/zip.ts +++ b/src/core/features/emulator/services/zip.ts @@ -46,7 +46,7 @@ export class ZipMock extends Zip { await this.file.createDir(destination, folder, true); // Folder created, add it to the destination path. - destination = CoreTextUtils.instance.concatenatePaths(destination, folder); + destination = CoreTextUtils.concatenatePaths(destination, folder); } } @@ -106,7 +106,7 @@ export class ZipMock extends Zip { const fileData = await file.async('blob'); // File read and parent folder created, now write the file. - const parentFolder = CoreTextUtils.instance.concatenatePaths(destination, fileDir); + const parentFolder = CoreTextUtils.concatenatePaths(destination, fileDir); await this.file.writeFile(parentFolder, fileName, fileData, { replace: true }); } else { diff --git a/src/core/features/fileuploader/fileuploader.module.ts b/src/core/features/fileuploader/fileuploader.module.ts index 24ff3c977..092e8e1a9 100644 --- a/src/core/features/fileuploader/fileuploader.module.ts +++ b/src/core/features/fileuploader/fileuploader.module.ts @@ -31,11 +31,11 @@ import { CoreFileUploaderVideoHandler } from './services/handlers/video'; multi: true, deps: [], useFactory: () => () => { - CoreFileUploaderDelegate.instance.registerHandler(CoreFileUploaderAlbumHandler.instance); - CoreFileUploaderDelegate.instance.registerHandler(CoreFileUploaderAudioHandler.instance); - CoreFileUploaderDelegate.instance.registerHandler(CoreFileUploaderCameraHandler.instance); - CoreFileUploaderDelegate.instance.registerHandler(CoreFileUploaderVideoHandler.instance); - CoreFileUploaderDelegate.instance.registerHandler(CoreFileUploaderFileHandler.instance); + CoreFileUploaderDelegate.registerHandler(CoreFileUploaderAlbumHandler.instance); + CoreFileUploaderDelegate.registerHandler(CoreFileUploaderAudioHandler.instance); + CoreFileUploaderDelegate.registerHandler(CoreFileUploaderCameraHandler.instance); + CoreFileUploaderDelegate.registerHandler(CoreFileUploaderVideoHandler.instance); + CoreFileUploaderDelegate.registerHandler(CoreFileUploaderFileHandler.instance); }, }, ], diff --git a/src/core/features/fileuploader/services/fileuploader-delegate.ts b/src/core/features/fileuploader/services/fileuploader-delegate.ts index 8826fece6..7dcc70d74 100644 --- a/src/core/features/fileuploader/services/fileuploader-delegate.ts +++ b/src/core/features/fileuploader/services/fileuploader-delegate.ts @@ -196,4 +196,4 @@ export class CoreFileUploaderDelegateService extends CoreDelegate { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); - const result = await Chooser.instance.getFile(mimetypes ? mimetypes.join(',') : undefined); + const result = await Chooser.getFile(mimetypes ? mimetypes.join(',') : undefined); modal.dismiss(); @@ -83,13 +83,13 @@ export class CoreFileUploaderHelperProvider { } // Verify that the mimetype is supported. - const error = CoreFileUploader.instance.isInvalidMimetype(mimetypes, result.name, result.mediaType); + const error = CoreFileUploader.isInvalidMimetype(mimetypes, result.name, result.mediaType); if (error) { throw new CoreError(error); } - const options = CoreFileUploader.instance.getFileUploadOptions(result.uri, result.name, result.mediaType, true); + const options = CoreFileUploader.getFileUploadOptions(result.uri, result.name, result.mediaType, true); if (upload) { return this.uploadFile(result.uri, maxSize || -1, true, options); @@ -119,8 +119,8 @@ export class CoreFileUploaderHelperProvider { return; } - if (!allowOffline && !CoreApp.instance.isOnline()) { - throw new CoreError(Translate.instance.instant('core.fileuploader.errormustbeonlinetoupload')); + if (!allowOffline && !CoreApp.isOnline()) { + throw new CoreError(Translate.instant('core.fileuploader.errormustbeonlinetoupload')); } wifiThreshold = typeof wifiThreshold == 'undefined' ? CoreFileUploaderProvider.WIFI_SIZE_WARNING : wifiThreshold; @@ -128,15 +128,15 @@ export class CoreFileUploaderHelperProvider { CoreFileUploaderProvider.LIMITED_SIZE_WARNING : limitedThreshold; if (size < 0) { - return CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.fileuploader.confirmuploadunknownsize')); - } else if (size >= wifiThreshold || (CoreApp.instance.isNetworkAccessLimited() && size >= limitedThreshold)) { - const readableSize = CoreTextUtils.instance.bytesToSize(size, 2); + return CoreDomUtils.showConfirm(Translate.instant('core.fileuploader.confirmuploadunknownsize')); + } else if (size >= wifiThreshold || (CoreApp.isNetworkAccessLimited() && size >= limitedThreshold)) { + const readableSize = CoreTextUtils.bytesToSize(size, 2); - return CoreDomUtils.instance.showConfirm( - Translate.instance.instant('core.fileuploader.confirmuploadfile', { size: readableSize }), + return CoreDomUtils.showConfirm( + Translate.instant('core.fileuploader.confirmuploadfile', { size: readableSize }), ); } else if (alwaysConfirm) { - return CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.areyousure')); + return CoreDomUtils.showConfirm(Translate.instant('core.areyousure')); } } @@ -151,17 +151,17 @@ export class CoreFileUploaderHelperProvider { async copyAndUploadFile(file: IFile | File, upload?: boolean, name?: string): Promise { name = name || file.name; - const modal = await CoreDomUtils.instance.showModalLoading('core.fileuploader.readingfile', true); + const modal = await CoreDomUtils.showModalLoading('core.fileuploader.readingfile', true); let fileEntry: FileEntry | undefined; try { // Get unique name for the copy. - const newName = await CoreFile.instance.getUniqueNameInFolder(CoreFileProvider.TMPFOLDER, name); + const newName = await CoreFile.getUniqueNameInFolder(CoreFileProvider.TMPFOLDER, name); - const filePath = CoreTextUtils.instance.concatenatePaths(CoreFileProvider.TMPFOLDER, newName); + const filePath = CoreTextUtils.concatenatePaths(CoreFileProvider.TMPFOLDER, newName); // Write the data into the file. - fileEntry = await CoreFile.instance.writeFileDataInFile( + fileEntry = await CoreFile.writeFileDataInFile( file, filePath, (progress: CoreFileProgressEvent) => this.showProgressModal(modal, 'core.fileuploader.readingfileperc', progress), @@ -200,14 +200,14 @@ export class CoreFileUploaderHelperProvider { options?: CoreFileUploaderOptions, ): Promise { - const fileName = options?.fileName || CoreFile.instance.getFileAndDirectoryFromPath(path).name; + const fileName = options?.fileName || CoreFile.getFileAndDirectoryFromPath(path).name; // Check that size isn't too large. if (typeof maxSize != 'undefined' && maxSize != -1) { try { - const fileEntry = await CoreFile.instance.getExternalFile(path); + const fileEntry = await CoreFile.getExternalFile(path); - const fileData = await CoreFile.instance.getFileObjectFromFileEntry(fileEntry); + const fileData = await CoreFile.getFileObjectFromFileEntry(fileEntry); if (fileData.size > maxSize) { throw this.createMaxBytesError(maxSize, fileEntry.name); @@ -219,14 +219,14 @@ export class CoreFileUploaderHelperProvider { // File isn't too large. // Get a unique name in the folder to prevent overriding another file. - const newName = await CoreFile.instance.getUniqueNameInFolder(CoreFileProvider.TMPFOLDER, fileName, defaultExt); + const newName = await CoreFile.getUniqueNameInFolder(CoreFileProvider.TMPFOLDER, fileName, defaultExt); // Now move or copy the file. - const destPath = CoreTextUtils.instance.concatenatePaths(CoreFileProvider.TMPFOLDER, newName); + const destPath = CoreTextUtils.concatenatePaths(CoreFileProvider.TMPFOLDER, newName); if (shouldDelete) { - return CoreFile.instance.moveExternalFile(path, destPath); + return CoreFile.moveExternalFile(path, destPath); } else { - return CoreFile.instance.copyExternalFile(path, destPath); + return CoreFile.copyExternalFile(path, destPath); } } @@ -238,10 +238,10 @@ export class CoreFileUploaderHelperProvider { * @return Message. */ protected createMaxBytesError(maxSize: number, fileName: string): CoreError { - return new CoreError(Translate.instance.instant('core.fileuploader.maxbytesfile', { + return new CoreError(Translate.instant('core.fileuploader.maxbytesfile', { $a: { file: fileName, - size: CoreTextUtils.instance.bytesToSize(maxSize, 2), + size: CoreTextUtils.bytesToSize(maxSize, 2), }, })); } @@ -277,17 +277,17 @@ export class CoreFileUploaderHelperProvider { * @return File name, undefined if cannot get it. */ protected getChosenFileNameFromPath(result: ChooserResult): string | undefined { - const nameAndDir = CoreFile.instance.getFileAndDirectoryFromPath(result.uri); + const nameAndDir = CoreFile.getFileAndDirectoryFromPath(result.uri); if (!nameAndDir.name) { return; } - let extension = CoreMimetypeUtils.instance.getFileExtension(nameAndDir.name); + let extension = CoreMimetypeUtils.getFileExtension(nameAndDir.name); if (!extension) { // The URI doesn't have an extension, add it now. - extension = CoreMimetypeUtils.instance.getExtension(result.mediaType); + extension = CoreMimetypeUtils.getExtension(result.mediaType); if (extension) { nameAndDir.name += '.' + extension; @@ -343,21 +343,21 @@ export class CoreFileUploaderHelperProvider { ): Promise { // Create the cancel button and get the handlers to upload the file. const buttons: ActionSheetButton[] = [{ - text: Translate.instance.instant('core.cancel'), + text: Translate.instant('core.cancel'), role: 'cancel', handler: (): void => { // User cancelled the action sheet. this.filePickerClosed(); }, }]; - const handlers = CoreFileUploaderDelegate.instance.getHandlers(mimetypes); + const handlers = CoreFileUploaderDelegate.getHandlers(mimetypes); - this.filePickerDeferred = CoreUtils.instance.promiseDefer(); + this.filePickerDeferred = CoreUtils.promiseDefer(); // Create a button for each handler. handlers.forEach((handler) => { buttons.push({ - text: Translate.instance.instant(handler.title), + text: Translate.instant(handler.title), icon: handler.icon, cssClass: handler.class, handler: async (): Promise => { @@ -366,9 +366,9 @@ export class CoreFileUploaderHelperProvider { return false; } - if (!allowOffline && !CoreApp.instance.isOnline()) { + if (!allowOffline && !CoreApp.isOnline()) { // Not allowed, show error. - CoreDomUtils.instance.showErrorModal('core.fileuploader.errormustbeonlinetoupload', true); + CoreDomUtils.showErrorModal('core.fileuploader.errormustbeonlinetoupload', true); return false; } @@ -391,10 +391,10 @@ export class CoreFileUploaderHelperProvider { try { // The handler provided a path. First treat it like it's a relative path. - fileEntry = await CoreFile.instance.getFile(data.path); + fileEntry = await CoreFile.getFile(data.path); } catch (error) { // File not found, it's probably an absolute path. - fileEntry = await CoreFile.instance.getExternalFile(data.path); + fileEntry = await CoreFile.getExternalFile(data.path); } // File found, treat it. @@ -406,9 +406,9 @@ export class CoreFileUploaderHelperProvider { // Nothing received, fail. throw new CoreError('No file received'); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault( + CoreDomUtils.showErrorModalDefault( error, - Translate.instance.instant('core.fileuploader.errorreadingfile'), + Translate.instant('core.fileuploader.errorreadingfile'), ); return false; @@ -417,8 +417,8 @@ export class CoreFileUploaderHelperProvider { }); }); - this.actionSheet = await ActionSheetController.instance.create({ - header: title ? title : Translate.instance.instant('core.fileuploader.' + (upload ? 'uploadafile' : 'selectafile')), + this.actionSheet = await ActionSheetController.create({ + header: title ? title : Translate.instant('core.fileuploader.' + (upload ? 'uploadafile' : 'selectafile')), buttons: buttons, }); await this.actionSheet.present(); @@ -445,15 +445,15 @@ export class CoreFileUploaderHelperProvider { */ async showConfirmAndUploadInSite(fileEntry: FileEntry, deleteAfterUpload?: boolean, siteId?: string): Promise { try { - const file = await CoreFile.instance.getFileObjectFromFileEntry(fileEntry); + const file = await CoreFile.getFileObjectFromFileEntry(fileEntry); await this.confirmUploadFile(file.size); await this.uploadGenericFile(fileEntry.toURL(), file.name, file.type, deleteAfterUpload, siteId); - CoreDomUtils.instance.showToast('core.fileuploader.fileuploaded', true, undefined, 'core-toast-success'); + CoreDomUtils.showToast('core.fileuploader.fileuploaded', true, undefined, 'core-toast-success'); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.fileuploader.errorreadingfile', true); + CoreDomUtils.showErrorModalDefault(error, 'core.fileuploader.errorreadingfile', true); throw error; } @@ -473,8 +473,8 @@ export class CoreFileUploaderHelperProvider { // Error, not cancelled. this.logger.error('Error while recording audio/video', error); - const message = this.isNoAppError(error) ? Translate.instance.instant('core.fileuploader.errornoapp') : - (error.message || Translate.instance.instant(defaultMessage)); + const message = this.isNoAppError(error) ? Translate.instant('core.fileuploader.errornoapp') : + (error.message || Translate.instant(defaultMessage)); throw new CoreError(message); } else { @@ -545,18 +545,18 @@ export class CoreFileUploaderHelperProvider { let media: MediaFile; try { - const medias = isAudio ? await CoreFileUploader.instance.captureAudio(captureOptions) : - await CoreFileUploader.instance.captureVideo(captureOptions); + const medias = isAudio ? await CoreFileUploader.captureAudio(captureOptions) : + await CoreFileUploader.captureVideo(captureOptions); media = medias[0]; // We used limit 1, we only want 1 media. } catch (error) { - if (isAudio && this.isNoAppError(error) && CoreApp.instance.isMobile() && - (!Platform.instance.is('android') || CoreApp.instance.getPlatformMajorVersion() < 10)) { + if (isAudio && this.isNoAppError(error) && CoreApp.isMobile() && + (!Platform.is('android') || CoreApp.getPlatformMajorVersion() < 10)) { // No app to record audio, fallback to capture it ourselves. // In Android it will only be done in Android 9 or lower because there's a bug in the plugin. try { - media = await CoreFileUploader.instance.captureAudioInApp(); + media = await CoreFileUploader.captureAudioInApp(); } catch (error) { throw this.treatCaptureError(error, 'core.fileuploader.errorcapturingaudio'); // Throw the right error. } @@ -569,18 +569,18 @@ export class CoreFileUploaderHelperProvider { } let path = media.fullPath; - const error = CoreFileUploader.instance.isInvalidMimetype(mimetypes, path); // Verify that the mimetype is supported. + const error = CoreFileUploader.isInvalidMimetype(mimetypes, path); // Verify that the mimetype is supported. if (error) { throw new Error(error); } // Make sure the path has the protocol. In iOS it doesn't. - if (CoreApp.instance.isMobile() && path.indexOf('file://') == -1) { + if (CoreApp.isMobile() && path.indexOf('file://') == -1) { path = 'file://' + path; } - const options = CoreFileUploader.instance.getMediaUploadOptions(media); + const options = CoreFileUploader.getMediaUploadOptions(media); if (upload) { return this.uploadFile(path, maxSize || -1, true, options); @@ -608,7 +608,7 @@ export class CoreFileUploaderHelperProvider { deleteAfterUpload?: boolean, siteId?: string, ): Promise { - const options = CoreFileUploader.instance.getFileUploadOptions(uri, name, type, deleteAfterUpload); + const options = CoreFileUploader.getFileUploadOptions(uri, name, type, deleteAfterUpload); return this.uploadFile(uri, -1, false, options, siteId); } @@ -632,56 +632,56 @@ export class CoreFileUploaderHelperProvider { const options: CameraOptions = { quality: 50, - destinationType: Camera.instance.DestinationType.FILE_URI, + destinationType: Camera.DestinationType.FILE_URI, correctOrientation: true, }; if (fromAlbum) { - const imageSupported = !mimetypes || CoreUtils.instance.indexOfRegexp(mimetypes, /^image\//) > -1; - const videoSupported = !mimetypes || CoreUtils.instance.indexOfRegexp(mimetypes, /^video\//) > -1; + const imageSupported = !mimetypes || CoreUtils.indexOfRegexp(mimetypes, /^image\//) > -1; + const videoSupported = !mimetypes || CoreUtils.indexOfRegexp(mimetypes, /^video\//) > -1; - options.sourceType = Camera.instance.PictureSourceType.PHOTOLIBRARY; + options.sourceType = Camera.PictureSourceType.PHOTOLIBRARY; options.popoverOptions = { x: 10, y: 10, - width: Platform.instance.width() - 200, - height: Platform.instance.height() - 200, - arrowDir: Camera.instance.PopoverArrowDirection.ARROW_ANY, + width: Platform.width() - 200, + height: Platform.height() - 200, + arrowDir: Camera.PopoverArrowDirection.ARROW_ANY, }; // Determine the mediaType based on the mimetypes. if (imageSupported && !videoSupported) { - options.mediaType = Camera.instance.MediaType.PICTURE; + options.mediaType = Camera.MediaType.PICTURE; } else if (!imageSupported && videoSupported) { - options.mediaType = Camera.instance.MediaType.VIDEO; - } else if (CoreApp.instance.isIOS()) { + options.mediaType = Camera.MediaType.VIDEO; + } else if (CoreApp.isIOS()) { // Only get all media in iOS because in Android using this option allows uploading any kind of file. - options.mediaType = Camera.instance.MediaType.ALLMEDIA; + options.mediaType = Camera.MediaType.ALLMEDIA; } } else if (mimetypes) { if (mimetypes.indexOf('image/jpeg') > -1) { - options.encodingType = Camera.instance.EncodingType.JPEG; + options.encodingType = Camera.EncodingType.JPEG; } else if (mimetypes.indexOf('image/png') > -1) { - options.encodingType = Camera.instance.EncodingType.PNG; + options.encodingType = Camera.EncodingType.PNG; } } let path: string | undefined; try { - path = await CoreFileUploader.instance.getPicture(options); + path = await CoreFileUploader.getPicture(options); } catch (error) { const defaultError = fromAlbum ? 'core.fileuploader.errorgettingimagealbum' : 'core.fileuploader.errorcapturingimage'; throw this.treatImageError(error, defaultError); } - const error = CoreFileUploader.instance.isInvalidMimetype(mimetypes, path); // Verify that the mimetype is supported. + const error = CoreFileUploader.isInvalidMimetype(mimetypes, path); // Verify that the mimetype is supported. if (error) { throw new CoreError(error); } - const uploadOptions = CoreFileUploader.instance.getCameraUploadOptions(path, fromAlbum); + const uploadOptions = CoreFileUploader.getCameraUploadOptions(path, fromAlbum); if (upload) { return this.uploadFile(path, maxSize || -1, true, uploadOptions); @@ -710,13 +710,13 @@ export class CoreFileUploaderHelperProvider { allowOffline?: boolean, name?: string, ): Promise { - const file = await CoreFile.instance.getFileObjectFromFileEntry(fileEntry); + const file = await CoreFile.getFileObjectFromFileEntry(fileEntry); const result = await this.uploadFileObject(file, maxSize, upload, allowOffline, name); if (deleteAfter) { // We have uploaded and deleted a copy of the file. Now delete the original one. - CoreFile.instance.removeFileByFileEntry(fileEntry); + CoreFile.removeFileByFileEntry(fileEntry); } return result; @@ -740,7 +740,7 @@ export class CoreFileUploaderHelperProvider { name?: string, ): Promise { if (maxSize === 0) { - const siteInfo = CoreSites.instance.getCurrentSite()?.getInfo(); + const siteInfo = CoreSites.getCurrentSite()?.getInfo(); if (siteInfo && siteInfo.usermaxuploadfilesize) { maxSize = siteInfo.usermaxuploadfilesize; @@ -777,17 +777,17 @@ export class CoreFileUploaderHelperProvider { siteId?: string, ): Promise { - const errorStr = Translate.instance.instant('core.error'); - const retryStr = Translate.instance.instant('core.retry'); - const uploadingStr = Translate.instance.instant('core.fileuploader.uploading'); + const errorStr = Translate.instant('core.error'); + const retryStr = Translate.instant('core.retry'); + const uploadingStr = Translate.instant('core.fileuploader.uploading'); const errorUploading = async (error): Promise => { // Allow the user to retry. try { - await CoreDomUtils.instance.showConfirm(error, errorStr, retryStr); + await CoreDomUtils.showConfirm(error, errorStr, retryStr); } catch (error) { // User cancelled. Delete the file if needed. if (options.deleteAfterUpload) { - CoreFile.instance.removeExternalFile(path); + CoreFile.removeExternalFile(path); } throw new CoreCanceledError(); @@ -797,8 +797,8 @@ export class CoreFileUploaderHelperProvider { return this.uploadFile(path, maxSize, checkSize, options, siteId); }; - if (!CoreApp.instance.isOnline()) { - return errorUploading(Translate.instance.instant('core.fileuploader.errormustbeonlinetoupload')); + if (!CoreApp.isOnline()) { + return errorUploading(Translate.instant('core.fileuploader.errormustbeonlinetoupload')); } let file: IFile | undefined; @@ -807,9 +807,9 @@ export class CoreFileUploaderHelperProvider { if (checkSize) { try { // Check that file size is the right one. - const fileEntry = await CoreFile.instance.getExternalFile(path); + const fileEntry = await CoreFile.getExternalFile(path); - file = await CoreFile.instance.getFileObjectFromFileEntry(fileEntry); + file = await CoreFile.getFileObjectFromFileEntry(fileEntry); size = file.size; } catch (error) { @@ -826,10 +826,10 @@ export class CoreFileUploaderHelperProvider { } // File isn't too large and user confirmed, let's upload. - const modal = await CoreDomUtils.instance.showModalLoading(uploadingStr); + const modal = await CoreDomUtils.showModalLoading(uploadingStr); try { - return await CoreFileUploader.instance.uploadFile( + return await CoreFileUploader.uploadFile( path, options, (progress: ProgressEvent) => { @@ -873,10 +873,10 @@ export class CoreFileUploaderHelperProvider { const contentElement = modal.loading?.querySelector('.loading-content'); if (contentElement) { - contentElement.innerHTML = Translate.instance.instant(stringKey, { $a: perc.toFixed(1) }); + contentElement.innerHTML = Translate.instant(stringKey, { $a: perc.toFixed(1) }); } } } -export class CoreFileUploaderHelper extends makeSingleton(CoreFileUploaderHelperProvider) {} +export const CoreFileUploaderHelper = makeSingleton(CoreFileUploaderHelperProvider); diff --git a/src/core/features/fileuploader/services/fileuploader.ts b/src/core/features/fileuploader/services/fileuploader.ts index d22e2d024..342815f33 100644 --- a/src/core/features/fileuploader/services/fileuploader.ts +++ b/src/core/features/fileuploader/services/fileuploader.ts @@ -90,7 +90,7 @@ export class CoreFileUploaderProvider { // Currently we are going to compare the order of the files as well. // This function can be improved comparing more fields or not comparing the order. for (let i = 0; i < a.length; i++) { - if (CoreFile.instance.getFileName(a[i]) != CoreFile.instance.getFileName(b[i])) { + if (CoreFile.getFileName(a[i]) != CoreFile.getFileName(b[i])) { return true; } } @@ -107,7 +107,7 @@ export class CoreFileUploaderProvider { */ async canDeleteDraftFiles(siteId?: string): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.canDeleteDraftFilesInSite(site); } catch (error) { @@ -123,7 +123,7 @@ export class CoreFileUploaderProvider { * @since 3.10 */ canDeleteDraftFilesInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!(site?.wsAvailable('core_files_delete_draft_files')); } @@ -138,7 +138,7 @@ export class CoreFileUploaderProvider { this.onAudioCapture.next(true); try { - return await MediaCapture.instance.captureAudio(options); + return await MediaCapture.captureAudio(options); } finally { this.onAudioCapture.next(false); } @@ -154,7 +154,7 @@ export class CoreFileUploaderProvider { type: 'audio', }; - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: CoreEmulatorCaptureMediaComponent, cssClass: 'core-modal-fullscreen', componentProps: params, @@ -182,7 +182,7 @@ export class CoreFileUploaderProvider { this.onVideoCapture.next(true); try { - return await MediaCapture.instance.captureVideo(options); + return await MediaCapture.captureVideo(options); } finally { this.onVideoCapture.next(false); } @@ -215,7 +215,7 @@ export class CoreFileUploaderProvider { * @return Promise resolved when done. */ async deleteDraftFiles(draftId: number, files: { filepath: string; filename: string }[], siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params = { draftitemid: draftId, @@ -233,20 +233,20 @@ export class CoreFileUploaderProvider { * @return Options. */ getCameraUploadOptions(uri: string, isFromAlbum?: boolean): CoreFileUploaderOptions { - const extension = CoreMimetypeUtils.instance.guessExtensionFromUrl(uri); - const mimetype = CoreMimetypeUtils.instance.getMimeType(extension); - const isIOS = CoreApp.instance.isIOS(); + const extension = CoreMimetypeUtils.guessExtensionFromUrl(uri); + const mimetype = CoreMimetypeUtils.getMimeType(extension); + const isIOS = CoreApp.isIOS(); const options: CoreFileUploaderOptions = { deleteAfterUpload: !isFromAlbum, mimeType: mimetype, }; - const fileName = CoreFile.instance.getFileAndDirectoryFromPath(uri).name; + const fileName = CoreFile.getFileAndDirectoryFromPath(uri).name; if (isIOS && (mimetype == 'image/jpeg' || mimetype == 'image/png')) { // In iOS, the pictures can have repeated names, even if they come from the album. // Add a timestamp to the filename to make it unique. const split = fileName.split('.'); - split[0] += '_' + CoreTimeUtils.instance.readableTimestamp(); + split[0] += '_' + CoreTimeUtils.readableTimestamp(); options.fileName = split.join('.'); } else { @@ -256,9 +256,9 @@ export class CoreFileUploaderProvider { if (isFromAlbum) { // If the file was picked from the album, delete it only if it was copied to the app's folder. - options.deleteAfterUpload = CoreFile.instance.isFileInAppFolder(uri); + options.deleteAfterUpload = CoreFile.isFileInAppFolder(uri); - if (CoreApp.instance.isAndroid()) { + if (CoreApp.isAndroid()) { // Picking an image from album in Android adds a timestamp at the end of the file. Delete it. options.fileName = options.fileName.replace(/(\.[^.]*)\?[^.]*$/, '$1'); } @@ -317,8 +317,8 @@ export class CoreFileUploaderProvider { ): CoreFileUploaderOptions { const options: CoreFileUploaderOptions = {}; options.fileName = name; - options.mimeType = mimetype || CoreMimetypeUtils.instance.getMimeType( - CoreMimetypeUtils.instance.getFileExtension(options.fileName), + options.mimeType = mimetype || CoreMimetypeUtils.getMimeType( + CoreMimetypeUtils.getFileExtension(options.fileName), ); options.deleteAfterUpload = !!deleteAfterUpload; options.itemId = itemId || 0; @@ -340,7 +340,7 @@ export class CoreFileUploaderProvider { if (!filename.match(/_\d{14}(\..*)?$/)) { // Add a timestamp to the filename to make it unique. const split = filename.split('.'); - split[0] += '_' + CoreTimeUtils.instance.readableTimestamp(); + split[0] += '_' + CoreTimeUtils.readableTimestamp(); filename = split.join('.'); } @@ -349,8 +349,8 @@ export class CoreFileUploaderProvider { if (mediaFile.type) { options.mimeType = mediaFile.type; } else { - options.mimeType = CoreMimetypeUtils.instance.getMimeType( - CoreMimetypeUtils.instance.getFileExtension(options.fileName), + options.mimeType = CoreMimetypeUtils.getMimeType( + CoreMimetypeUtils.getFileExtension(options.fileName), ); } @@ -366,7 +366,7 @@ export class CoreFileUploaderProvider { getPicture(options: CameraOptions): Promise { this.onGetPicture.next(true); - return Camera.instance.getPicture(options).finally(() => { + return Camera.getPicture(options).finally(() => { this.onGetPicture.next(false); }); } @@ -378,7 +378,7 @@ export class CoreFileUploaderProvider { * @return Promise resolved with the list of files. */ async getStoredFiles(folderPath: string): Promise { - return await CoreFile.instance.getDirectoryContents(folderPath); + return await CoreFile.getDirectoryContents(folderPath); } /** @@ -395,11 +395,11 @@ export class CoreFileUploaderProvider { let files: (CoreWSExternalFile | FileEntry)[] = []; if (filesObject.online.length > 0) { - files = CoreUtils.instance.clone(filesObject.online); + files = CoreUtils.clone(filesObject.online); } if (filesObject.offline > 0) { - const offlineFiles = await CoreUtils.instance.ignoreErrors(this.getStoredFiles(folderPath)); + const offlineFiles = await CoreUtils.ignoreErrors(this.getStoredFiles(folderPath)); if (offlineFiles) { files = files.concat(offlineFiles); @@ -424,24 +424,24 @@ export class CoreFileUploaderProvider { if (mimetypes) { // Verify that the mimetype of the file is supported. if (mimetype) { - extension = CoreMimetypeUtils.instance.getExtension(mimetype); + extension = CoreMimetypeUtils.getExtension(mimetype); if (mimetypes.indexOf(mimetype) == -1) { // Get the "main" mimetype of the extension. // It's possible that the list of accepted mimetypes only includes the "main" mimetypes. - mimetype = CoreMimetypeUtils.instance.getMimeType(extension); + mimetype = CoreMimetypeUtils.getMimeType(extension); } } else if (path) { - extension = CoreMimetypeUtils.instance.getFileExtension(path); - mimetype = CoreMimetypeUtils.instance.getMimeType(extension); + extension = CoreMimetypeUtils.getFileExtension(path); + mimetype = CoreMimetypeUtils.getMimeType(extension); } else { throw new CoreError('No mimetype or path supplied.'); } if (mimetype && mimetypes.indexOf(mimetype) == -1) { - extension = extension || Translate.instance.instant('core.unknown'); + extension = extension || Translate.instant('core.unknown'); - return Translate.instance.instant('core.fileuploader.invalidfiletype', { $a: extension }); + return Translate.instant('core.fileuploader.invalidfiletype', { $a: extension }); } } } @@ -485,16 +485,16 @@ export class CoreFileUploaderProvider { if (filetype.indexOf('/') != -1) { // It's a mimetype. typesInfo.push({ - name: CoreMimetypeUtils.instance.getMimetypeDescription(filetype), - extlist: CoreMimetypeUtils.instance.getExtensions(filetype).map(this.addDot).join(' '), + name: CoreMimetypeUtils.getMimetypeDescription(filetype), + extlist: CoreMimetypeUtils.getExtensions(filetype).map(this.addDot).join(' '), }); mimetypes[filetype] = true; } else if (filetype.indexOf('.') === 0) { // It's an extension. - const mimetype = CoreMimetypeUtils.instance.getMimeType(filetype); + const mimetype = CoreMimetypeUtils.getMimeType(filetype); typesInfo.push({ - name: mimetype && CoreMimetypeUtils.instance.getMimetypeDescription(mimetype), + name: mimetype && CoreMimetypeUtils.getMimetypeDescription(mimetype), extlist: filetype, }); @@ -503,12 +503,12 @@ export class CoreFileUploaderProvider { } } else { // It's a group. - const groupExtensions = CoreMimetypeUtils.instance.getGroupMimeInfo(filetype, 'extensions'); - const groupMimetypes = CoreMimetypeUtils.instance.getGroupMimeInfo(filetype, 'mimetypes'); + const groupExtensions = CoreMimetypeUtils.getGroupMimeInfo(filetype, 'extensions'); + const groupMimetypes = CoreMimetypeUtils.getGroupMimeInfo(filetype, 'mimetypes'); if (groupExtensions && groupExtensions.length > 0) { typesInfo.push({ - name: CoreMimetypeUtils.instance.getTranslatedGroupName(filetype), + name: CoreMimetypeUtils.getTranslatedGroupName(filetype), extlist: groupExtensions.map(this.addDot).join(' '), }); @@ -521,9 +521,9 @@ export class CoreFileUploaderProvider { // Treat them as extensions. filetype = this.addDot(filetype); - const mimetype = CoreMimetypeUtils.instance.getMimeType(filetype); + const mimetype = CoreMimetypeUtils.getMimeType(filetype); typesInfo.push({ - name: mimetype && CoreMimetypeUtils.instance.getMimetypeDescription(mimetype), + name: mimetype && CoreMimetypeUtils.getMimetypeDescription(mimetype), extlist: filetype, }); @@ -562,10 +562,10 @@ export class CoreFileUploaderProvider { } // Remove unused files from previous saves. - await CoreFile.instance.removeUnusedFiles(folderPath, files); + await CoreFile.removeUnusedFiles(folderPath, files); await Promise.all(files.map(async (file) => { - if (!CoreUtils.instance.isFileEntry(file)) { + if (!CoreUtils.isFileEntry(file)) { // It's an online file, add it to the result and ignore it. result.online.push({ filename: file.filename, @@ -577,10 +577,10 @@ export class CoreFileUploaderProvider { } else { // Local file, copy it. // Use copy instead of move to prevent having a unstable state if some copies succeed and others don't. - const destFile = CoreTextUtils.instance.concatenatePaths(folderPath, file.name); + const destFile = CoreTextUtils.concatenatePaths(folderPath, file.name); result.offline++; - await CoreFile.instance.copyFile(file.toURL(), destFile); + await CoreFile.copyFile(file.toURL(), destFile); } })); @@ -605,16 +605,16 @@ export class CoreFileUploaderProvider { options = options || {}; const deleteAfterUpload = options.deleteAfterUpload; - const ftOptions = CoreUtils.instance.clone(options); + const ftOptions = CoreUtils.clone(options); delete ftOptions.deleteAfterUpload; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const result = await site.uploadFile(uri, ftOptions, onProgress); if (deleteAfterUpload) { - CoreFile.instance.removeExternalFile(uri); + CoreFile.removeExternalFile(uri); } return result; @@ -630,7 +630,7 @@ export class CoreFileUploaderProvider { * @return Promise resolved with the itemId. */ async uploadFiles(itemId: number, files: (CoreWSExternalFile | FileEntry)[], siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!files || !files.length) { return; @@ -640,7 +640,7 @@ export class CoreFileUploaderProvider { const usedNames: {[name: string]: (CoreWSExternalFile | FileEntry)} = {}; const filesToUpload: FileEntry[] = []; files.forEach((file) => { - if (CoreUtils.instance.isFileEntry(file)) { + if (CoreUtils.isFileEntry(file)) { filesToUpload.push( file); } else { // It's an online file. @@ -650,7 +650,7 @@ export class CoreFileUploaderProvider { await Promise.all(filesToUpload.map(async (file) => { // Make sure the file name is unique in the area. - const name = CoreFile.instance.calculateUniqueName(usedNames, file.name); + const name = CoreFile.calculateUniqueName(usedNames, file.name); usedNames[name] = file; // Now upload the file. @@ -680,14 +680,14 @@ export class CoreFileUploaderProvider { componentId?: string | number, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); let fileName: string | undefined; let fileEntry: FileEntry | undefined; - const isOnline = !CoreUtils.instance.isFileEntry(file); + const isOnline = !CoreUtils.isFileEntry(file); - if (CoreUtils.instance.isFileEntry(file)) { + if (CoreUtils.isFileEntry(file)) { // Local file, we already have the file entry. fileName = file.name; fileEntry = file; @@ -695,7 +695,7 @@ export class CoreFileUploaderProvider { // It's an online file. We need to download it and re-upload it. fileName = file.filename; - const path = await CoreFilepool.instance.downloadUrl( + const path = await CoreFilepool.downloadUrl( siteId, file.fileurl, false, @@ -707,12 +707,12 @@ export class CoreFileUploaderProvider { file, ); - fileEntry = await CoreFile.instance.getExternalFile(path); + fileEntry = await CoreFile.getExternalFile(path); } // Now upload the file. - const extension = CoreMimetypeUtils.instance.getFileExtension(fileName!); - const mimetype = extension ? CoreMimetypeUtils.instance.getMimeType(extension) : undefined; + const extension = CoreMimetypeUtils.getFileExtension(fileName!); + const mimetype = extension ? CoreMimetypeUtils.getMimeType(extension) : undefined; const options = this.getFileUploadOptions(fileEntry.toURL(), fileName!, mimetype, isOnline, 'draft', itemId); const result = await this.uploadFile(fileEntry.toURL(), options, undefined, siteId); @@ -739,7 +739,7 @@ export class CoreFileUploaderProvider { componentId?: string | number, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!files || !files.length) { // Return fake draft ID. @@ -763,7 +763,7 @@ export class CoreFileUploaderProvider { } -export class CoreFileUploader extends makeSingleton(CoreFileUploaderProvider) {} +export const CoreFileUploader = makeSingleton(CoreFileUploaderProvider); export type CoreFileUploaderStoreFilesResult = { online: CoreWSExternalFile[]; // List of online files. diff --git a/src/core/features/fileuploader/services/handlers/album.ts b/src/core/features/fileuploader/services/handlers/album.ts index e926580bf..474e9b8b5 100644 --- a/src/core/features/fileuploader/services/handlers/album.ts +++ b/src/core/features/fileuploader/services/handlers/album.ts @@ -35,7 +35,7 @@ export class CoreFileUploaderAlbumHandlerService implements CoreFileUploaderHand * @return Promise resolved with true if enabled. */ async isEnabled(): Promise { - return CoreApp.instance.isMobile(); + return CoreApp.isMobile(); } /** @@ -46,7 +46,7 @@ export class CoreFileUploaderAlbumHandlerService implements CoreFileUploaderHand */ getSupportedMimetypes(mimetypes: string[]): string[] { // Album allows picking images and videos. - return CoreUtils.instance.filterByRegexp(mimetypes, /^(image|video)\//); + return CoreUtils.filterByRegexp(mimetypes, /^(image|video)\//); } /** @@ -65,7 +65,7 @@ export class CoreFileUploaderAlbumHandlerService implements CoreFileUploaderHand allowOffline?: boolean, mimetypes?: string[], ): Promise => { - const result = await CoreFileUploaderHelper.instance.uploadImage(true, maxSize, upload, mimetypes); + const result = await CoreFileUploaderHelper.uploadImage(true, maxSize, upload, mimetypes); return { treated: true, @@ -77,4 +77,4 @@ export class CoreFileUploaderAlbumHandlerService implements CoreFileUploaderHand } -export class CoreFileUploaderAlbumHandler extends makeSingleton(CoreFileUploaderAlbumHandlerService) {} +export const CoreFileUploaderAlbumHandler = makeSingleton(CoreFileUploaderAlbumHandlerService); diff --git a/src/core/features/fileuploader/services/handlers/audio.ts b/src/core/features/fileuploader/services/handlers/audio.ts index 4d846e7f9..3c612bd2c 100644 --- a/src/core/features/fileuploader/services/handlers/audio.ts +++ b/src/core/features/fileuploader/services/handlers/audio.ts @@ -34,7 +34,7 @@ export class CoreFileUploaderAudioHandlerService implements CoreFileUploaderHand * @return Promise resolved with true if enabled. */ async isEnabled(): Promise { - return CoreApp.instance.isMobile() || (CoreApp.instance.canGetUserMedia() && CoreApp.instance.canRecordMedia()); + return CoreApp.isMobile() || (CoreApp.canGetUserMedia() && CoreApp.canRecordMedia()); } /** @@ -44,12 +44,12 @@ export class CoreFileUploaderAudioHandlerService implements CoreFileUploaderHand * @return Supported mimetypes. */ getSupportedMimetypes(mimetypes: string[]): string[] { - if (CoreApp.instance.isIOS()) { + if (CoreApp.isIOS()) { // In iOS it's recorded as WAV. - return CoreUtils.instance.filterByRegexp(mimetypes, /^audio\/wav$/); - } else if (CoreApp.instance.isAndroid()) { + return CoreUtils.filterByRegexp(mimetypes, /^audio\/wav$/); + } else if (CoreApp.isAndroid()) { // In Android we don't know the format the audio will be recorded, so accept any audio mimetype. - return CoreUtils.instance.filterByRegexp(mimetypes, /^audio\//); + return CoreUtils.filterByRegexp(mimetypes, /^audio\//); } else { // In browser, support audio formats that are supported by MediaRecorder. if (MediaRecorder) { @@ -80,7 +80,7 @@ export class CoreFileUploaderAudioHandlerService implements CoreFileUploaderHand allowOffline?: boolean, mimetypes?: string[], ): Promise => { - const result = await CoreFileUploaderHelper.instance.uploadAudioOrVideo(true, maxSize, upload, mimetypes); + const result = await CoreFileUploaderHelper.uploadAudioOrVideo(true, maxSize, upload, mimetypes); return { treated: true, @@ -92,4 +92,4 @@ export class CoreFileUploaderAudioHandlerService implements CoreFileUploaderHand } -export class CoreFileUploaderAudioHandler extends makeSingleton(CoreFileUploaderAudioHandlerService) { } +export const CoreFileUploaderAudioHandler = makeSingleton(CoreFileUploaderAudioHandlerService); diff --git a/src/core/features/fileuploader/services/handlers/camera.ts b/src/core/features/fileuploader/services/handlers/camera.ts index d1aa80036..db3bde46f 100644 --- a/src/core/features/fileuploader/services/handlers/camera.ts +++ b/src/core/features/fileuploader/services/handlers/camera.ts @@ -35,7 +35,7 @@ export class CoreFileUploaderCameraHandlerService implements CoreFileUploaderHan * @return Promise resolved with true if enabled. */ async isEnabled(): Promise { - return CoreApp.instance.isMobile() || CoreApp.instance.canGetUserMedia(); + return CoreApp.isMobile() || CoreApp.canGetUserMedia(); } /** @@ -46,7 +46,7 @@ export class CoreFileUploaderCameraHandlerService implements CoreFileUploaderHan */ getSupportedMimetypes(mimetypes: string[]): string[] { // Camera only supports JPEG and PNG. - return CoreUtils.instance.filterByRegexp(mimetypes, /^image\/(jpeg|png)$/); + return CoreUtils.filterByRegexp(mimetypes, /^image\/(jpeg|png)$/); } /** @@ -65,7 +65,7 @@ export class CoreFileUploaderCameraHandlerService implements CoreFileUploaderHan allowOffline?: boolean, mimetypes?: string[], ): Promise => { - const result = await CoreFileUploaderHelper.instance.uploadImage(false, maxSize, upload, mimetypes); + const result = await CoreFileUploaderHelper.uploadImage(false, maxSize, upload, mimetypes); return { treated: true, @@ -77,4 +77,4 @@ export class CoreFileUploaderCameraHandlerService implements CoreFileUploaderHan } -export class CoreFileUploaderCameraHandler extends makeSingleton(CoreFileUploaderCameraHandlerService) {} +export const CoreFileUploaderCameraHandler = makeSingleton(CoreFileUploaderCameraHandlerService); diff --git a/src/core/features/fileuploader/services/handlers/file.ts b/src/core/features/fileuploader/services/handlers/file.ts index 11e1caff0..5ce1ab8ad 100644 --- a/src/core/features/fileuploader/services/handlers/file.ts +++ b/src/core/features/fileuploader/services/handlers/file.ts @@ -61,14 +61,14 @@ export class CoreFileUploaderFileHandlerService implements CoreFileUploaderHandl icon: 'folder', }; - if (CoreApp.instance.isMobile()) { + if (CoreApp.isMobile()) { handler.action = async ( maxSize?: number, upload?: boolean, allowOffline?: boolean, mimetypes?: string[], ): Promise => { - const result = await CoreFileUploaderHelper.instance.chooseAndUploadFile(maxSize, upload, allowOffline, mimetypes); + const result = await CoreFileUploaderHelper.chooseAndUploadFile(maxSize, upload, allowOffline, mimetypes); return { treated: true, @@ -93,7 +93,7 @@ export class CoreFileUploaderFileHandlerService implements CoreFileUploaderHandl const input = document.createElement('input'); input.setAttribute('type', 'file'); input.classList.add('core-fileuploader-file-handler-input'); - if (mimetypes && mimetypes.length && (!CoreApp.instance.isAndroid() || mimetypes.length == 1)) { + if (mimetypes && mimetypes.length && (!CoreApp.isAndroid() || mimetypes.length == 1)) { // Don't use accept attribute in Android with several mimetypes, it's not supported. input.setAttribute('accept', mimetypes.join(', ')); } @@ -107,16 +107,16 @@ export class CoreFileUploaderFileHandlerService implements CoreFileUploaderHandl } // Verify that the mimetype of the file is supported, in case the accept attribute isn't supported. - const error = CoreFileUploader.instance.isInvalidMimetype(mimetypes, file.name, file.type); + const error = CoreFileUploader.isInvalidMimetype(mimetypes, file.name, file.type); if (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); return; } try { // Upload the picked file. - const result = await CoreFileUploaderHelper.instance.uploadFileObject( + const result = await CoreFileUploaderHelper.uploadFileObject( file, maxSize, upload, @@ -124,16 +124,16 @@ export class CoreFileUploaderFileHandlerService implements CoreFileUploaderHandl file.name, ); - CoreFileUploaderHelper.instance.fileUploaded(result); + CoreFileUploaderHelper.fileUploaded(result); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault( + CoreDomUtils.showErrorModalDefault( error, - Translate.instance.instant('core.fileuploader.errorreadingfile'), + Translate.instant('core.fileuploader.errorreadingfile'), ); } }); - if (CoreApp.instance.isIOS()) { + if (CoreApp.isIOS()) { // In iOS, the click on the input stopped working for some reason. We need to put it 1 level higher. element.parentElement?.appendChild(input); @@ -157,4 +157,4 @@ export class CoreFileUploaderFileHandlerService implements CoreFileUploaderHandl } -export class CoreFileUploaderFileHandler extends makeSingleton(CoreFileUploaderFileHandlerService) {} +export const CoreFileUploaderFileHandler = makeSingleton(CoreFileUploaderFileHandlerService); diff --git a/src/core/features/fileuploader/services/handlers/video.ts b/src/core/features/fileuploader/services/handlers/video.ts index 9feb2c7b5..4a350ea0d 100644 --- a/src/core/features/fileuploader/services/handlers/video.ts +++ b/src/core/features/fileuploader/services/handlers/video.ts @@ -34,7 +34,7 @@ export class CoreFileUploaderVideoHandlerService implements CoreFileUploaderHand * @return Promise resolved with true if enabled. */ async isEnabled(): Promise { - return CoreApp.instance.isMobile() || (CoreApp.instance.canGetUserMedia() && CoreApp.instance.canRecordMedia()); + return CoreApp.isMobile() || (CoreApp.canGetUserMedia() && CoreApp.canRecordMedia()); } /** @@ -44,12 +44,12 @@ export class CoreFileUploaderVideoHandlerService implements CoreFileUploaderHand * @return Supported mimetypes. */ getSupportedMimetypes(mimetypes: string[]): string[] { - if (CoreApp.instance.isIOS()) { + if (CoreApp.isIOS()) { // In iOS it's recorded as MOV. - return CoreUtils.instance.filterByRegexp(mimetypes, /^video\/quicktime$/); - } else if (CoreApp.instance.isAndroid()) { + return CoreUtils.filterByRegexp(mimetypes, /^video\/quicktime$/); + } else if (CoreApp.isAndroid()) { // In Android we don't know the format the video will be recorded, so accept any video mimetype. - return CoreUtils.instance.filterByRegexp(mimetypes, /^video\//); + return CoreUtils.filterByRegexp(mimetypes, /^video\//); } else { // In browser, support video formats that are supported by MediaRecorder. if (MediaRecorder) { @@ -80,7 +80,7 @@ export class CoreFileUploaderVideoHandlerService implements CoreFileUploaderHand allowOffline?: boolean, mimetypes?: string[], ): Promise => { - const result = await CoreFileUploaderHelper.instance.uploadAudioOrVideo(false, maxSize, upload, mimetypes); + const result = await CoreFileUploaderHelper.uploadAudioOrVideo(false, maxSize, upload, mimetypes); return { treated: true, @@ -92,4 +92,4 @@ export class CoreFileUploaderVideoHandlerService implements CoreFileUploaderHand } -export class CoreFileUploaderVideoHandler extends makeSingleton(CoreFileUploaderVideoHandlerService) {} +export const CoreFileUploaderVideoHandler = makeSingleton(CoreFileUploaderVideoHandlerService); diff --git a/src/core/features/filter/services/filter-delegate.ts b/src/core/features/filter/services/filter-delegate.ts index dcd394f0b..4e4a08936 100644 --- a/src/core/features/filter/services/filter-delegate.ts +++ b/src/core/features/filter/services/filter-delegate.ts @@ -108,7 +108,7 @@ export class CoreFilterDelegateService extends CoreDelegate { // Wait for filters to be initialized. await this.handlersInitPromise; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); filters = filters || []; options = options || {}; @@ -191,7 +191,7 @@ export class CoreFilterDelegateService extends CoreDelegate { // Wait for filters to be initialized. await this.handlersInitPromise; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); filters = filters || []; options = options || {}; @@ -287,4 +287,4 @@ export class CoreFilterDelegateService extends CoreDelegate { } -export class CoreFilterDelegate extends makeSingleton(CoreFilterDelegateService) {} +export const CoreFilterDelegate = makeSingleton(CoreFilterDelegateService); diff --git a/src/core/features/filter/services/filter-helper.ts b/src/core/features/filter/services/filter-helper.ts index 588be18f7..574233d2c 100644 --- a/src/core/features/filter/services/filter-helper.ts +++ b/src/core/features/filter/services/filter-helper.ts @@ -74,7 +74,7 @@ export class CoreFilterHelperProvider { * @return Promise resolved with the contexts. */ async getBlocksContexts(courseId: number, siteId?: string): Promise { - const blocks = await CoreCourse.instance.getCourseBlocks(courseId, siteId); + const blocks = await CoreCourse.getCourseBlocks(courseId, siteId); const contexts: CoreFiltersGetAvailableInContextWSParamContext[] = []; @@ -115,7 +115,7 @@ export class CoreFilterHelperProvider { const contexts = await getFilters(); - const filters = await CoreFilter.instance.getAvailableInContexts(contexts, siteId); + const filters = await CoreFilter.getAvailableInContexts(contexts, siteId); this.storeInMemoryCache(options.courseId ?? -1, contextLevel, filters, siteId); @@ -130,7 +130,7 @@ export class CoreFilterHelperProvider { * @return Promise resolved with the contexts. */ async getCourseContexts(courseId: number, siteId?: string): Promise { - const courseIds = await CoreCourses.instance.getCourseIdsIfEnrolled(courseId, siteId); + const courseIds = await CoreCourses.getCourseIdsIfEnrolled(courseId, siteId); const contexts: CoreFiltersGetAvailableInContextWSParamContext[] = []; @@ -152,7 +152,7 @@ export class CoreFilterHelperProvider { * @return Promise resolved with the contexts. */ async getCourseModulesContexts(courseId: number, siteId?: string): Promise { - const sections = await CoreCourse.instance.getSections(courseId, false, true, undefined, siteId); + const sections = await CoreCourse.getSections(courseId, false, true, undefined, siteId); const contexts: CoreFiltersGetAvailableInContextWSParamContext[] = []; @@ -195,16 +195,16 @@ export class CoreFilterHelperProvider { options.filter = false; try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); - const canGet = await CoreFilter.instance.canGetFilters(siteId); + const canGet = await CoreFilter.canGetFilters(siteId); if (!canGet) { options.filter = true; // We cannot check which filters are available, apply them all. - return CoreFilterDelegate.instance.getEnabledFilters(contextLevel, instanceId); + return CoreFilterDelegate.getEnabledFilters(contextLevel, instanceId); } let hasFilters = true; @@ -233,14 +233,14 @@ export class CoreFilterHelperProvider { const getFilters = this.getCourseContexts.bind(this, instanceId, siteId); return this.getCacheableFilters(contextLevel, instanceId, getFilters, options, site); - } else if (contextLevel == 'block' && options.courseId && CoreCourse.instance.canGetCourseBlocks(site)) { + } else if (contextLevel == 'block' && options.courseId && CoreCourse.canGetCourseBlocks(site)) { // Get all the course blocks filters with a single call to decrease number of WS calls. const getFilters = this.getBlocksContexts.bind(this, options.courseId, siteId); return this.getCacheableFilters(contextLevel, instanceId, getFilters, options, site); } - return CoreFilter.instance.getAvailableInContext(contextLevel, instanceId, siteId); + return CoreFilter.getAvailableInContext(contextLevel, instanceId, siteId); } catch (error) { this.logger.error('Error getting filters, return an empty array', error, contextLevel, instanceId); @@ -268,7 +268,7 @@ export class CoreFilterHelperProvider { const filters = await this.getFilters(contextLevel, instanceId, options, siteId); - text = await CoreFilter.instance.formatText(text, options, filters, siteId); + text = await CoreFilter.formatText(text, options, filters, siteId); return { text, filters: filters }; } @@ -298,7 +298,7 @@ export class CoreFilterHelperProvider { const cachedData = this.moduleContextsCache[siteId][courseId][contextLevel]; - if (!CoreApp.instance.isOnline() || Date.now() <= cachedData.time + site.getExpirationDelay(CoreSite.FREQUENCY_RARELY)) { + if (!CoreApp.isOnline() || Date.now() <= cachedData.time + site.getExpirationDelay(CoreSite.FREQUENCY_RARELY)) { // We can use cache, return the filters if found. return cachedData.contexts[contextLevel] && cachedData.contexts[contextLevel][instanceId]; } @@ -314,12 +314,12 @@ export class CoreFilterHelperProvider { async siteHasFiltersToTreat(options?: CoreFilterFormatTextOptions, siteId?: string): Promise { options = options || {}; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Get filters at site level. - const filters = await CoreFilter.instance.getAvailableInContext('system', 0, site.getId()); + const filters = await CoreFilter.getAvailableInContext('system', 0, site.getId()); - return CoreFilterDelegate.instance.shouldBeApplied(filters, options, site); + return CoreFilterDelegate.shouldBeApplied(filters, options, site); } /** @@ -345,4 +345,4 @@ export class CoreFilterHelperProvider { } -export class CoreFilterHelper extends makeSingleton(CoreFilterHelperProvider) {} +export const CoreFilterHelper = makeSingleton(CoreFilterHelperProvider); diff --git a/src/core/features/filter/services/filter.ts b/src/core/features/filter/services/filter.ts index fc973a02e..b5139a92f 100644 --- a/src/core/features/filter/services/filter.ts +++ b/src/core/features/filter/services/filter.ts @@ -68,7 +68,7 @@ export class CoreFilterProvider { * @since 3.4 */ async canGetAvailableInContext(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.canGetAvailableInContextInSite(site); } @@ -81,7 +81,7 @@ export class CoreFilterProvider { * @since 3.4 */ canGetAvailableInContextInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!(site?.wsAvailable('core_filters_get_available_in_context')); } @@ -116,7 +116,7 @@ export class CoreFilterProvider { * @return Promise resolved with boolean: whether it's disabled. */ async checkFiltersDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.checkFiltersDisabledInSite(site); } @@ -128,7 +128,7 @@ export class CoreFilterProvider { * @return Whether it's disabled. */ checkFiltersDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!(site?.isFeatureDisabled('CoreFilterDelegate')); } @@ -225,19 +225,19 @@ export class CoreFilterProvider { } if (options.filter) { - text = await CoreFilterDelegate.instance.filterText(text, filters, options, [], siteId); + text = await CoreFilterDelegate.filterText(text, filters, options, [], siteId); } if (options.clean) { - text = CoreTextUtils.instance.cleanTags(text, options.singleLine); + text = CoreTextUtils.cleanTags(text, options.singleLine); } if (options.shortenLength && options.shortenLength > 0) { - text = CoreTextUtils.instance.shortenText(text, options.shortenLength); + text = CoreTextUtils.shortenText(text, options.shortenLength); } if (options.highlight) { - text = CoreTextUtils.instance.highlightText(text, options.highlight); + text = CoreTextUtils.highlightText(text, options.highlight); } return text; @@ -274,7 +274,7 @@ export class CoreFilterProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.getId(); @@ -345,7 +345,7 @@ export class CoreFilterProvider { // Check if we have the contexts in the memory cache. const siteContexts = this.contextsCache[site.getId()]; - const isOnline = CoreApp.instance.isOnline(); + const isOnline = CoreApp.isOnline(); const result: CoreFilterClassifiedFilters = {}; let allFound = true; @@ -377,7 +377,7 @@ export class CoreFilterProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAllAvailableInContext(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getAvailableInContextsPrefixCacheKey()); } @@ -393,7 +393,7 @@ export class CoreFilterProvider { contexts: CoreFiltersGetAvailableInContextWSParamContext[], siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAvailableInContextsCacheKey(contexts)); } @@ -481,7 +481,7 @@ export class CoreFilterProvider { } -export class CoreFilter extends makeSingleton(CoreFilterProvider) {} +export const CoreFilter = makeSingleton(CoreFilterProvider); /** * Params of core_filters_get_available_in_context WS. diff --git a/src/core/features/grades/grades-lazy.module.ts b/src/core/features/grades/grades-lazy.module.ts index e6b90626e..f97dfa538 100644 --- a/src/core/features/grades/grades-lazy.module.ts +++ b/src/core/features/grades/grades-lazy.module.ts @@ -63,8 +63,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; @NgModule({ diff --git a/src/core/features/grades/grades.module.ts b/src/core/features/grades/grades.module.ts index eea8feb79..05da84659 100644 --- a/src/core/features/grades/grades.module.ts +++ b/src/core/features/grades/grades.module.ts @@ -22,7 +22,7 @@ import { CoreMainMenuTabRoutingModule } from '@features/mainmenu/mainmenu-tab-ro import { CoreMainMenuDelegate } from '@features/mainmenu/services/mainmenu-delegate'; import { CoreUserDelegate } from '@features/user/services/user-delegate'; import { CoreGradesCourseOptionHandler } from './services/handlers/course-option'; -import CoreGradesMainMenuHandler, { CoreGradesMainMenuHandlerService } from './services/handlers/mainmenu'; +import { CoreGradesMainMenuHandler, CoreGradesMainMenuHandlerService } from './services/handlers/mainmenu'; import { CoreGradesOverviewLinkHandler } from './services/handlers/overview-link'; import { CoreGradesUserHandler } from './services/handlers/user'; import { CoreGradesUserLinkHandler } from './services/handlers/user-link'; @@ -53,11 +53,11 @@ const courseIndexRoutes: Routes = [ multi: true, deps: [], useValue: () => { - CoreMainMenuDelegate.instance.registerHandler(CoreGradesMainMenuHandler.instance); - CoreUserDelegate.instance.registerHandler(CoreGradesUserHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(CoreGradesUserLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(CoreGradesOverviewLinkHandler.instance); - CoreCourseOptionsDelegate.instance.registerHandler(CoreGradesCourseOptionHandler.instance); + CoreMainMenuDelegate.registerHandler(CoreGradesMainMenuHandler.instance); + CoreUserDelegate.registerHandler(CoreGradesUserHandler.instance); + CoreContentLinksDelegate.registerHandler(CoreGradesUserLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(CoreGradesOverviewLinkHandler.instance); + CoreCourseOptionsDelegate.registerHandler(CoreGradesCourseOptionHandler.instance); }, }, ], diff --git a/src/core/features/grades/pages/course/course.page.ts b/src/core/features/grades/pages/course/course.page.ts index df99882d6..7b3dac6df 100644 --- a/src/core/features/grades/pages/course/course.page.ts +++ b/src/core/features/grades/pages/course/course.page.ts @@ -49,7 +49,7 @@ export class CoreGradesCoursePage implements AfterViewInit, OnDestroy { constructor(route: ActivatedRoute) { const courseId = parseInt(route.snapshot.params.courseId ?? route.snapshot.queryParams.courseId); - const userId = parseInt(route.snapshot.queryParams.userId ?? CoreSites.instance.getCurrentSiteUserId()); + const userId = parseInt(route.snapshot.queryParams.userId ?? CoreSites.getCurrentSiteUserId()); const useSplitView = route.snapshot.data.useSplitView ?? true; const outsideGradesTab = route.snapshot.data.outsideGradesTab ?? false; @@ -81,8 +81,8 @@ export class CoreGradesCoursePage implements AfterViewInit, OnDestroy { async refreshGrades(refresher: IonRefresher): Promise { const { courseId, userId } = this.grades; - await CoreUtils.instance.ignoreErrors(CoreGrades.instance.invalidateCourseGradesData(courseId, userId)); - await CoreUtils.instance.ignoreErrors(this.fetchGrades()); + await CoreUtils.ignoreErrors(CoreGrades.invalidateCourseGradesData(courseId, userId)); + await CoreUtils.ignoreErrors(this.fetchGrades()); refresher?.complete(); } @@ -94,7 +94,7 @@ export class CoreGradesCoursePage implements AfterViewInit, OnDestroy { try { await this.fetchGrades(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading course'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading course'); this.grades.setTable({ columns: [], rows: [] }); } @@ -104,8 +104,8 @@ export class CoreGradesCoursePage implements AfterViewInit, OnDestroy { * Update the table of grades. */ private async fetchGrades(): Promise { - const table = await CoreGrades.instance.getCourseGradesTable(this.grades.courseId!, this.grades.userId); - const formattedTable = await CoreGradesHelper.instance.formatGradesTable(table); + const table = await CoreGrades.getCourseGradesTable(this.grades.courseId!, this.grades.userId); + const formattedTable = await CoreGradesHelper.formatGradesTable(table); this.grades.setTable(formattedTable); } @@ -149,7 +149,7 @@ class CoreGradesCourseManager extends CorePageItemsListManager { if (this.outsideGradesTab) { - await CoreNavigator.instance.navigateToSitePath(`/grades/${this.courseId}/${row.id}`); + await CoreNavigator.navigateToSitePath(`/grades/${this.courseId}/${row.id}`); return; } @@ -189,7 +189,7 @@ class CoreGradesCourseManager extends CorePageItemsListManager { - await CoreGrades.instance.logCourseGradesView(this.courseId!, this.userId!); + await CoreGrades.logCourseGradesView(this.courseId!, this.userId!); } /** diff --git a/src/core/features/grades/pages/courses/courses.ts b/src/core/features/grades/pages/courses/courses.ts index 76827f588..df98d2033 100644 --- a/src/core/features/grades/pages/courses/courses.ts +++ b/src/core/features/grades/pages/courses/courses.ts @@ -58,8 +58,8 @@ export class CoreGradesCoursesPage implements OnDestroy, AfterViewInit { * @param refresher Refresher. */ async refreshCourses(refresher: IonRefresher): Promise { - await CoreUtils.instance.ignoreErrors(CoreGrades.instance.invalidateCoursesGradesData()); - await CoreUtils.instance.ignoreErrors(this.fetchCourses()); + await CoreUtils.ignoreErrors(CoreGrades.invalidateCoursesGradesData()); + await CoreUtils.ignoreErrors(this.fetchCourses()); refresher?.complete(); } @@ -71,7 +71,7 @@ export class CoreGradesCoursesPage implements OnDestroy, AfterViewInit { try { await this.fetchCourses(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading courses'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading courses'); this.courses.setItems([]); } @@ -81,8 +81,8 @@ export class CoreGradesCoursesPage implements OnDestroy, AfterViewInit { * Update the list of courses. */ private async fetchCourses(): Promise { - const grades = await CoreGrades.instance.getCoursesGrades(); - const courses = await CoreGradesHelper.instance.getGradesCourseData(grades); + const grades = await CoreGrades.getCoursesGrades(); + const courses = await CoreGradesHelper.getGradesCourseData(grades); this.courses.setItems(courses); } @@ -114,7 +114,7 @@ class CoreGradesCoursesManager extends CorePageItemsListManager { - await CoreGrades.instance.logCoursesGradesView(); + await CoreGrades.logCoursesGradesView(); } } diff --git a/src/core/features/grades/pages/grade/grade.ts b/src/core/features/grades/pages/grade/grade.ts index efec61258..9778286be 100644 --- a/src/core/features/grades/pages/grade/grade.ts +++ b/src/core/features/grades/pages/grade/grade.ts @@ -40,7 +40,7 @@ export class CoreGradesGradePage implements OnInit { constructor(route: ActivatedRoute) { this.courseId = parseInt(route.snapshot.params.courseId ?? route.snapshot.parent?.params.courseId); this.gradeId = parseInt(route.snapshot.params.gradeId); - this.userId = parseInt(route.snapshot.queryParams.userId ?? CoreSites.instance.getCurrentSiteUserId()); + this.userId = parseInt(route.snapshot.queryParams.userId ?? CoreSites.getCurrentSiteUserId()); } /** @@ -55,10 +55,10 @@ export class CoreGradesGradePage implements OnInit { */ async fetchGrade(): Promise { try { - this.grade = await CoreGradesHelper.instance.getGradeItem(this.courseId, this.gradeId, this.userId); + this.grade = await CoreGradesHelper.getGradeItem(this.courseId, this.gradeId, this.userId); this.gradeLoaded = true; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading grade item'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading grade item'); } } @@ -68,8 +68,8 @@ export class CoreGradesGradePage implements OnInit { * @param refresher Refresher. */ async refreshGrade(refresher: IonRefresher): Promise { - await CoreUtils.instance.ignoreErrors(CoreGrades.instance.invalidateCourseGradesData(this.courseId, this.userId)); - await CoreUtils.instance.ignoreErrors(this.fetchGrade()); + await CoreUtils.ignoreErrors(CoreGrades.invalidateCourseGradesData(this.courseId, this.userId)); + await CoreUtils.ignoreErrors(this.fetchGrade()); refresher.complete(); } diff --git a/src/core/features/grades/services/grades-helper.ts b/src/core/features/grades/services/grades-helper.ts index 6958f064c..08105547e 100644 --- a/src/core/features/grades/services/grades-helper.ts +++ b/src/core/features/grades/services/grades-helper.ts @@ -66,9 +66,9 @@ export class CoreGradesHelperProvider { row.rowclass += tableRow[name]!.class.indexOf('dimmed_text') >= 0 ? ' dimmed_text' : ''; content = content.replace(/<\/span>/gi, '\n'); - content = CoreTextUtils.instance.cleanTags(content); + content = CoreTextUtils.cleanTags(content); } else { - content = CoreTextUtils.instance.replaceNewLines(content, '
'); + content = CoreTextUtils.replaceNewLines(content, '
'); } if (content == ' ') { @@ -105,10 +105,10 @@ export class CoreGradesHelperProvider { row.rowclass += tableRow[name]!.class.indexOf('dimmed_text') >= 0 ? ' dimmed_text' : ''; content = content.replace(/<\/span>/gi, '\n'); - content = CoreTextUtils.instance.cleanTags(content); + content = CoreTextUtils.cleanTags(content); name = 'gradeitem'; } else { - content = CoreTextUtils.instance.replaceNewLines(content, '
'); + content = CoreTextUtils.replaceNewLines(content, '
'); } if (content == ' ') { @@ -208,8 +208,8 @@ export class CoreGradesHelperProvider { let coursesWereMissing = false; try { - const courses = await CoreCourses.instance.getUserCourses(undefined, undefined, CoreSitesReadingStrategy.OnlyCache); - const coursesMap = CoreUtils.instance.arrayToObject(courses, 'id'); + const courses = await CoreCourses.getUserCourses(undefined, undefined, CoreSitesReadingStrategy.OnlyCache); + const coursesMap = CoreUtils.arrayToObject(courses, 'id'); coursesWereMissing = this.addCourseData(grades, coursesMap); } catch { @@ -218,13 +218,13 @@ export class CoreGradesHelperProvider { // If any course wasn't found, make a network request. if (coursesWereMissing) { - const coursesPromise = CoreCourses.instance.isGetCoursesByFieldAvailable() - ? CoreCourses.instance.getCoursesByField('ids', grades.map((grade) => grade.courseid).join(',')) - : CoreCourses.instance.getUserCourses(undefined, undefined, CoreSitesReadingStrategy.PreferNetwork); + const coursesPromise = CoreCourses.isGetCoursesByFieldAvailable() + ? CoreCourses.getCoursesByField('ids', grades.map((grade) => grade.courseid).join(',')) + : CoreCourses.getUserCourses(undefined, undefined, CoreSitesReadingStrategy.PreferNetwork); const courses = await coursesPromise; const coursesMap = - CoreUtils.instance.arrayToObject(courses as Record[], 'id') as + CoreUtils.arrayToObject(courses as Record[], 'id') as Record | Record; @@ -278,7 +278,7 @@ export class CoreGradesHelperProvider { siteId?: string, ignoreCache: boolean = false, ): Promise { - const grades = await CoreGrades.instance.getCourseGradesTable(courseId, userId, siteId, ignoreCache); + const grades = await CoreGrades.getCourseGradesTable(courseId, userId, siteId, ignoreCache); if (!grades) { throw new CoreError('Couldn\'t get grade item'); @@ -329,7 +329,7 @@ export class CoreGradesHelperProvider { siteId?: string, ignoreCache: boolean = false, ): Promise { - const grades = await CoreGrades.instance.getGradeItems(courseId, userId, groupId, siteId, ignoreCache); + const grades = await CoreGrades.getGradeItems(courseId, userId, groupId, siteId, ignoreCache); if (!grades) { throw new CoreError('Couldn\'t get grade module items'); @@ -369,7 +369,7 @@ export class CoreGradesHelperProvider { * @return URL linking to the module. */ protected getModuleLink(text: string): string | false { - const el = CoreDomUtils.instance.toDom(text)[0]; + const el = CoreDomUtils.toDom(text)[0]; const link = el.attributes['href'] ? el.attributes['href'].value : false; if (!link || link.indexOf('/mod/') < 0) { @@ -424,7 +424,7 @@ export class CoreGradesHelperProvider { const matches = row.itemname.content.match(regex); if (matches && matches.length) { - const hrefParams = CoreUrlUtils.instance.extractUrlParams(matches[1]); + const hrefParams = CoreUrlUtils.extractUrlParams(matches[1]); return hrefParams && parseInt(hrefParams.id) === moduleId; } @@ -449,11 +449,11 @@ export class CoreGradesHelperProvider { moduleId?: number, siteId?: string, ): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); let currentUserId: number; try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = site.id; currentUserId = site.getUserId(); @@ -463,7 +463,7 @@ export class CoreGradesHelperProvider { } // Try to open the module grade directly. Check if it's possible. - const grades = await CoreGrades.instance.isGradeItemsAvalaible(siteId); + const grades = await CoreGrades.isGradeItemsAvalaible(siteId); if (!grades) { throw new CoreError('No grades found.'); @@ -471,7 +471,7 @@ export class CoreGradesHelperProvider { try { // Can get grades. Do it. - const items = await CoreGrades.instance.getGradeItems(courseId, userId, undefined, siteId); + const items = await CoreGrades.getGradeItems(courseId, userId, undefined, siteId); // Find the item of the module. const item = Array.isArray(items) && items.find((item) => moduleId == item.cmid); @@ -483,8 +483,8 @@ export class CoreGradesHelperProvider { // Open the item directly. const gradeId = item.id; - await CoreUtils.instance.ignoreErrors( - CoreNavigator.instance.navigateToSitePath(`/grades/${courseId}/${gradeId}`, { + await CoreUtils.ignoreErrors( + CoreNavigator.navigateToSitePath(`/grades/${courseId}/${gradeId}`, { siteId, params: { userId }, }), @@ -493,8 +493,8 @@ export class CoreGradesHelperProvider { // Cannot get grade items or there's no need to. if (userId && userId != currentUserId) { // View another user grades. Open the grades page directly. - await CoreUtils.instance.ignoreErrors( - CoreNavigator.instance.navigateToSitePath(`/grades/${courseId}`, { + await CoreUtils.ignoreErrors( + CoreNavigator.navigateToSitePath(`/grades/${courseId}`, { siteId, params: { userId }, }), @@ -502,23 +502,23 @@ export class CoreGradesHelperProvider { } // View own grades. Check if we already are in the course index page. - if (CoreCourse.instance.currentViewIsCourse(courseId)) { + if (CoreCourse.currentViewIsCourse(courseId)) { // Current view is this course, just select the grades tab. - CoreCourse.instance.selectCourseTab('CoreGrades'); + CoreCourse.selectCourseTab('CoreGrades'); return; } // @todo // Open the course with the grades tab selected. - // await CoreCourseHelper.instance.getCourse(courseId, siteId).then(async (result) => { + // await CoreCourseHelper.getCourse(courseId, siteId).then(async (result) => { // const pageParams = { // course: result.course, // selectedTab: 'CoreGrades', // }; - // // CoreContentLinksHelper.instance.goInSite(navCtrl, 'CoreCourseSectionPage', pageParams, siteId) - // return await CoreUtils.instance.ignoreErrors(CoreNavigator.instance.navigateToSitePath('/course', { + // // CoreContentLinksHelper.goInSite(navCtrl, 'CoreCourseSectionPage', pageParams, siteId) + // return await CoreUtils.ignoreErrors(CoreNavigator.navigateToSitePath('/course', { // siteId, // params: pageParams, // })); @@ -526,7 +526,7 @@ export class CoreGradesHelperProvider { } } catch (error) { // Cannot get course for some reason, just open the grades page. - await CoreNavigator.instance.navigateToSitePath(`/grades/${courseId}`, { siteId }); + await CoreNavigator.navigateToSitePath(`/grades/${courseId}`, { siteId }); } finally { modal.dismiss(); } @@ -542,16 +542,16 @@ export class CoreGradesHelperProvider { * @return Promise to be resolved when the grades are invalidated. */ async invalidateGradeModuleItems(courseId: number, userId?: number, groupId?: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); - const enabled = await CoreGrades.instance.isGradeItemsAvalaible(siteId); + const enabled = await CoreGrades.isGradeItemsAvalaible(siteId); return enabled - ? CoreGrades.instance.invalidateCourseGradesItemsData(courseId, userId, groupId, siteId) - : CoreGrades.instance.invalidateCourseGradesData(courseId, userId, siteId); + ? CoreGrades.invalidateCourseGradesItemsData(courseId, userId, groupId, siteId) + : CoreGrades.invalidateCourseGradesData(courseId, userId, siteId); } /** @@ -587,9 +587,9 @@ export class CoreGradesHelperProvider { if (typeof module?.[1] != 'undefined') { row.itemtype = 'mod'; row.itemmodule = module[1]; - row.image = CoreCourse.instance.getModuleIconSrc( + row.image = CoreCourse.getModuleIconSrc( module[1], - CoreDomUtils.instance.convertToElement(text).querySelector('img')?.getAttribute('src') ?? undefined, + CoreDomUtils.convertToElement(text).querySelector('img')?.getAttribute('src') ?? undefined, ); } } else { @@ -633,11 +633,11 @@ export class CoreGradesHelperProvider { ): Promise { if (gradingType < 0) { if (scale) { - return Promise.resolve(CoreUtils.instance.makeMenuFromList(scale, defaultLabel, undefined, defaultValue)); + return Promise.resolve(CoreUtils.makeMenuFromList(scale, defaultLabel, undefined, defaultValue)); } else if (moduleId) { - return CoreCourse.instance.getModuleBasicGradeInfo(moduleId).then((gradeInfo) => { + return CoreCourse.getModuleBasicGradeInfo(moduleId).then((gradeInfo) => { if (gradeInfo && gradeInfo.scale) { - return CoreUtils.instance.makeMenuFromList(gradeInfo.scale, defaultLabel, undefined, defaultValue); + return CoreUtils.makeMenuFromList(gradeInfo.scale, defaultLabel, undefined, defaultValue); } return []; @@ -681,7 +681,7 @@ export class CoreGradesHelperProvider { } -export class CoreGradesHelper extends makeSingleton(CoreGradesHelperProvider) {} +export const CoreGradesHelper = makeSingleton(CoreGradesHelperProvider); // @todo formatted data types. export type CoreGradesFormattedRowForTable = any; diff --git a/src/core/features/grades/services/grades.ts b/src/core/features/grades/services/grades.ts index 9986009f9..74c680a9d 100644 --- a/src/core/features/grades/services/grades.ts +++ b/src/core/features/grades/services/grades.ts @@ -101,9 +101,9 @@ export class CoreGradesProvider { siteId?: string, ignoreCache: boolean = false, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -139,7 +139,7 @@ export class CoreGradesProvider { siteId?: string, ignoreCache: boolean = false, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); groupId = groupId || 0; @@ -188,7 +188,7 @@ export class CoreGradesProvider { siteId?: string, ignoreCache: boolean = false, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -223,7 +223,7 @@ export class CoreGradesProvider { * @return Promise to be resolved when the grades are retrieved. */ async getCoursesGrades(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); this.logger.debug('Get course grades'); @@ -253,7 +253,7 @@ export class CoreGradesProvider { * @return Promise resolved when the data is invalidated. */ invalidateAllCourseGradesData(courseId: number, siteId?: string): Promise { - return CoreSites.instance.getSite(siteId) + return CoreSites.getSite(siteId) .then((site) => site.invalidateWsCacheForKeyStartingWith(this.getCourseGradesPrefixCacheKey(courseId))); } @@ -266,7 +266,7 @@ export class CoreGradesProvider { * @return Promise resolved when the data is invalidated. */ invalidateCourseGradesData(courseId: number, userId?: number, siteId?: string): Promise { - return CoreSites.instance.getSite(siteId).then((site) => { + return CoreSites.getSite(siteId).then((site) => { userId = userId || site.getUserId(); return site.invalidateWsCacheForKey(this.getCourseGradesCacheKey(courseId, userId)); @@ -280,7 +280,7 @@ export class CoreGradesProvider { * @return Promise resolved when the data is invalidated. */ invalidateCoursesGradesData(siteId?: string): Promise { - return CoreSites.instance.getSite(siteId).then((site) => site.invalidateWsCacheForKey(this.getCoursesGradesCacheKey())); + return CoreSites.getSite(siteId).then((site) => site.invalidateWsCacheForKey(this.getCoursesGradesCacheKey())); } /** @@ -293,7 +293,7 @@ export class CoreGradesProvider { * @return Promise resolved when the data is invalidated. */ invalidateCourseGradesItemsData(courseId: number, userId: number, groupId?: number, siteId?: string): Promise { - return CoreSites.instance.getSite(siteId) + return CoreSites.getSite(siteId) .then((site) => site.invalidateWsCacheForKey(this.getCourseGradesItemsCacheKey(courseId, userId, groupId))); } @@ -305,7 +305,7 @@ export class CoreGradesProvider { * @since Moodle 3.2 */ isCourseGradesEnabled(siteId?: string): Promise { - return CoreSites.instance.getSite(siteId).then((site) => { + return CoreSites.getSite(siteId).then((site) => { if (!site.wsAvailable('gradereport_overview_get_course_grades')) { return false; } @@ -328,7 +328,7 @@ export class CoreGradesProvider { return Promise.reject(null); } - return CoreCourses.instance.getUserCourse(courseId, true, siteId) + return CoreCourses.getUserCourse(courseId, true, siteId) .then((course) => !(course && typeof course.showgrades != 'undefined' && !course.showgrades)); } @@ -340,7 +340,7 @@ export class CoreGradesProvider { * @since Moodle 3.2 */ async isGradeItemsAvalaible(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.wsAvailable('gradereport_user_get_grade_items'); } @@ -354,15 +354,15 @@ export class CoreGradesProvider { * @return Promise resolved when done. */ async logCourseGradesView(courseId: number, userId: number, name?: string): Promise { - userId = userId || CoreSites.instance.getCurrentSiteUserId(); + userId = userId || CoreSites.getCurrentSiteUserId(); const wsName = 'gradereport_user_view_grade_report'; if (!name) { // eslint-disable-next-line promise/catch-or-return - CoreCourses.instance.getUserCourse(courseId, true) + CoreCourses.getUserCourse(courseId, true) .catch(() => ({})) - .then(course => CorePushNotifications.instance.logViewEvent( + .then(course => CorePushNotifications.logViewEvent( courseId, 'fullname' in course ? course.fullname : '', 'grades', @@ -370,10 +370,10 @@ export class CoreGradesProvider { { userid: userId }, )); } else { - CorePushNotifications.instance.logViewEvent(courseId, name, 'grades', wsName, { userid: userId }); + CorePushNotifications.logViewEvent(courseId, name, 'grades', wsName, { userid: userId }); } - const site = await CoreSites.instance.getCurrentSite(); + const site = await CoreSites.getCurrentSite(); await site?.write(wsName, { courseid: courseId, userid: userId }); } @@ -386,23 +386,23 @@ export class CoreGradesProvider { */ async logCoursesGradesView(courseId?: number): Promise { if (!courseId) { - courseId = CoreSites.instance.getCurrentSiteHomeId(); + courseId = CoreSites.getCurrentSiteHomeId(); } const params = { courseid: courseId, }; - CorePushNotifications.instance.logViewListEvent('grades', 'gradereport_overview_view_grade_report', params); + CorePushNotifications.logViewListEvent('grades', 'gradereport_overview_view_grade_report', params); - const site = await CoreSites.instance.getCurrentSite(); + const site = await CoreSites.getCurrentSite(); await site?.write('gradereport_overview_view_grade_report', params); } } -export class CoreGrades extends makeSingleton(CoreGradesProvider) {} +export const CoreGrades = makeSingleton(CoreGradesProvider); /** * Params of gradereport_user_get_grade_items WS. diff --git a/src/core/features/grades/services/handlers/course-option.ts b/src/core/features/grades/services/handlers/course-option.ts index dae804c8a..0621b9a7a 100644 --- a/src/core/features/grades/services/handlers/course-option.ts +++ b/src/core/features/grades/services/handlers/course-option.ts @@ -46,7 +46,7 @@ export class CoreGradesCourseOptionHandlerService implements CoreCourseOptionsHa return Promise.resolve(); } - return CoreCourses.instance.invalidateUserCourses(); + return CoreCourses.invalidateUserCourses(); } /** @@ -79,7 +79,7 @@ export class CoreGradesCourseOptionHandlerService implements CoreCourseOptionsHa return navOptions.grades; } - return CoreGrades.instance.isPluginEnabledForCourse(courseId); + return CoreGrades.isPluginEnabledForCourse(courseId); } /** @@ -100,9 +100,9 @@ export class CoreGradesCourseOptionHandlerService implements CoreCourseOptionsHa * @return Promise resolved when done. */ async prefetch(course: CoreEnrolledCourseDataWithExtraInfoAndOptions): Promise { - await CoreGrades.instance.getCourseGradesTable(course.id, undefined, undefined, true); + await CoreGrades.getCourseGradesTable(course.id, undefined, undefined, true); } } -export class CoreGradesCourseOptionHandler extends makeSingleton(CoreGradesCourseOptionHandlerService) {} +export const CoreGradesCourseOptionHandler = makeSingleton(CoreGradesCourseOptionHandlerService); diff --git a/src/core/features/grades/services/handlers/mainmenu.ts b/src/core/features/grades/services/handlers/mainmenu.ts index b39b77f04..344cfd6d3 100644 --- a/src/core/features/grades/services/handlers/mainmenu.ts +++ b/src/core/features/grades/services/handlers/mainmenu.ts @@ -34,7 +34,7 @@ export class CoreGradesMainMenuHandlerService implements CoreMainMenuHandler { * @return Whether or not the handler is enabled on a site level. */ isEnabled(): Promise { - return CoreGrades.instance.isCourseGradesEnabled(); + return CoreGrades.isCourseGradesEnabled(); } /** @@ -53,4 +53,4 @@ export class CoreGradesMainMenuHandlerService implements CoreMainMenuHandler { } -export default class CoreGradesMainMenuHandler extends makeSingleton(CoreGradesMainMenuHandlerService) {} +export const CoreGradesMainMenuHandler = makeSingleton(CoreGradesMainMenuHandlerService); diff --git a/src/core/features/grades/services/handlers/overview-link.ts b/src/core/features/grades/services/handlers/overview-link.ts index a13399431..ddfd90351 100644 --- a/src/core/features/grades/services/handlers/overview-link.ts +++ b/src/core/features/grades/services/handlers/overview-link.ts @@ -36,7 +36,7 @@ export class CoreGradesOverviewLinkHandlerService extends CoreContentLinksHandle getActions(): CoreContentLinksAction[] | Promise { return [{ action: siteId => { - CoreNavigator.instance.navigateToSitePath('/grades', { siteId }); + CoreNavigator.navigateToSitePath('/grades', { siteId }); }, }]; } @@ -49,9 +49,9 @@ export class CoreGradesOverviewLinkHandlerService extends CoreContentLinksHandle * @return Whether the handler is enabled for the URL and site. */ async isEnabled(siteId: string): Promise { - return CoreGrades.instance.isCourseGradesEnabled(siteId); + return CoreGrades.isCourseGradesEnabled(siteId); } } -export class CoreGradesOverviewLinkHandler extends makeSingleton(CoreGradesOverviewLinkHandlerService) {} +export const CoreGradesOverviewLinkHandler = makeSingleton(CoreGradesOverviewLinkHandlerService); diff --git a/src/core/features/grades/services/handlers/user-link.ts b/src/core/features/grades/services/handlers/user-link.ts index a70b6b7bd..432ff1937 100644 --- a/src/core/features/grades/services/handlers/user-link.ts +++ b/src/core/features/grades/services/handlers/user-link.ts @@ -54,7 +54,7 @@ export class CoreGradesUserLinkHandlerService extends CoreContentLinksHandlerBas const userId = params.userid ? parseInt(params.userid, 10) : undefined; const moduleId = data?.cmid && parseInt(data.cmid, 10) || undefined; - CoreGradesHelper.instance.goToGrades(courseId!, userId, moduleId, siteId); + CoreGradesHelper.goToGrades(courseId!, userId, moduleId, siteId); }, }]; } @@ -74,9 +74,9 @@ export class CoreGradesUserLinkHandlerService extends CoreContentLinksHandlerBas return false; } - return CoreGrades.instance.isPluginEnabledForCourse(courseId || Number(params.id), siteId); + return CoreGrades.isPluginEnabledForCourse(courseId || Number(params.id), siteId); } } -export class CoreGradesUserLinkHandler extends makeSingleton(CoreGradesUserLinkHandlerService) {} +export const CoreGradesUserLinkHandler = makeSingleton(CoreGradesUserLinkHandlerService); diff --git a/src/core/features/grades/services/handlers/user.ts b/src/core/features/grades/services/handlers/user.ts index 2895a2fe4..1d7db05d5 100644 --- a/src/core/features/grades/services/handlers/user.ts +++ b/src/core/features/grades/services/handlers/user.ts @@ -86,7 +86,7 @@ export class CoreGradesUserHandlerService implements CoreUserProfileHandler { return cache; } - const enabled = await CoreUtils.instance.ignoreErrors(CoreGrades.instance.isPluginEnabledForCourse(courseId), false); + const enabled = await CoreUtils.ignoreErrors(CoreGrades.isPluginEnabledForCourse(courseId), false); this.viewGradesEnabledCache[cacheKey] = enabled; @@ -106,7 +106,7 @@ export class CoreGradesUserHandlerService implements CoreUserProfileHandler { action: (event, user, courseId): void => { event.preventDefault(); event.stopPropagation(); - CoreNavigator.instance.navigateToSitePath(`/grades/${courseId}`, { + CoreNavigator.navigateToSitePath(`/grades/${courseId}`, { params: { userId: user.id }, }); }, @@ -115,4 +115,4 @@ export class CoreGradesUserHandlerService implements CoreUserProfileHandler { } -export class CoreGradesUserHandler extends makeSingleton(CoreGradesUserHandlerService) {} +export const CoreGradesUserHandler = makeSingleton(CoreGradesUserHandlerService); diff --git a/src/core/features/h5p/classes/content-validator.ts b/src/core/features/h5p/classes/content-validator.ts index a65c8f4f3..dd27fa6ef 100644 --- a/src/core/features/h5p/classes/content-validator.ts +++ b/src/core/features/h5p/classes/content-validator.ts @@ -65,7 +65,7 @@ export class CoreH5PContentValidator { type: 'preloaded', }; - this.nextWeight = await CoreH5P.instance.h5pCore.findLibraryDependencies(this.dependencies, library, this.nextWeight); + this.nextWeight = await CoreH5P.h5pCore.findLibraryDependencies(this.dependencies, library, this.nextWeight); this.dependencies[depKey].weight = this.nextWeight++; } @@ -88,7 +88,7 @@ export class CoreH5PContentValidator { // eslint-disable-next-line @typescript-eslint/no-explicit-any validateMetadata(metadata: any): Promise { const semantics = this.getMetadataSemantics(); - const group = CoreUtils.instance.clone(metadata || {}); + const group = CoreUtils.clone(metadata || {}); // Stop complaining about "invalid selected option in select" for old content without license chosen. if (typeof group.license == 'undefined') { @@ -131,7 +131,7 @@ export class CoreH5PContentValidator { tags.push('s'); } - tags = CoreUtils.instance.uniqueArray(tags); + tags = CoreUtils.uniqueArray(tags); // Determine allowed style tags const stylePatterns: RegExp[] = []; @@ -164,7 +164,7 @@ export class CoreH5PContentValidator { text = this.filterXss(text, tags, stylePatterns); } else { // Filter text to plain text. - text = CoreTextUtils.instance.escapeHTML(text, false); + text = CoreTextUtils.escapeHTML(text, false); } // Check if string is within allowed length. @@ -270,7 +270,7 @@ export class CoreH5PContentValidator { if (strict && !optional && !options[value]) { delete select[key]; } else { - select[key] = CoreTextUtils.instance.escapeHTML(value, false); + select[key] = CoreTextUtils.escapeHTML(value, false); } } } else { @@ -282,7 +282,7 @@ export class CoreH5PContentValidator { if (strict && !optional && !options[select]) { select = ( semantics.options![0]).value || ''; } - select = CoreTextUtils.instance.escapeHTML(select, false); + select = CoreTextUtils.escapeHTML(select, false); } return select; @@ -331,7 +331,7 @@ export class CoreH5PContentValidator { } if (!isArray) { - list = CoreUtils.instance.objectToArray(> list); + list = CoreUtils.objectToArray(> list); } if (!list.length) { @@ -362,9 +362,9 @@ export class CoreH5PContentValidator { } // Make sure path and mime does not have any special chars - file.path = CoreTextUtils.instance.escapeHTML(file.path, false); + file.path = CoreTextUtils.escapeHTML(file.path, false); if (file.mime) { - file.mime = CoreTextUtils.instance.escapeHTML(file.mime, false); + file.mime = CoreTextUtils.escapeHTML(file.mime, false); } // Remove attributes that should not exist, they may contain JSON escape code. @@ -372,7 +372,7 @@ export class CoreH5PContentValidator { if (semantics.extraAttributes) { validKeys = validKeys.concat(semantics.extraAttributes); } - validKeys = CoreUtils.instance.uniqueArray(validKeys); + validKeys = CoreUtils.uniqueArray(validKeys); this.filterParams(file, validKeys); @@ -385,7 +385,7 @@ export class CoreH5PContentValidator { } if (file.codecs) { - file.codecs = CoreTextUtils.instance.escapeHTML(file.codecs, false); + file.codecs = CoreTextUtils.escapeHTML(file.codecs, false); } if (typeof file.bitrate == 'string') { @@ -398,7 +398,7 @@ export class CoreH5PContentValidator { } else { this.filterParams(file.quality, ['level', 'label']); file.quality.level = Number(file.quality.level); - file.quality.label = CoreTextUtils.instance.escapeHTML(file.quality.label, false); + file.quality.label = CoreTextUtils.escapeHTML(file.quality.label, false); } } @@ -545,7 +545,7 @@ export class CoreH5PContentValidator { // Load the library and store it in the index of libraries. const libSpec = CoreH5PCore.libraryFromString(value.library); - this.libraries[value.library] = await CoreH5P.instance.h5pCore.loadLibrary( + this.libraries[value.library] = await CoreH5P.h5pCore.loadLibrary( libSpec?.machineName || '', libSpec?.majorVersion || 0, libSpec?.minorVersion || 0, @@ -565,7 +565,7 @@ export class CoreH5PContentValidator { let validKeys = ['library', 'params', 'subContentId', 'metadata']; if (semantics.extraAttributes) { - validKeys = CoreUtils.instance.uniqueArray(validKeys.concat(semantics.extraAttributes)); + validKeys = CoreUtils.uniqueArray(validKeys.concat(semantics.extraAttributes)); } this.filterParams(value, validKeys); @@ -583,7 +583,7 @@ export class CoreH5PContentValidator { type: 'preloaded', }; - this.nextWeight = await CoreH5P.instance.h5pCore.findLibraryDependencies(this.dependencies, library, this.nextWeight); + this.nextWeight = await CoreH5P.h5pCore.findLibraryDependencies(this.dependencies, library, this.nextWeight); this.dependencies[depKey].weight = this.nextWeight++; @@ -663,7 +663,7 @@ export class CoreH5PContentValidator { */ protected filterXssSplit(tags: string[], store: boolean = false): string { if (store) { - this.allowedHtml = CoreUtils.instance.arrayToObject(tags); + this.allowedHtml = CoreUtils.arrayToObject(tags); return ''; } @@ -853,10 +853,10 @@ export class CoreH5PContentValidator { filterXssBadProtocol(str: string, decode: boolean = true): string { // Get the plain text representation of the attribute value (i.e. its meaning). if (decode) { - str = CoreTextUtils.instance.decodeHTMLEntities(str); + str = CoreTextUtils.decodeHTMLEntities(str); } - return CoreTextUtils.instance.escapeHTML(this.stripDangerousProtocols(str), false); + return CoreTextUtils.escapeHTML(this.stripDangerousProtocols(str), false); } /** @@ -915,92 +915,92 @@ export class CoreH5PContentValidator { { name: 'title', type: 'text', - label: Translate.instance.instant('core.h5p.title'), + label: Translate.instant('core.h5p.title'), placeholder: 'La Gioconda', }, { name: 'license', type: 'select', - label: Translate.instance.instant('core.h5p.license'), + label: Translate.instant('core.h5p.license'), default: 'U', options: [ { value: 'U', - label: Translate.instance.instant('core.h5p.undisclosed'), + label: Translate.instant('core.h5p.undisclosed'), }, { type: 'optgroup', - label: Translate.instance.instant('core.h5p.creativecommons'), + label: Translate.instant('core.h5p.creativecommons'), options: [ { value: 'CC BY', - label: Translate.instance.instant('core.h5p.ccattribution'), + label: Translate.instant('core.h5p.ccattribution'), versions: ccVersions, }, { value: 'CC BY-SA', - label: Translate.instance.instant('core.h5p.ccattributionsa'), + label: Translate.instant('core.h5p.ccattributionsa'), versions: ccVersions, }, { value: 'CC BY-ND', - label: Translate.instance.instant('core.h5p.ccattributionnd'), + label: Translate.instant('core.h5p.ccattributionnd'), versions: ccVersions, }, { value: 'CC BY-NC', - label: Translate.instance.instant('core.h5p.ccattributionnc'), + label: Translate.instant('core.h5p.ccattributionnc'), versions: ccVersions, }, { value: 'CC BY-NC-SA', - label: Translate.instance.instant('core.h5p.ccattributionncsa'), + label: Translate.instant('core.h5p.ccattributionncsa'), versions: ccVersions, }, { value: 'CC BY-NC-ND', - label: Translate.instance.instant('core.h5p.ccattributionncnd'), + label: Translate.instant('core.h5p.ccattributionncnd'), versions: ccVersions, }, { value: 'CC0 1.0', - label: Translate.instance.instant('core.h5p.ccpdd'), + label: Translate.instant('core.h5p.ccpdd'), }, { value: 'CC PDM', - label: Translate.instance.instant('core.h5p.pdm'), + label: Translate.instant('core.h5p.pdm'), }, ], }, { value: 'GNU GPL', - label: Translate.instance.instant('core.h5p.gpl'), + label: Translate.instant('core.h5p.gpl'), }, { value: 'PD', - label: Translate.instance.instant('core.h5p.pd'), + label: Translate.instant('core.h5p.pd'), }, { value: 'ODC PDDL', - label: Translate.instance.instant('core.h5p.pddl'), + label: Translate.instant('core.h5p.pddl'), }, { value: 'C', - label: Translate.instance.instant('core.h5p.copyrightstring'), + label: Translate.instant('core.h5p.copyrightstring'), }, ], }, { name: 'licenseVersion', type: 'select', - label: Translate.instance.instant('core.h5p.licenseversion'), + label: Translate.instant('core.h5p.licenseversion'), options: ccVersions, optional: true, }, { name: 'yearFrom', type: 'number', - label: Translate.instance.instant('core.h5p.yearsfrom'), + label: Translate.instant('core.h5p.yearsfrom'), placeholder: '1991', min: -9999, max: 9999, @@ -1009,7 +1009,7 @@ export class CoreH5PContentValidator { { name: 'yearTo', type: 'number', - label: Translate.instance.instant('core.h5p.yearsto'), + label: Translate.instant('core.h5p.yearsto'), placeholder: '1992', min: -9999, max: 9999, @@ -1018,7 +1018,7 @@ export class CoreH5PContentValidator { { name: 'source', type: 'text', - label: Translate.instance.instant('core.h5p.source'), + label: Translate.instant('core.h5p.source'), placeholder: 'https://', optional: true, }, @@ -1030,7 +1030,7 @@ export class CoreH5PContentValidator { type: 'group', fields: [ { - label: Translate.instance.instant('core.h5p.authorname'), + label: Translate.instant('core.h5p.authorname'), name: 'name', optional: true, type: 'text', @@ -1038,24 +1038,24 @@ export class CoreH5PContentValidator { { name: 'role', type: 'select', - label: Translate.instance.instant('core.h5p.authorrole'), + label: Translate.instant('core.h5p.authorrole'), default: 'Author', options: [ { value: 'Author', - label: Translate.instance.instant('core.h5p.author'), + label: Translate.instant('core.h5p.author'), }, { value: 'Editor', - label: Translate.instance.instant('core.h5p.editor'), + label: Translate.instant('core.h5p.editor'), }, { value: 'Licensee', - label: Translate.instance.instant('core.h5p.licensee'), + label: Translate.instant('core.h5p.licensee'), }, { value: 'Originator', - label: Translate.instance.instant('core.h5p.originator'), + label: Translate.instant('core.h5p.originator'), }, ], }, @@ -1066,9 +1066,9 @@ export class CoreH5PContentValidator { name: 'licenseExtras', type: 'text', widget: 'textarea', - label: Translate.instance.instant('core.h5p.licenseextras'), + label: Translate.instant('core.h5p.licenseextras'), optional: true, - description: Translate.instance.instant('core.h5p.additionallicenseinfo'), + description: Translate.instant('core.h5p.additionallicenseinfo'), }, { name: 'changes', @@ -1076,26 +1076,26 @@ export class CoreH5PContentValidator { field: { name: 'change', type: 'group', - label: Translate.instance.instant('core.h5p.changelog'), + label: Translate.instant('core.h5p.changelog'), fields: [ { name: 'date', type: 'text', - label: Translate.instance.instant('core.h5p.date'), + label: Translate.instant('core.h5p.date'), optional: true, }, { name: 'author', type: 'text', - label: Translate.instance.instant('core.h5p.changedby'), + label: Translate.instant('core.h5p.changedby'), optional: true, }, { name: 'log', type: 'text', widget: 'textarea', - label: Translate.instance.instant('core.h5p.changedescription'), - placeholder: Translate.instance.instant('core.h5p.changeplaceholder'), + label: Translate.instant('core.h5p.changedescription'), + placeholder: Translate.instant('core.h5p.changeplaceholder'), optional: true, }, ], @@ -1105,8 +1105,8 @@ export class CoreH5PContentValidator { name: 'authorComments', type: 'text', widget: 'textarea', - label: Translate.instance.instant('core.h5p.authorcomments'), - description: Translate.instance.instant('core.h5p.authorcommentsdescription'), + label: Translate.instant('core.h5p.authorcomments'), + description: Translate.instant('core.h5p.authorcommentsdescription'), optional: true, }, { @@ -1140,33 +1140,33 @@ export class CoreH5PContentValidator { this.copyrightSemantics = { name: 'copyright', type: 'group', - label: Translate.instance.instant('core.h5p.copyrightinfo'), + label: Translate.instant('core.h5p.copyrightinfo'), fields: [ { name: 'title', type: 'text', - label: Translate.instance.instant('core.h5p.title'), + label: Translate.instant('core.h5p.title'), placeholder: 'La Gioconda', optional: true, }, { name: 'author', type: 'text', - label: Translate.instance.instant('core.h5p.author'), + label: Translate.instant('core.h5p.author'), placeholder: 'Leonardo da Vinci', optional: true, }, { name: 'year', type: 'text', - label: Translate.instance.instant('core.h5p.years'), + label: Translate.instant('core.h5p.years'), placeholder: '1503 - 1517', optional: true, }, { name: 'source', type: 'text', - label: Translate.instance.instant('core.h5p.source'), + label: Translate.instant('core.h5p.source'), placeholder: 'http://en.wikipedia.org/wiki/Mona_Lisa', optional: true, regexp: { @@ -1177,64 +1177,64 @@ export class CoreH5PContentValidator { { name: 'license', type: 'select', - label: Translate.instance.instant('core.h5p.license'), + label: Translate.instant('core.h5p.license'), default: 'U', options: [ { value: 'U', - label: Translate.instance.instant('core.h5p.undisclosed'), + label: Translate.instant('core.h5p.undisclosed'), }, { value: 'CC BY', - label: Translate.instance.instant('core.h5p.ccattribution'), + label: Translate.instant('core.h5p.ccattribution'), versions: ccVersions, }, { value: 'CC BY-SA', - label: Translate.instance.instant('core.h5p.ccattributionsa'), + label: Translate.instant('core.h5p.ccattributionsa'), versions: ccVersions, }, { value: 'CC BY-ND', - label: Translate.instance.instant('core.h5p.ccattributionnd'), + label: Translate.instant('core.h5p.ccattributionnd'), versions: ccVersions, }, { value: 'CC BY-NC', - label: Translate.instance.instant('core.h5p.ccattributionnc'), + label: Translate.instant('core.h5p.ccattributionnc'), versions: ccVersions, }, { value: 'CC BY-NC-SA', - label: Translate.instance.instant('core.h5p.ccattributionncsa'), + label: Translate.instant('core.h5p.ccattributionncsa'), versions: ccVersions, }, { value: 'CC BY-NC-ND', - label: Translate.instance.instant('core.h5p.ccattributionncnd'), + label: Translate.instant('core.h5p.ccattributionncnd'), versions: ccVersions, }, { value: 'GNU GPL', - label: Translate.instance.instant('core.h5p.licenseGPL'), + label: Translate.instant('core.h5p.licenseGPL'), versions: [ { value: 'v3', - label: Translate.instance.instant('core.h5p.licenseV3'), + label: Translate.instant('core.h5p.licenseV3'), }, { value: 'v2', - label: Translate.instance.instant('core.h5p.licenseV2'), + label: Translate.instant('core.h5p.licenseV2'), }, { value: 'v1', - label: Translate.instance.instant('core.h5p.licenseV1'), + label: Translate.instant('core.h5p.licenseV1'), }, ], }, { value: 'PD', - label: Translate.instance.instant('core.h5p.pd'), + label: Translate.instant('core.h5p.pd'), versions: [ { value: '-', @@ -1242,24 +1242,24 @@ export class CoreH5PContentValidator { }, { value: 'CC0 1.0', - label: Translate.instance.instant('core.h5p.licenseCC010U'), + label: Translate.instant('core.h5p.licenseCC010U'), }, { value: 'CC PDM', - label: Translate.instance.instant('core.h5p.pdm'), + label: Translate.instant('core.h5p.pdm'), }, ], }, { value: 'C', - label: Translate.instance.instant('core.h5p.copyrightstring'), + label: Translate.instant('core.h5p.copyrightstring'), }, ], }, { name: 'version', type: 'select', - label: Translate.instance.instant('core.h5p.licenseversion'), + label: Translate.instant('core.h5p.licenseversion'), options: [], }, ], @@ -1277,23 +1277,23 @@ export class CoreH5PContentValidator { return [ { value: '4.0', - label: Translate.instance.instant('core.h5p.licenseCC40'), + label: Translate.instant('core.h5p.licenseCC40'), }, { value: '3.0', - label: Translate.instance.instant('core.h5p.licenseCC30'), + label: Translate.instant('core.h5p.licenseCC30'), }, { value: '2.5', - label: Translate.instance.instant('core.h5p.licenseCC25'), + label: Translate.instant('core.h5p.licenseCC25'), }, { value: '2.0', - label: Translate.instance.instant('core.h5p.licenseCC20'), + label: Translate.instant('core.h5p.licenseCC20'), }, { value: '1.0', - label: Translate.instance.instant('core.h5p.licenseCC10'), + label: Translate.instant('core.h5p.licenseCC10'), }, ]; } diff --git a/src/core/features/h5p/classes/core.ts b/src/core/features/h5p/classes/core.ts index c0d65a380..e2b5acb1b 100644 --- a/src/core/features/h5p/classes/core.ts +++ b/src/core/features/h5p/classes/core.ts @@ -141,14 +141,14 @@ export class CoreH5PCore { * @return array The array containg urls of the core JavaScript files: */ static getScripts(): string[] { - const libUrl = CoreH5P.instance.h5pCore.h5pFS.getCoreH5PPath(); + const libUrl = CoreH5P.h5pCore.h5pFS.getCoreH5PPath(); const urls: string[] = []; CoreH5PCore.SCRIPTS.forEach((script) => { urls.push(libUrl + script); }); - urls.push(CoreTextUtils.instance.concatenatePaths(libUrl, 'moodle/js/h5p_overrides.js')); + urls.push(CoreTextUtils.concatenatePaths(libUrl, 'moodle/js/h5p_overrides.js')); return urls; } @@ -235,7 +235,7 @@ export class CoreH5PCore { * @return Promise resolved with the filtered params, resolved with null if error. */ async filterParameters(content: CoreH5PContentData, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (content.filtered) { return content.filtered; @@ -247,7 +247,7 @@ export class CoreH5PCore { const params = { library: CoreH5PCore.libraryToString(content.library), - params: CoreTextUtils.instance.parseJSON(content.params, false), + params: CoreTextUtils.parseJSON(content.params, false), }; if (!params.params) { @@ -332,7 +332,7 @@ export class CoreH5PCore { siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const types = ['dynamic', 'preloaded', 'editor']; @@ -456,7 +456,7 @@ export class CoreH5PCore { // Add URL prefix if not external. if (asset.path.indexOf('://') == -1 && assetsFolderPath) { - url = CoreTextUtils.instance.concatenatePaths(assetsFolderPath, url); + url = CoreTextUtils.concatenatePaths(assetsFolderPath, url); } // Add version if set. @@ -485,7 +485,7 @@ export class CoreH5PCore { prefix: string = '', siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Build files list for assets. const files: CoreH5PDependenciesFiles = { @@ -547,7 +547,7 @@ export class CoreH5PCore { * @return Promise resolved with an object containing the path of each content dependency. */ async getDependencyRoots(id: number, siteId?: string): Promise<{[libString: string]: string}> { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const roots = {}; @@ -584,7 +584,7 @@ export class CoreH5PCore { } // Check if we should skip CSS. - if (type === 'preloadedCss' && CoreUtils.instance.isTrueOrOne(dependency.dropCss)) { + if (type === 'preloadedCss' && CoreUtils.isTrueOrOne(dependency.dropCss)) { return; } @@ -636,73 +636,73 @@ export class CoreH5PCore { */ getLocalization(): {[name: string]: string} { return { - fullscreen: Translate.instance.instant('core.h5p.fullscreen'), - disableFullscreen: Translate.instance.instant('core.h5p.disablefullscreen'), - download: Translate.instance.instant('core.h5p.download'), - copyrights: Translate.instance.instant('core.h5p.copyright'), - embed: Translate.instance.instant('core.h5p.embed'), - size: Translate.instance.instant('core.h5p.size'), - showAdvanced: Translate.instance.instant('core.h5p.showadvanced'), - hideAdvanced: Translate.instance.instant('core.h5p.hideadvanced'), - advancedHelp: Translate.instance.instant('core.h5p.resizescript'), - copyrightInformation: Translate.instance.instant('core.h5p.copyright'), - close: Translate.instance.instant('core.h5p.close'), - title: Translate.instance.instant('core.h5p.title'), - author: Translate.instance.instant('core.h5p.author'), - year: Translate.instance.instant('core.h5p.year'), - source: Translate.instance.instant('core.h5p.source'), - license: Translate.instance.instant('core.h5p.license'), - thumbnail: Translate.instance.instant('core.h5p.thumbnail'), - noCopyrights: Translate.instance.instant('core.h5p.nocopyright'), - reuse: Translate.instance.instant('core.h5p.reuse'), - reuseContent: Translate.instance.instant('core.h5p.reuseContent'), - reuseDescription: Translate.instance.instant('core.h5p.reuseDescription'), - downloadDescription: Translate.instance.instant('core.h5p.downloadtitle'), - copyrightsDescription: Translate.instance.instant('core.h5p.copyrighttitle'), - embedDescription: Translate.instance.instant('core.h5p.embedtitle'), - h5pDescription: Translate.instance.instant('core.h5p.h5ptitle'), - contentChanged: Translate.instance.instant('core.h5p.contentchanged'), - startingOver: Translate.instance.instant('core.h5p.startingover'), - by: Translate.instance.instant('core.h5p.by'), - showMore: Translate.instance.instant('core.h5p.showmore'), - showLess: Translate.instance.instant('core.h5p.showless'), - subLevel: Translate.instance.instant('core.h5p.sublevel'), - confirmDialogHeader: Translate.instance.instant('core.h5p.confirmdialogheader'), - confirmDialogBody: Translate.instance.instant('core.h5p.confirmdialogbody'), - cancelLabel: Translate.instance.instant('core.h5p.cancellabel'), - confirmLabel: Translate.instance.instant('core.h5p.confirmlabel'), - licenseU: Translate.instance.instant('core.h5p.undisclosed'), - licenseCCBY: Translate.instance.instant('core.h5p.ccattribution'), - licenseCCBYSA: Translate.instance.instant('core.h5p.ccattributionsa'), - licenseCCBYND: Translate.instance.instant('core.h5p.ccattributionnd'), - licenseCCBYNC: Translate.instance.instant('core.h5p.ccattributionnc'), - licenseCCBYNCSA: Translate.instance.instant('core.h5p.ccattributionncsa'), - licenseCCBYNCND: Translate.instance.instant('core.h5p.ccattributionncnd'), - licenseCC40: Translate.instance.instant('core.h5p.licenseCC40'), - licenseCC30: Translate.instance.instant('core.h5p.licenseCC30'), - licenseCC25: Translate.instance.instant('core.h5p.licenseCC25'), - licenseCC20: Translate.instance.instant('core.h5p.licenseCC20'), - licenseCC10: Translate.instance.instant('core.h5p.licenseCC10'), - licenseGPL: Translate.instance.instant('core.h5p.licenseGPL'), - licenseV3: Translate.instance.instant('core.h5p.licenseV3'), - licenseV2: Translate.instance.instant('core.h5p.licenseV2'), - licenseV1: Translate.instance.instant('core.h5p.licenseV1'), - licensePD: Translate.instance.instant('core.h5p.pd'), - licenseCC010: Translate.instance.instant('core.h5p.licenseCC010'), - licensePDM: Translate.instance.instant('core.h5p.pdm'), - licenseC: Translate.instance.instant('core.h5p.copyrightstring'), - contentType: Translate.instance.instant('core.h5p.contenttype'), - licenseExtras: Translate.instance.instant('core.h5p.licenseextras'), - changes: Translate.instance.instant('core.h5p.changelog'), - contentCopied: Translate.instance.instant('core.h5p.contentCopied'), - connectionLost: Translate.instance.instant('core.h5p.connectionLost'), - connectionReestablished: Translate.instance.instant('core.h5p.connectionReestablished'), - resubmitScores: Translate.instance.instant('core.h5p.resubmitScores'), - offlineDialogHeader: Translate.instance.instant('core.h5p.offlineDialogHeader'), - offlineDialogBody: Translate.instance.instant('core.h5p.offlineDialogBody'), - offlineDialogRetryMessage: Translate.instance.instant('core.h5p.offlineDialogRetryMessage'), - offlineDialogRetryButtonLabel: Translate.instance.instant('core.h5p.offlineDialogRetryButtonLabel'), - offlineSuccessfulSubmit: Translate.instance.instant('core.h5p.offlineSuccessfulSubmit'), + fullscreen: Translate.instant('core.h5p.fullscreen'), + disableFullscreen: Translate.instant('core.h5p.disablefullscreen'), + download: Translate.instant('core.h5p.download'), + copyrights: Translate.instant('core.h5p.copyright'), + embed: Translate.instant('core.h5p.embed'), + size: Translate.instant('core.h5p.size'), + showAdvanced: Translate.instant('core.h5p.showadvanced'), + hideAdvanced: Translate.instant('core.h5p.hideadvanced'), + advancedHelp: Translate.instant('core.h5p.resizescript'), + copyrightInformation: Translate.instant('core.h5p.copyright'), + close: Translate.instant('core.h5p.close'), + title: Translate.instant('core.h5p.title'), + author: Translate.instant('core.h5p.author'), + year: Translate.instant('core.h5p.year'), + source: Translate.instant('core.h5p.source'), + license: Translate.instant('core.h5p.license'), + thumbnail: Translate.instant('core.h5p.thumbnail'), + noCopyrights: Translate.instant('core.h5p.nocopyright'), + reuse: Translate.instant('core.h5p.reuse'), + reuseContent: Translate.instant('core.h5p.reuseContent'), + reuseDescription: Translate.instant('core.h5p.reuseDescription'), + downloadDescription: Translate.instant('core.h5p.downloadtitle'), + copyrightsDescription: Translate.instant('core.h5p.copyrighttitle'), + embedDescription: Translate.instant('core.h5p.embedtitle'), + h5pDescription: Translate.instant('core.h5p.h5ptitle'), + contentChanged: Translate.instant('core.h5p.contentchanged'), + startingOver: Translate.instant('core.h5p.startingover'), + by: Translate.instant('core.h5p.by'), + showMore: Translate.instant('core.h5p.showmore'), + showLess: Translate.instant('core.h5p.showless'), + subLevel: Translate.instant('core.h5p.sublevel'), + confirmDialogHeader: Translate.instant('core.h5p.confirmdialogheader'), + confirmDialogBody: Translate.instant('core.h5p.confirmdialogbody'), + cancelLabel: Translate.instant('core.h5p.cancellabel'), + confirmLabel: Translate.instant('core.h5p.confirmlabel'), + licenseU: Translate.instant('core.h5p.undisclosed'), + licenseCCBY: Translate.instant('core.h5p.ccattribution'), + licenseCCBYSA: Translate.instant('core.h5p.ccattributionsa'), + licenseCCBYND: Translate.instant('core.h5p.ccattributionnd'), + licenseCCBYNC: Translate.instant('core.h5p.ccattributionnc'), + licenseCCBYNCSA: Translate.instant('core.h5p.ccattributionncsa'), + licenseCCBYNCND: Translate.instant('core.h5p.ccattributionncnd'), + licenseCC40: Translate.instant('core.h5p.licenseCC40'), + licenseCC30: Translate.instant('core.h5p.licenseCC30'), + licenseCC25: Translate.instant('core.h5p.licenseCC25'), + licenseCC20: Translate.instant('core.h5p.licenseCC20'), + licenseCC10: Translate.instant('core.h5p.licenseCC10'), + licenseGPL: Translate.instant('core.h5p.licenseGPL'), + licenseV3: Translate.instant('core.h5p.licenseV3'), + licenseV2: Translate.instant('core.h5p.licenseV2'), + licenseV1: Translate.instant('core.h5p.licenseV1'), + licensePD: Translate.instant('core.h5p.pd'), + licenseCC010: Translate.instant('core.h5p.licenseCC010'), + licensePDM: Translate.instant('core.h5p.pdm'), + licenseC: Translate.instant('core.h5p.copyrightstring'), + contentType: Translate.instant('core.h5p.contenttype'), + licenseExtras: Translate.instant('core.h5p.licenseextras'), + changes: Translate.instant('core.h5p.changelog'), + contentCopied: Translate.instant('core.h5p.contentCopied'), + connectionLost: Translate.instant('core.h5p.connectionLost'), + connectionReestablished: Translate.instant('core.h5p.connectionReestablished'), + resubmitScores: Translate.instant('core.h5p.resubmitScores'), + offlineDialogHeader: Translate.instant('core.h5p.offlineDialogHeader'), + offlineDialogBody: Translate.instant('core.h5p.offlineDialogBody'), + offlineDialogRetryMessage: Translate.instant('core.h5p.offlineDialogRetryMessage'), + offlineDialogRetryButtonLabel: Translate.instant('core.h5p.offlineDialogRetryButtonLabel'), + offlineSuccessfulSubmit: Translate.instant('core.h5p.offlineSuccessfulSubmit'), }; } @@ -715,7 +715,7 @@ export class CoreH5PCore { * @return Promise resolved with the content data. */ async loadContent(id?: number, fileUrl?: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const content = await this.h5pFramework.loadContent(id, fileUrl, siteId); diff --git a/src/core/features/h5p/classes/file-storage.ts b/src/core/features/h5p/classes/file-storage.ts index 453d8cd52..76105c1c9 100644 --- a/src/core/features/h5p/classes/file-storage.ts +++ b/src/core/features/h5p/classes/file-storage.ts @@ -60,17 +60,17 @@ export class CoreH5PFileStorage { // Create new file for cached assets. const fileName = key + '.' + (type == 'scripts' ? 'js' : 'css'); - const path = CoreTextUtils.instance.concatenatePaths(cachedAssetsPath, fileName); + const path = CoreTextUtils.concatenatePaths(cachedAssetsPath, fileName); // Store concatenated content. const content = await this.concatenateFiles(assets, type); - await CoreFile.instance.writeFile(path, content); + await CoreFile.writeFile(path, content); // Now update the files data. files[type] = [ { - path: CoreTextUtils.instance.concatenatePaths(CoreH5PFileStorage.CACHED_ASSETS_FOLDER_NAME, fileName), + path: CoreTextUtils.concatenatePaths(CoreH5PFileStorage.CACHED_ASSETS_FOLDER_NAME, fileName), version: '', }, ]; @@ -85,13 +85,13 @@ export class CoreH5PFileStorage { * @return Promise resolved with all of the files content in one string. */ protected async concatenateFiles(assets: CoreH5PDependencyAsset[], type: string): Promise { - const basePath = CoreFile.instance.convertFileSrc(CoreFile.instance.getBasePathInstant()); + const basePath = CoreFile.convertFileSrc(CoreFile.getBasePathInstant()); let content = ''; for (const i in assets) { const asset = assets[i]; - let fileContent = await CoreFile.instance.readFile(asset.path); + let fileContent = await CoreFile.readFile(asset.path); if (type == 'scripts') { // No need to treat scripts, just append the content. @@ -141,8 +141,8 @@ export class CoreH5PFileStorage { } fileContent = fileContent.replace( - new RegExp(CoreTextUtils.instance.escapeForRegex(match), 'g'), - 'url("' + CoreTextUtils.instance.concatenatePaths(basePath, url) + '")', + new RegExp(CoreTextUtils.escapeForRegex(match), 'g'), + 'url("' + CoreTextUtils.concatenatePaths(basePath, url) + '")', ); }); } @@ -162,7 +162,7 @@ export class CoreH5PFileStorage { */ async deleteCachedAssets(removedEntries: CoreH5PLibraryCachedAssetsDBRecord[], siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const promises: Promise[] = []; @@ -170,14 +170,14 @@ export class CoreH5PFileStorage { const cachedAssetsFolder = this.getCachedAssetsFolderPath(entry.foldername, site.getId()); ['js', 'css'].forEach((type) => { - const path = CoreTextUtils.instance.concatenatePaths(cachedAssetsFolder, entry.hash + '.' + type); + const path = CoreTextUtils.concatenatePaths(cachedAssetsFolder, entry.hash + '.' + type); - promises.push(CoreFile.instance.removeFile(path)); + promises.push(CoreFile.removeFile(path)); }); }); // Ignore errors, maybe there's no cached asset of some type. - await CoreUtils.instance.ignoreErrors(CoreUtils.instance.allPromises(promises)); + await CoreUtils.ignoreErrors(CoreUtils.allPromises(promises)); } /** @@ -188,7 +188,7 @@ export class CoreH5PFileStorage { * @return Promise resolved when done. */ async deleteContentFolder(folderName: string, siteId: string): Promise { - await CoreFile.instance.removeDir(this.getContentFolderPath(folderName, siteId)); + await CoreFile.removeDir(this.getContentFolderPath(folderName, siteId)); } /** @@ -199,7 +199,7 @@ export class CoreH5PFileStorage { * @return Promise resolved when done. */ async deleteContentIndex(folderName: string, siteId: string): Promise { - await CoreFile.instance.removeFile(this.getContentIndexPath(folderName, siteId)); + await CoreFile.removeFile(this.getContentIndexPath(folderName, siteId)); } /** @@ -211,7 +211,7 @@ export class CoreH5PFileStorage { */ async deleteContentIndexesForLibrary(libraryId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const db = site.getDb(); @@ -247,7 +247,7 @@ export class CoreH5PFileStorage { siteId: string, folderName?: string, ): Promise { - await CoreFile.instance.removeDir(this.getLibraryFolderPath(libraryData, siteId, folderName)); + await CoreFile.removeDir(this.getLibraryFolderPath(libraryData, siteId, folderName)); } /** @@ -282,9 +282,9 @@ export class CoreH5PFileStorage { protected async getCachedAsset(key: string, extension: string): Promise { try { - const path = CoreTextUtils.instance.concatenatePaths(CoreH5PFileStorage.CACHED_ASSETS_FOLDER_NAME, key + extension); + const path = CoreTextUtils.concatenatePaths(CoreH5PFileStorage.CACHED_ASSETS_FOLDER_NAME, key + extension); - const size = await CoreFile.instance.getFileSize(path); + const size = await CoreFile.getFileSize(path); if (size > 0) { return [ @@ -307,7 +307,7 @@ export class CoreH5PFileStorage { * @return Path. */ getCachedAssetsFolderPath(folderName: string, siteId: string): string { - return CoreTextUtils.instance.concatenatePaths( + return CoreTextUtils.concatenatePaths( this.getContentFolderPath(folderName, siteId), CoreH5PFileStorage.CACHED_ASSETS_FOLDER_NAME, ); @@ -321,11 +321,11 @@ export class CoreH5PFileStorage { * @return Promise resolved with the folder name. */ async getContentFolderNameByUrl(fileUrl: string, siteId: string): Promise { - const path = await CoreFilepool.instance.getFilePathByUrl(siteId, fileUrl); + const path = await CoreFilepool.getFilePathByUrl(siteId, fileUrl); - const fileAndDir = CoreFile.instance.getFileAndDirectoryFromPath(path); + const fileAndDir = CoreFile.getFileAndDirectoryFromPath(path); - return CoreMimetypeUtils.instance.removeExtension(fileAndDir.name); + return CoreMimetypeUtils.removeExtension(fileAndDir.name); } /** @@ -336,7 +336,7 @@ export class CoreH5PFileStorage { * @return Folder path. */ getContentFolderPath(folderName: string, siteId: string): string { - return CoreTextUtils.instance.concatenatePaths( + return CoreTextUtils.concatenatePaths( this.getExternalH5PFolderPath(siteId), 'packages/' + folderName + '/content', ); @@ -350,11 +350,11 @@ export class CoreH5PFileStorage { * @return Promise resolved with the file URL if exists, rejected otherwise. */ async getContentIndexFileUrl(fileUrl: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const folderName = await this.getContentFolderNameByUrl(fileUrl, siteId); - const file = await CoreFile.instance.getFile(this.getContentIndexPath(folderName, siteId)); + const file = await CoreFile.getFile(this.getContentIndexPath(folderName, siteId)); return file.toURL(); } @@ -367,7 +367,7 @@ export class CoreH5PFileStorage { * @return Folder path. */ getContentIndexPath(folderName: string, siteId: string): string { - return CoreTextUtils.instance.concatenatePaths(this.getContentFolderPath(folderName, siteId), 'index.html'); + return CoreTextUtils.concatenatePaths(this.getContentFolderPath(folderName, siteId), 'index.html'); } /** @@ -376,7 +376,7 @@ export class CoreH5PFileStorage { * @return Folder path. */ getCoreH5PPath(): string { - return CoreTextUtils.instance.concatenatePaths(CoreFile.instance.getWWWPath(), '/h5p/'); + return CoreTextUtils.concatenatePaths(CoreFile.getWWWPath(), '/h5p/'); } /** @@ -396,7 +396,7 @@ export class CoreH5PFileStorage { * @return Folder path. */ getExternalH5PFolderPath(siteId: string): string { - return CoreTextUtils.instance.concatenatePaths(CoreFile.instance.getSiteFolder(siteId), 'h5p'); + return CoreTextUtils.concatenatePaths(CoreFile.getSiteFolder(siteId), 'h5p'); } /** @@ -406,7 +406,7 @@ export class CoreH5PFileStorage { * @return Folder path. */ getLibrariesFolderPath(siteId: string): string { - return CoreTextUtils.instance.concatenatePaths(this.getExternalH5PFolderPath(siteId), 'libraries'); + return CoreTextUtils.concatenatePaths(this.getExternalH5PFolderPath(siteId), 'libraries'); } /** @@ -426,7 +426,7 @@ export class CoreH5PFileStorage { folderName = CoreH5PCore.libraryToString(libraryData, true); } - return CoreTextUtils.instance.concatenatePaths(this.getLibrariesFolderPath(siteId), folderName); + return CoreTextUtils.concatenatePaths(this.getLibrariesFolderPath(siteId), folderName); } /** @@ -441,10 +441,10 @@ export class CoreH5PFileStorage { const folderPath = this.getContentFolderPath(folderName, siteId); // Delete existing content for this package. - await CoreUtils.instance.ignoreErrors(CoreFile.instance.removeDir(folderPath)); + await CoreUtils.ignoreErrors(CoreFile.removeDir(folderPath)); // Copy the new one. - await CoreFile.instance.moveDir(contentPath, folderPath); + await CoreFile.moveDir(contentPath, folderPath); } /** @@ -455,20 +455,20 @@ export class CoreH5PFileStorage { * @return Promise resolved when done. */ async saveLibrary(libraryData: CoreH5PLibraryBeingSaved, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const folderPath = this.getLibraryFolderPath(libraryData, siteId); // Delete existing library version. try { - await CoreFile.instance.removeDir(folderPath); + await CoreFile.removeDir(folderPath); } catch (error) { // Ignore errors, maybe it doesn't exist. } if (libraryData.uploadDirectory) { // Copy the new one. - await CoreFile.instance.moveDir(libraryData.uploadDirectory, folderPath, true); + await CoreFile.moveDir(libraryData.uploadDirectory, folderPath, true); } } diff --git a/src/core/features/h5p/classes/framework.ts b/src/core/features/h5p/classes/framework.ts index 0e966a259..bbdf06594 100644 --- a/src/core/features/h5p/classes/framework.ts +++ b/src/core/features/h5p/classes/framework.ts @@ -61,7 +61,7 @@ export class CoreH5PFramework { return; } - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const whereAndParams = db.getInOrEqual(libraryIds); whereAndParams.sql = 'mainlibraryid ' + whereAndParams.sql; @@ -78,7 +78,7 @@ export class CoreH5PFramework { */ async deleteCachedAssets(libraryId: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); // Get all the hashes that use this library. const entries = await db.getRecords( @@ -105,7 +105,7 @@ export class CoreH5PFramework { */ async deleteContentData(id: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await Promise.all([ // Delete the content data. @@ -124,7 +124,7 @@ export class CoreH5PFramework { * @return Promise resolved when done. */ async deleteLibrary(id: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await db.deleteRecords(LIBRARIES_TABLE_NAME, { id }); } @@ -137,7 +137,7 @@ export class CoreH5PFramework { * @return Promise resolved when done. */ async deleteLibraryDependencies(libraryId: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await db.deleteRecords(LIBRARY_DEPENDENCIES_TABLE_NAME, { libraryid: libraryId }); } @@ -150,7 +150,7 @@ export class CoreH5PFramework { * @return Promise resolved when done. */ async deleteLibraryUsage(id: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await db.deleteRecords(CONTENTS_LIBRARIES_TABLE_NAME, { h5pid: id }); } @@ -162,7 +162,7 @@ export class CoreH5PFramework { * @return Promise resolved with the list of content data. */ async getAllContentData(siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); return db.getAllRecords(CONTENT_TABLE_NAME); } @@ -175,7 +175,7 @@ export class CoreH5PFramework { * @return Promise resolved with the content data. */ async getContentData(id: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); return db.getRecord(CONTENT_TABLE_NAME, { id }); } @@ -188,12 +188,12 @@ export class CoreH5PFramework { * @return Promise resolved with the content data. */ async getContentDataByUrl(fileUrl: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const db = site.getDb(); // Try to use the folder name, it should be more reliable than the URL. - const folderName = await CoreH5P.instance.h5pCore.h5pFS.getContentFolderNameByUrl(fileUrl, site.getId()); + const folderName = await CoreH5P.h5pCore.h5pFS.getContentFolderNameByUrl(fileUrl, site.getId()); try { return await db.getRecord(CONTENT_TABLE_NAME, { foldername: folderName }); @@ -211,7 +211,7 @@ export class CoreH5PFramework { */ async getLatestLibraryVersion(machineName: string, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); try { const records = await db.getRecords( @@ -249,7 +249,7 @@ export class CoreH5PFramework { siteId?: string, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const libraries = await db.getRecords(LIBRARIES_TABLE_NAME, { machinename: machineName, @@ -283,7 +283,7 @@ export class CoreH5PFramework { * @return Promise resolved with the library data, rejected if not found. */ async getLibraryById(id: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const library = await db.getRecord(LIBRARIES_TABLE_NAME, { id }); @@ -412,7 +412,7 @@ export class CoreH5PFramework { */ async loadAddons(siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const query = 'SELECT l1.id AS libraryId, l1.machinename AS machineName, ' + 'l1.majorversion AS majorVersion, l1.minorversion AS minorVersion, ' + @@ -444,7 +444,7 @@ export class CoreH5PFramework { * @return Promise resolved with the content data. */ async loadContent(id?: number, fileUrl?: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); let contentData: CoreH5PContentDBRecord; @@ -479,7 +479,7 @@ export class CoreH5PFramework { }; // eslint-disable-next-line @typescript-eslint/no-explicit-any - const params = CoreTextUtils.instance.parseJSON(contentData.jsoncontent); + const params = CoreTextUtils.parseJSON(contentData.jsoncontent); if (!params.metadata) { params.metadata = {}; } @@ -502,7 +502,7 @@ export class CoreH5PFramework { siteId?: string, ): Promise<{[machineName: string]: CoreH5PContentDependencyData}> { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); let query = 'SELECT hl.id AS libraryId, hl.machinename AS machineName, ' + 'hl.majorversion AS majorVersion, hl.minorversion AS minorVersion, ' + @@ -585,7 +585,7 @@ export class CoreH5PFramework { library.id, ]; - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const result = await db.execute(sql, sqlParams); @@ -611,7 +611,7 @@ export class CoreH5PFramework { */ parseLibAddonData(library: LibraryAddonDBData): CoreH5PLibraryAddonData { const parsedLib = library; - parsedLib.addTo = CoreTextUtils.instance.parseJSON(library.addTo, null); + parsedLib.addTo = CoreTextUtils.parseJSON(library.addTo, null); return parsedLib; } @@ -624,9 +624,9 @@ export class CoreH5PFramework { */ protected parseLibDBData(library: CoreH5PLibraryDBRecord): CoreH5PLibraryParsedDBRecord { return Object.assign(library, { - semantics: library.semantics ? CoreTextUtils.instance.parseJSON(library.semantics, null) : null, - addto: library.addto ? CoreTextUtils.instance.parseJSON(library.addto, null) : null, - metadatasettings: library.metadatasettings ? CoreTextUtils.instance.parseJSON(library.metadatasettings, null) : null, + semantics: library.semantics ? CoreTextUtils.parseJSON(library.semantics, null) : null, + addto: library.addto ? CoreTextUtils.parseJSON(library.addto, null) : null, + metadatasettings: library.metadatasettings ? CoreTextUtils.parseJSON(library.metadatasettings, null) : null, }); } @@ -659,7 +659,7 @@ export class CoreH5PFramework { siteId?: string, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await Promise.all(Object.keys(dependencies).map(async (key) => { const data: Partial = { @@ -697,7 +697,7 @@ export class CoreH5PFramework { embedTypes = libraryData.embedTypes.join(', '); } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const db = site.getDb(); const data: Partial = { @@ -751,7 +751,7 @@ export class CoreH5PFramework { siteId?: string, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await Promise.all(dependencies.map(async (dependency) => { // Get the ID of the library. @@ -782,7 +782,7 @@ export class CoreH5PFramework { siteId?: string, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); // Calculate the CSS to drop. const dropLibraryCssList: Record = {}; @@ -825,7 +825,7 @@ export class CoreH5PFramework { */ async updateContent(content: CoreH5PContentBeingSaved, folderName: string, fileUrl: string, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); // If the libraryid declared in the package is empty, get the latest version. if (content.library && typeof content.library.libraryId == 'undefined') { @@ -872,7 +872,7 @@ export class CoreH5PFramework { */ async updateContentFields(id: number, fields: Partial, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const data = Object.assign({}, fields); diff --git a/src/core/features/h5p/classes/helper.ts b/src/core/features/h5p/classes/helper.ts index 4a0822ce0..4054bcb01 100644 --- a/src/core/features/h5p/classes/helper.ts +++ b/src/core/features/h5p/classes/helper.ts @@ -37,14 +37,14 @@ export class CoreH5PHelper { * @return Object with display options. */ static decodeDisplayOptions(displayOptions: number): CoreH5PDisplayOptions { - const displayOptionsObject = CoreH5P.instance.h5pCore.getDisplayOptionsAsObject(displayOptions); + const displayOptionsObject = CoreH5P.h5pCore.getDisplayOptionsAsObject(displayOptions); const config: CoreH5PDisplayOptions = { export: false, // Don't allow downloading in the app. embed: false, // Don't display the embed button in the app. - copyright: CoreUtils.instance.notNullOrUndefined(displayOptionsObject[CoreH5PCore.DISPLAY_OPTION_COPYRIGHT]) ? + copyright: CoreUtils.notNullOrUndefined(displayOptionsObject[CoreH5PCore.DISPLAY_OPTION_COPYRIGHT]) ? displayOptionsObject[CoreH5PCore.DISPLAY_OPTION_COPYRIGHT] : false, - icon: CoreUtils.instance.notNullOrUndefined(displayOptionsObject[CoreH5PCore.DISPLAY_OPTION_ABOUT]) ? + icon: CoreUtils.notNullOrUndefined(displayOptionsObject[CoreH5PCore.DISPLAY_OPTION_ABOUT]) ? displayOptionsObject[CoreH5PCore.DISPLAY_OPTION_ABOUT] : false, }; @@ -72,7 +72,7 @@ export class CoreH5PHelper { settings.loadedJs = []; settings.loadedCss = []; - const libUrl = CoreH5P.instance.h5pCore.h5pFS.getCoreH5PPath(); + const libUrl = CoreH5P.h5pCore.h5pFS.getCoreH5PPath(); const cssRequires: string[] = []; const jsRequires: string[] = []; @@ -99,33 +99,33 @@ export class CoreH5PHelper { */ static async getCoreSettings(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const userId = site.getUserId(); - const user = await CoreUtils.instance.ignoreErrors(CoreUser.instance.getProfile(userId, undefined, false, siteId)); + const user = await CoreUtils.ignoreErrors(CoreUser.getProfile(userId, undefined, false, siteId)); if (!user || !user.email) { - throw new CoreError(Translate.instance.instant('core.h5p.errorgetemail')); + throw new CoreError(Translate.instant('core.h5p.errorgetemail')); } - const basePath = CoreFile.instance.getBasePathInstant(); + const basePath = CoreFile.getBasePathInstant(); const ajaxPaths = { xAPIResult: '', contentUserData: '', }; return { - baseUrl: CoreFile.instance.getWWWPath(), - url: CoreFile.instance.convertFileSrc( - CoreTextUtils.instance.concatenatePaths( + baseUrl: CoreFile.getWWWPath(), + url: CoreFile.convertFileSrc( + CoreTextUtils.concatenatePaths( basePath, - CoreH5P.instance.h5pCore.h5pFS.getExternalH5PFolderPath(site.getId()), + CoreH5P.h5pCore.h5pFS.getExternalH5PFolderPath(site.getId()), ), ), - urlLibraries: CoreFile.instance.convertFileSrc( - CoreTextUtils.instance.concatenatePaths( + urlLibraries: CoreFile.convertFileSrc( + CoreTextUtils.concatenatePaths( basePath, - CoreH5P.instance.h5pCore.h5pFS.getLibrariesFolderPath(site.getId()), + CoreH5P.h5pCore.h5pFS.getLibrariesFolderPath(site.getId()), ), ), postUserStatistics: false, @@ -133,7 +133,7 @@ export class CoreH5PHelper { saveFreq: false, siteUrl: site.getURL(), l10n: { - H5P: CoreH5P.instance.h5pCore.getLocalization(), // eslint-disable-line @typescript-eslint/naming-convention + H5P: CoreH5P.h5pCore.getLocalization(), // eslint-disable-line @typescript-eslint/naming-convention }, user: { name: site.getInfo()!.fullname, mail: user.email }, hubIsEnabled: false, @@ -141,7 +141,7 @@ export class CoreH5PHelper { crossorigin: null, libraryConfig: null, pluginCacheBuster: '', - libraryUrl: CoreTextUtils.instance.concatenatePaths(CoreH5P.instance.h5pCore.h5pFS.getCoreH5PPath(), 'js'), + libraryUrl: CoreTextUtils.concatenatePaths(CoreH5P.h5pCore.h5pFS.getCoreH5PPath(), 'js'), }; } @@ -156,14 +156,14 @@ export class CoreH5PHelper { * @return Promise resolved when done. */ static async saveH5P(fileUrl: string, file: FileEntry, siteId?: string, onProgress?: CoreH5PSaveOnProgress): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Notify that the unzip is starting. onProgress && onProgress({ message: 'core.unzipping' }); const queueId = siteId + ':saveH5P:' + fileUrl; - await CoreH5P.instance.queueRunner.run(queueId, () => CoreH5PHelper.performSave(fileUrl, file, siteId, onProgress)); + await CoreH5P.queueRunner.run(queueId, () => CoreH5PHelper.performSave(fileUrl, file, siteId, onProgress)); } /** @@ -182,33 +182,33 @@ export class CoreH5PHelper { onProgress?: CoreH5PSaveOnProgress, ): Promise { - const folderName = CoreMimetypeUtils.instance.removeExtension(file.name); - const destFolder = CoreTextUtils.instance.concatenatePaths(CoreFileProvider.TMPFOLDER, 'h5p/' + folderName); + const folderName = CoreMimetypeUtils.removeExtension(file.name); + const destFolder = CoreTextUtils.concatenatePaths(CoreFileProvider.TMPFOLDER, 'h5p/' + folderName); // Unzip the file. - await CoreFile.instance.unzipFile(file.toURL(), destFolder, onProgress); + await CoreFile.unzipFile(file.toURL(), destFolder, onProgress); try { // Notify that the unzip is starting. onProgress && onProgress({ message: 'core.storingfiles' }); // Read the contents of the unzipped dir, process them and store them. - const contents = await CoreFile.instance.getDirectoryContents(destFolder); + const contents = await CoreFile.getDirectoryContents(destFolder); - const filesData = await CoreH5P.instance.h5pValidator.processH5PFiles(destFolder, contents); + const filesData = await CoreH5P.h5pValidator.processH5PFiles(destFolder, contents); - const content = await CoreH5P.instance.h5pStorage.savePackage(filesData, folderName, fileUrl, false, siteId); + const content = await CoreH5P.h5pStorage.savePackage(filesData, folderName, fileUrl, false, siteId); // Create the content player. - const contentData = await CoreH5P.instance.h5pCore.loadContent(content.id, undefined, siteId); + const contentData = await CoreH5P.h5pCore.loadContent(content.id, undefined, siteId); const embedType = CoreH5PCore.determineEmbedType(contentData.embedType, contentData.library.embedTypes); - await CoreH5P.instance.h5pPlayer.createContentIndex(content.id!, fileUrl, contentData, embedType, siteId); + await CoreH5P.h5pPlayer.createContentIndex(content.id!, fileUrl, contentData, embedType, siteId); } finally { // Remove tmp folder. try { - await CoreFile.instance.removeDir(destFolder); + await CoreFile.removeDir(destFolder); } catch (error) { // Ignore errors, it will be deleted eventually. } diff --git a/src/core/features/h5p/classes/player.ts b/src/core/features/h5p/classes/player.ts index db77e3d0b..73da742fe 100644 --- a/src/core/features/h5p/classes/player.ts +++ b/src/core/features/h5p/classes/player.ts @@ -43,7 +43,7 @@ export class CoreH5PPlayer { * @return URL. */ calculateOnlinePlayerUrl(siteUrl: string, fileUrl: string, displayOptions?: CoreH5PDisplayOptions, component?: string): string { - fileUrl = CoreH5P.instance.treatH5PUrl(fileUrl, siteUrl); + fileUrl = CoreH5P.treatH5PUrl(fileUrl, siteUrl); const params = this.getUrlParamsFromDisplayOptions(displayOptions); params.url = encodeURIComponent(fileUrl); @@ -51,7 +51,7 @@ export class CoreH5PPlayer { params.component = component; } - return CoreUrlUtils.instance.addParamsToUrl(CoreTextUtils.instance.concatenatePaths(siteUrl, '/h5p/embed.php'), params); + return CoreUrlUtils.addParamsToUrl(CoreTextUtils.concatenatePaths(siteUrl, '/h5p/embed.php'), params); } /** @@ -73,12 +73,12 @@ export class CoreH5PPlayer { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const contentId = this.getContentId(id); - const basePath = CoreFile.instance.getBasePathInstant(); - const contentUrl = CoreFile.instance.convertFileSrc( - CoreTextUtils.instance.concatenatePaths( + const basePath = CoreFile.getBasePathInstant(); + const contentUrl = CoreFile.convertFileSrc( + CoreTextUtils.concatenatePaths( basePath, this.h5pCore.h5pFS.getContentFolderPath(content.folderName, site.getId()), ), @@ -122,7 +122,7 @@ export class CoreH5PPlayer { JSON.stringify(result.settings).replace(/\//g, '\\/') + ''; // Add our own script to handle the params. - html += ''; @@ -132,7 +132,7 @@ export class CoreH5PPlayer { // Include the required JS at the beginning of the body, like Moodle web does. // Load the embed.js to allow communication with the parent window. html += ''; + CoreTextUtils.concatenatePaths(this.h5pCore.h5pFS.getCoreH5PPath(), 'moodle/js/embed.js') + '">'; result.jsRequires.forEach((jsUrl) => { html += ''; @@ -143,7 +143,7 @@ export class CoreH5PPlayer { 'style="height:1px; min-width: 100%" src="about:blank">' + ''; - const fileEntry = await CoreFile.instance.writeFile(indexPath, html); + const fileEntry = await CoreFile.writeFile(indexPath, html); return fileEntry.toURL(); } @@ -154,7 +154,7 @@ export class CoreH5PPlayer { * @return Promise resolved when done. */ async deleteAllContentIndexes(): Promise { - const siteIds = await CoreSites.instance.getSitesIds(); + const siteIds = await CoreSites.getSitesIds(); await Promise.all(siteIds.map((siteId) => this.deleteAllContentIndexesForSite(siteId))); } @@ -166,7 +166,7 @@ export class CoreH5PPlayer { * @return Promise resolved when done. */ async deleteAllContentIndexesForSite(siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!siteId) { return; @@ -175,7 +175,7 @@ export class CoreH5PPlayer { const records = await this.h5pCore.h5pFramework.getAllContentData(siteId); await Promise.all(records.map(async (record) => { - await CoreUtils.instance.ignoreErrors(this.h5pCore.h5pFS.deleteContentIndex(record.foldername, siteId!)); + await CoreUtils.ignoreErrors(this.h5pCore.h5pFS.deleteContentIndex(record.foldername, siteId!)); })); } @@ -187,11 +187,11 @@ export class CoreH5PPlayer { * @return Promise resolved when done. */ async deleteContentByUrl(fileUrl: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const data = await this.h5pCore.h5pFramework.getContentDataByUrl(fileUrl, siteId); - await CoreUtils.instance.allPromises([ + await CoreUtils.allPromises([ this.h5pCore.h5pFramework.deleteContentData(data.id, siteId), this.h5pCore.h5pFS.deleteContentFolder(data.foldername, siteId), @@ -214,7 +214,7 @@ export class CoreH5PPlayer { siteId?: string, ): Promise<{settings: AssetsSettings; cssRequires: string[]; jsRequires: string[]}> { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Get core assets. const coreAssets = await CoreH5PHelper.getCoreAssets(siteId); @@ -273,7 +273,7 @@ export class CoreH5PPlayer { contextId?: number, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const path = await this.h5pCore.h5pFS.getContentIndexFileUrl(fileUrl, siteId); @@ -288,10 +288,10 @@ export class CoreH5PPlayer { }; if (contextId) { - params.trackingUrl = await CoreXAPI.instance.getUrl(contextId, 'activity', siteId); + params.trackingUrl = await CoreXAPI.getUrl(contextId, 'activity', siteId); } - return CoreUrlUtils.instance.addParamsToUrl(path, params); + return CoreUrlUtils.addParamsToUrl(path, params); } /** @@ -303,9 +303,9 @@ export class CoreH5PPlayer { * @return Promise resolved with the files. */ protected async getDependencyFiles(id: number, folderName: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const preloadedDeps = await CoreH5P.instance.h5pCore.loadContentDependencies(id, 'preloaded', siteId); + const preloadedDeps = await CoreH5P.h5pCore.loadContentDependencies(id, 'preloaded', siteId); return this.h5pCore.getDependenciesFiles( preloadedDeps, @@ -331,7 +331,7 @@ export class CoreH5PPlayer { displayOptions[CoreH5PCore.DISPLAY_OPTION_DOWNLOAD] = false; // Never allow downloading in the app. displayOptions[CoreH5PCore.DISPLAY_OPTION_EMBED] = false; // Never show the embed option in the app. displayOptions[CoreH5PCore.DISPLAY_OPTION_COPYRIGHT] = - CoreUtils.instance.isTrueOrOne(params[CoreH5PCore.DISPLAY_OPTION_COPYRIGHT]); + CoreUtils.isTrueOrOne(params[CoreH5PCore.DISPLAY_OPTION_COPYRIGHT]); displayOptions[CoreH5PCore.DISPLAY_OPTION_FRAME] = displayOptions[CoreH5PCore.DISPLAY_OPTION_DOWNLOAD] || displayOptions[CoreH5PCore.DISPLAY_OPTION_EMBED] || displayOptions[CoreH5PCore.DISPLAY_OPTION_COPYRIGHT]; displayOptions[CoreH5PCore.DISPLAY_OPTION_ABOUT] = @@ -364,7 +364,7 @@ export class CoreH5PPlayer { * @return The embed URL. */ protected getEmbedUrl(siteUrl: string, h5pUrl: string): string { - return CoreTextUtils.instance.concatenatePaths(siteUrl, '/h5p/embed.php') + '?url=' + h5pUrl; + return CoreTextUtils.concatenatePaths(siteUrl, '/h5p/embed.php') + '?url=' + h5pUrl; } /** @@ -382,7 +382,7 @@ export class CoreH5PPlayer { * @return URL. */ getResizerScriptUrl(): string { - return CoreTextUtils.instance.concatenatePaths(this.h5pCore.h5pFS.getCoreH5PPath(), 'js/h5p-resizer.js'); + return CoreTextUtils.concatenatePaths(this.h5pCore.h5pFS.getCoreH5PPath(), 'js/h5p-resizer.js'); } /** diff --git a/src/core/features/h5p/classes/storage.ts b/src/core/features/h5p/classes/storage.ts index 049e2efab..395eee442 100644 --- a/src/core/features/h5p/classes/storage.ts +++ b/src/core/features/h5p/classes/storage.ts @@ -45,10 +45,10 @@ export class CoreH5PStorage { * @return Promise resolved when done. */ protected async saveLibraries(librariesJsonData: CoreH5PLibrariesJsonData, folderName: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // First of all, try to create the dir where the libraries are stored. This way we don't have to do it for each lib. - await CoreFile.instance.createDir(this.h5pCore.h5pFS.getLibrariesFolderPath(siteId)); + await CoreFile.createDir(this.h5pCore.h5pFS.getLibrariesFolderPath(siteId)); const libraryIds: number[] = []; @@ -57,7 +57,7 @@ export class CoreH5PStorage { const libraryData: CoreH5PLibraryBeingSaved = librariesJsonData[libString]; // Find local library identifier. - const dbData = await CoreUtils.instance.ignoreErrors(this.h5pFramework.getLibraryByData(libraryData)); + const dbData = await CoreUtils.ignoreErrors(this.h5pFramework.getLibraryByData(libraryData)); if (dbData) { // Library already installed. @@ -107,7 +107,7 @@ export class CoreH5PStorage { await this.h5pCore.h5pFS.deleteCachedAssets(removedEntries, siteId); } - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); } })); @@ -164,7 +164,7 @@ export class CoreH5PStorage { skipContent?: boolean, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.h5pCore.mayUpdateLibraries()) { // Save the libraries that were processed. @@ -192,8 +192,8 @@ export class CoreH5PStorage { await this.h5pCore.saveContent(content, folderName, fileUrl, siteId); // Save the content files in their right place in FS. - const destFolder = CoreTextUtils.instance.concatenatePaths(CoreFileProvider.TMPFOLDER, 'h5p/' + folderName); - const contentPath = CoreTextUtils.instance.concatenatePaths(destFolder, 'content'); + const destFolder = CoreTextUtils.concatenatePaths(CoreFileProvider.TMPFOLDER, 'h5p/' + folderName); + const contentPath = CoreTextUtils.concatenatePaths(destFolder, 'content'); try { await this.h5pCore.h5pFS.saveContent(contentPath, folderName, siteId); diff --git a/src/core/features/h5p/classes/validator.ts b/src/core/features/h5p/classes/validator.ts index dc6994ef0..a957443d7 100644 --- a/src/core/features/h5p/classes/validator.ts +++ b/src/core/features/h5p/classes/validator.ts @@ -68,7 +68,7 @@ export class CoreH5PValidator { return; } - const libDirPath = CoreTextUtils.instance.concatenatePaths(packagePath, entry.name); + const libDirPath = CoreTextUtils.concatenatePaths(packagePath, entry.name); const libraryData = await this.getLibraryData( entry, libDirPath); @@ -86,11 +86,11 @@ export class CoreH5PValidator { * @return Promise resolved with boolean: whether the library has an icon file. */ protected async libraryHasIcon(libPath: string): Promise { - const path = CoreTextUtils.instance.concatenatePaths(libPath, 'icon.svg'); + const path = CoreTextUtils.concatenatePaths(libPath, 'icon.svg'); try { // Check if the file exists. - await CoreFile.instance.getFile(path); + await CoreFile.getFile(path); return true; } catch (error) { @@ -131,9 +131,9 @@ export class CoreH5PValidator { * @return Promise resolved with the parsed file contents. */ protected readH5PContentJsonFile(packagePath: string): Promise { - const path = CoreTextUtils.instance.concatenatePaths(packagePath, 'content/content.json'); + const path = CoreTextUtils.concatenatePaths(packagePath, 'content/content.json'); - return CoreFile.instance.readFile(path, CoreFileFormat.FORMATJSON); + return CoreFile.readFile(path, CoreFileFormat.FORMATJSON); } /** @@ -143,9 +143,9 @@ export class CoreH5PValidator { * @return Promise resolved with the parsed file contents. */ protected readH5PJsonFile(packagePath: string): Promise { - const path = CoreTextUtils.instance.concatenatePaths(packagePath, 'h5p.json'); + const path = CoreTextUtils.concatenatePaths(packagePath, 'h5p.json'); - return CoreFile.instance.readFile(path, CoreFileFormat.FORMATJSON); + return CoreFile.readFile(path, CoreFileFormat.FORMATJSON); } /** @@ -155,9 +155,9 @@ export class CoreH5PValidator { * @return Promise resolved with the parsed file contents. */ protected readLibraryJsonFile(libPath: string): Promise { - const path = CoreTextUtils.instance.concatenatePaths(libPath, 'library.json'); + const path = CoreTextUtils.concatenatePaths(libPath, 'library.json'); - return CoreFile.instance.readFile(path, CoreFileFormat.FORMATJSON); + return CoreFile.readFile(path, CoreFileFormat.FORMATJSON); } /** @@ -168,17 +168,17 @@ export class CoreH5PValidator { */ protected async readLibraryLanguageFiles(libPath: string): Promise { try { - const path = CoreTextUtils.instance.concatenatePaths(libPath, 'language'); + const path = CoreTextUtils.concatenatePaths(libPath, 'language'); const langIndex: CoreH5PLibraryLangsJsonData = {}; // Read all the files in the language directory. - const entries = await CoreFile.instance.getDirectoryContents(path); + const entries = await CoreFile.getDirectoryContents(path); await Promise.all(entries.map(async (entry) => { - const langFilePath = CoreTextUtils.instance.concatenatePaths(path, entry.name); + const langFilePath = CoreTextUtils.concatenatePaths(path, entry.name); try { - const langFileData = await CoreFile.instance.readFile( + const langFileData = await CoreFile.readFile( langFilePath, CoreFileFormat.FORMATJSON, ); @@ -205,9 +205,9 @@ export class CoreH5PValidator { */ protected async readLibrarySemanticsFile(libPath: string): Promise { try { - const path = CoreTextUtils.instance.concatenatePaths(libPath, 'semantics.json'); + const path = CoreTextUtils.concatenatePaths(libPath, 'semantics.json'); - return await CoreFile.instance.readFile(path, CoreFileFormat.FORMATJSON); + return await CoreFile.readFile(path, CoreFileFormat.FORMATJSON); } catch (error) { // Probably doesn't exist, ignore. } diff --git a/src/core/features/h5p/components/h5p-iframe/h5p-iframe.ts b/src/core/features/h5p/components/h5p-iframe/h5p-iframe.ts index 0bcb55350..a05f4cdcc 100644 --- a/src/core/features/h5p/components/h5p-iframe/h5p-iframe.ts +++ b/src/core/features/h5p/components/h5p-iframe/h5p-iframe.ts @@ -63,9 +63,9 @@ export class CoreH5PIframeComponent implements OnChanges, OnDestroy { ) { this.logger = CoreLogger.getInstance('CoreH5PIframeComponent'); - this.site = CoreSites.instance.getCurrentSite()!; + this.site = CoreSites.getCurrentSite()!; this.siteId = this.site.getId(); - this.siteCanDownload = this.site.canDownloadFiles() && !CoreH5P.instance.isOfflineDisabledInSite(); + this.siteCanDownload = this.site.canDownloadFiles() && !CoreH5P.isOfflineDisabledInSite(); // Send resize events when the page holding this component is re-entered. // @todo: Check that this works as expected. @@ -101,12 +101,12 @@ export class CoreH5PIframeComponent implements OnChanges, OnDestroy { let state: string; if (this.fileUrl) { - state = await CoreFilepool.instance.getFileStateByUrl(this.siteId, this.fileUrl); + state = await CoreFilepool.getFileStateByUrl(this.siteId, this.fileUrl); } else { state = CoreConstants.NOT_DOWNLOADABLE; } - if (this.siteCanDownload && CoreFileHelper.instance.isStateDownloaded(state)) { + if (this.siteCanDownload && CoreFileHelper.isStateDownloaded(state)) { // Package is downloaded, use the local URL. localUrl = await this.getLocalUrl(); } @@ -116,7 +116,7 @@ export class CoreH5PIframeComponent implements OnChanges, OnDestroy { // Local package. this.iframeSrc = localUrl; } else { - this.onlinePlayerUrl = this.onlinePlayerUrl || CoreH5P.instance.h5pPlayer.calculateOnlinePlayerUrl( + this.onlinePlayerUrl = this.onlinePlayerUrl || CoreH5P.h5pPlayer.calculateOnlinePlayerUrl( this.site.getURL(), this.fileUrl || '', this.displayOptions, @@ -133,10 +133,10 @@ export class CoreH5PIframeComponent implements OnChanges, OnDestroy { const url = await this.site.getAutoLoginUrl(src, false); // Add the preventredirect param so the user can authenticate. - this.iframeSrc = CoreUrlUtils.instance.addParamsToUrl(url, { preventredirect: false }); + this.iframeSrc = CoreUrlUtils.addParamsToUrl(url, { preventredirect: false }); } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading H5P package.', true); + CoreDomUtils.showErrorModalDefault(error, 'Error loading H5P package.', true); } finally { this.addResizerScript(); @@ -151,7 +151,7 @@ export class CoreH5PIframeComponent implements OnChanges, OnDestroy { */ protected async getLocalUrl(): Promise { try { - const url = await CoreH5P.instance.h5pPlayer.getContentIndexFileUrl( + const url = await CoreH5P.h5pPlayer.getContentIndexFileUrl( this.fileUrl!, this.displayOptions, this.trackComponent, @@ -163,14 +163,14 @@ export class CoreH5PIframeComponent implements OnChanges, OnDestroy { } catch (error) { // Index file doesn't exist, probably deleted because a lib was updated. Try to create it again. try { - const path = await CoreFilepool.instance.getInternalUrlByUrl(this.siteId, this.fileUrl!); + const path = await CoreFilepool.getInternalUrlByUrl(this.siteId, this.fileUrl!); - const file = await CoreFile.instance.getFile(path); + const file = await CoreFile.getFile(path); await CoreH5PHelper.saveH5P(this.fileUrl!, file, this.siteId); // File treated. Try to get the index file URL again. - const url = await CoreH5P.instance.h5pPlayer.getContentIndexFileUrl( + const url = await CoreH5P.h5pPlayer.getContentIndexFileUrl( this.fileUrl!, this.displayOptions, this.trackComponent, @@ -198,7 +198,7 @@ export class CoreH5PIframeComponent implements OnChanges, OnDestroy { const script = document.createElement('script'); script.id = 'core-h5p-resizer-script'; script.type = 'text/javascript'; - script.src = CoreH5P.instance.h5pPlayer.getResizerScriptUrl(); + script.src = CoreH5P.h5pPlayer.getResizerScriptUrl(); document.head.appendChild(script); } diff --git a/src/core/features/h5p/components/h5p-player/h5p-player.ts b/src/core/features/h5p/components/h5p-player/h5p-player.ts index 27830dc58..a8664a1d8 100644 --- a/src/core/features/h5p/components/h5p-player/h5p-player.ts +++ b/src/core/features/h5p/components/h5p-player/h5p-player.ts @@ -59,9 +59,9 @@ export class CoreH5PPlayerComponent implements OnInit, OnChanges, OnDestroy { ) { this.logger = CoreLogger.getInstance('CoreH5PPlayerComponent'); - this.site = CoreSites.instance.getCurrentSite()!; + this.site = CoreSites.getCurrentSite()!; this.siteId = this.site.getId(); - this.siteCanDownload = this.site.canDownloadFiles() && !CoreH5P.instance.isOfflineDisabledInSite(); + this.siteCanDownload = this.site.canDownloadFiles() && !CoreH5P.isOfflineDisabledInSite(); } /** @@ -90,7 +90,7 @@ export class CoreH5PPlayerComponent implements OnInit, OnChanges, OnDestroy { e.preventDefault(); e.stopPropagation(); - this.displayOptions = CoreH5P.instance.h5pPlayer.getDisplayOptionsFromUrlParams(this.urlParams); + this.displayOptions = CoreH5P.h5pPlayer.getDisplayOptionsFromUrlParams(this.urlParams); this.showPackage = true; if (!this.canDownload || (this.state != CoreConstants.OUTDATED && this.state != CoreConstants.NOT_DOWNLOADED)) { @@ -111,28 +111,28 @@ export class CoreH5PPlayerComponent implements OnInit, OnChanges, OnDestroy { * @return Promise resolved when done. */ async download(): Promise { - if (!CoreApp.instance.isOnline()) { - CoreDomUtils.instance.showErrorModal('core.networkerrormsg', true); + if (!CoreApp.isOnline()) { + CoreDomUtils.showErrorModal('core.networkerrormsg', true); return; } try { // Get the file size and ask the user to confirm. - const size = await CorePluginFileDelegate.instance.getFileSize({ fileurl: this.urlParams!.url }, this.siteId); + const size = await CorePluginFileDelegate.getFileSize({ fileurl: this.urlParams!.url }, this.siteId); - await CoreDomUtils.instance.confirmDownloadSize({ size: size, total: true }); + await CoreDomUtils.confirmDownloadSize({ size: size, total: true }); // User confirmed, add to the queue. - await CoreFilepool.instance.addToQueueByUrl(this.siteId, this.urlParams!.url, this.component, this.componentId); + await CoreFilepool.addToQueueByUrl(this.siteId, this.urlParams!.url, this.component, this.componentId); } catch (error) { - if (CoreDomUtils.instance.isCanceledError(error)) { + if (CoreDomUtils.isCanceledError(error)) { // User cancelled, stop. return; } - CoreDomUtils.instance.showErrorModalDefault(error, 'core.errordownloading', true); + CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); this.calculateState(); } } @@ -143,17 +143,17 @@ export class CoreH5PPlayerComponent implements OnInit, OnChanges, OnDestroy { * @return Promise resolved when done. */ protected async attemptDownloadInBg(): Promise { - if (!this.urlParams || !this.src || !this.siteCanDownload || !CoreH5P.instance.canGetTrustedH5PFileInSite() || - !CoreApp.instance.isOnline()) { + if (!this.urlParams || !this.src || !this.siteCanDownload || !CoreH5P.canGetTrustedH5PFileInSite() || + !CoreApp.isOnline()) { return; } // Get the file size. - const size = await CorePluginFileDelegate.instance.getFileSize({ fileurl: this.urlParams.url }, this.siteId); + const size = await CorePluginFileDelegate.getFileSize({ fileurl: this.urlParams.url }, this.siteId); - if (CoreFilepool.instance.shouldDownload(size)) { + if (CoreFilepool.shouldDownload(size)) { // Download the file in background. - CoreFilepool.instance.addToQueueByUrl(this.siteId, this.urlParams.url, this.component, this.componentId); + CoreFilepool.addToQueueByUrl(this.siteId, this.urlParams.url, this.component, this.componentId); } } @@ -164,14 +164,14 @@ export class CoreH5PPlayerComponent implements OnInit, OnChanges, OnDestroy { */ protected async checkCanDownload(): Promise { this.observer && this.observer.off(); - this.urlParams = CoreUrlUtils.instance.extractUrlParams(this.src || ''); + this.urlParams = CoreUrlUtils.extractUrlParams(this.src || ''); - if (this.src && this.siteCanDownload && CoreH5P.instance.canGetTrustedH5PFileInSite() && this.site.containsUrl(this.src)) { + if (this.src && this.siteCanDownload && CoreH5P.canGetTrustedH5PFileInSite() && this.site.containsUrl(this.src)) { this.calculateState(); // Listen for changes in the state. try { - const eventName = await CoreFilepool.instance.getFileEventNameByUrl(this.siteId, this.urlParams.url); + const eventName = await CoreFilepool.getFileEventNameByUrl(this.siteId, this.urlParams.url); this.observer = CoreEvents.on(eventName, () => { this.calculateState(); @@ -198,7 +198,7 @@ export class CoreH5PPlayerComponent implements OnInit, OnChanges, OnDestroy { // Get the status of the file. try { - const state = await CoreFilepool.instance.getFileStateByUrl(this.siteId, this.urlParams!.url); + const state = await CoreFilepool.getFileStateByUrl(this.siteId, this.urlParams!.url); this.canDownload = true; this.state = state; diff --git a/src/core/features/h5p/h5p.module.ts b/src/core/features/h5p/h5p.module.ts index cc9b809dc..cd988c458 100644 --- a/src/core/features/h5p/h5p.module.ts +++ b/src/core/features/h5p/h5p.module.ts @@ -35,7 +35,7 @@ import { CoreH5PPluginFileHandler } from './services/handlers/pluginfile'; multi: true, deps: [], useFactory: () => () => { - CorePluginFileDelegate.instance.registerHandler(CoreH5PPluginFileHandler.instance); + CorePluginFileDelegate.registerHandler(CoreH5PPluginFileHandler.instance); }, }, ], diff --git a/src/core/features/h5p/services/h5p.ts b/src/core/features/h5p/services/h5p.ts index bb3106fc6..9d54c1bc9 100644 --- a/src/core/features/h5p/services/h5p.ts +++ b/src/core/features/h5p/services/h5p.ts @@ -63,7 +63,7 @@ export class CoreH5PProvider { * @since 3.8 */ async canGetTrustedH5PFile(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.canGetTrustedH5PFileInSite(site); } @@ -76,7 +76,7 @@ export class CoreH5PProvider { * @since 3.8 */ canGetTrustedH5PFileInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!(site?.wsAvailable('core_h5p_get_trusted_h5p_file')); } @@ -99,7 +99,7 @@ export class CoreH5PProvider { options = options || {}; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data: CoreH5pGetTrustedH5pFileWSParams = { url: this.treatH5PUrl(url, site.getURL()), @@ -157,7 +157,7 @@ export class CoreH5PProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAllGetTrustedH5PFile(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getTrustedH5PFilePrefixCacheKey()); } @@ -170,7 +170,7 @@ export class CoreH5PProvider { * @return Promise resolved when the data is invalidated. */ async invalidateGetTrustedH5PFile(url: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getTrustedH5PFileCacheKey(url)); } @@ -182,7 +182,7 @@ export class CoreH5PProvider { * @return Promise resolved with boolean: whether is disabled. */ async isOfflineDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isOfflineDisabledInSite(site); } @@ -194,7 +194,7 @@ export class CoreH5PProvider { * @return Whether is disabled. */ isOfflineDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!(site?.isFeatureDisabled('NoDelegate_H5POffline')); } @@ -207,16 +207,23 @@ export class CoreH5PProvider { * @return Treated url. */ treatH5PUrl(url: string, siteUrl: string): string { - if (url.indexOf(CoreTextUtils.instance.concatenatePaths(siteUrl, '/webservice/pluginfile.php')) === 0) { + if (url.indexOf(CoreTextUtils.concatenatePaths(siteUrl, '/webservice/pluginfile.php')) === 0) { url = url.replace('/webservice/pluginfile', '/pluginfile'); } - return CoreUrlUtils.instance.removeUrlParams(url); + return CoreUrlUtils.removeUrlParams(url); } } -export class CoreH5P extends makeSingleton(CoreH5PProvider) {} +export const CoreH5P = makeSingleton(CoreH5PProvider, [ + 'h5pCore', + 'h5pFramework', + 'h5pPlayer', + 'h5pStorage', + 'h5pValidator', + 'queueRunner', +]); /** * Params of core_h5p_get_trusted_h5p_file WS. diff --git a/src/core/features/h5p/services/handlers/pluginfile.ts b/src/core/features/h5p/services/handlers/pluginfile.ts index 05b816b35..879710aec 100644 --- a/src/core/features/h5p/services/handlers/pluginfile.ts +++ b/src/core/features/h5p/services/handlers/pluginfile.ts @@ -44,7 +44,7 @@ export class CoreH5PPluginFileHandlerService implements CorePluginFileHandler { */ async fileDeleted(fileUrl: string, path: string, siteId?: string): Promise { // If an h5p file is deleted, remove the contents folder. - await CoreH5P.instance.h5pPlayer.deleteContentByUrl(fileUrl, siteId); + await CoreH5P.h5pPlayer.deleteContentByUrl(fileUrl, siteId); } /** @@ -55,14 +55,14 @@ export class CoreH5PPluginFileHandlerService implements CorePluginFileHandler { * @return Promise resolved with the file to use. Rejected if cannot download. */ async getDownloadableFile(file: CoreWSExternalFile, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (site.containsUrl(file.fileurl) && file.fileurl.match(/pluginfile\.php\/[^/]+\/core_h5p\/export\//i)) { // It's already a deployed file, use it. return file; } - return CoreH5P.instance.getTrustedH5PFile(file.fileurl, {}, false, siteId); + return CoreH5P.getTrustedH5PFile(file.fileurl, {}, false, siteId); } /** @@ -77,7 +77,7 @@ export class CoreH5PPluginFileHandlerService implements CorePluginFileHandler { const urls: string[] = []; for (let i = 0; i < iframes.length; i++) { - const params = CoreUrlUtils.instance.extractUrlParams(iframes[i].src); + const params = CoreUrlUtils.extractUrlParams(iframes[i].src); if (params.url) { urls.push(params.url); @@ -100,7 +100,7 @@ export class CoreH5PPluginFileHandlerService implements CorePluginFileHandler { return trustedFile.filesize || 0; } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // WS returned an error, it means it cannot be downloaded. return 0; } @@ -115,7 +115,7 @@ export class CoreH5PPluginFileHandlerService implements CorePluginFileHandler { * @return Whether or not the handler is enabled on a site level. */ async isEnabled(): Promise { - return CoreH5P.instance.canGetTrustedH5PFileInSite(); + return CoreH5P.canGetTrustedH5PFileInSite(); } /** @@ -126,12 +126,12 @@ export class CoreH5PPluginFileHandlerService implements CorePluginFileHandler { * @return Promise resolved with a boolean and a reason why it isn't downloadable if needed. */ async isFileDownloadable(file: CoreWSExternalFile, siteId?: string): Promise { - const offlineDisabled = await CoreH5P.instance.isOfflineDisabled(siteId); + const offlineDisabled = await CoreH5P.isOfflineDisabled(siteId); if (offlineDisabled) { return { downloadable: false, - reason: Translate.instance.instant('core.h5p.offlinedisabled'), + reason: Translate.instant('core.h5p.offlinedisabled'), }; } else { return { @@ -147,7 +147,7 @@ export class CoreH5PPluginFileHandlerService implements CorePluginFileHandler { * @return Whether the file should be treated by this handler. */ shouldHandleFile(file: CoreWSExternalFile): boolean { - return CoreMimetypeUtils.instance.guessExtensionFromUrl(file.fileurl) == 'h5p'; + return CoreMimetypeUtils.guessExtensionFromUrl(file.fileurl) == 'h5p'; } /** @@ -170,4 +170,4 @@ export class CoreH5PPluginFileHandlerService implements CorePluginFileHandler { } -export class CoreH5PPluginFileHandler extends makeSingleton(CoreH5PPluginFileHandlerService) {} +export const CoreH5PPluginFileHandler = makeSingleton(CoreH5PPluginFileHandlerService); diff --git a/src/core/features/login/components/site-help/site-help.ts b/src/core/features/login/components/site-help/site-help.ts index baab97d08..fe3f42bf0 100644 --- a/src/core/features/login/components/site-help/site-help.ts +++ b/src/core/features/login/components/site-help/site-help.ts @@ -35,18 +35,18 @@ export class CoreLoginSiteHelpComponent { constructor() { - this.canScanQR = CoreUtils.instance.canScanQR(); + this.canScanQR = CoreUtils.canScanQR(); this.urlImageHtml = CoreLoginHelperProvider.FAQ_URL_IMAGE_HTML; this.qrCodeImageHtml = CoreLoginHelperProvider.FAQ_QRCODE_IMAGE_HTML; this.setupLinkHtml = 'https://moodle.com/getstarted/'; + Translate.instant('core.login.faqsetupsitelinktitle') + '">https://moodle.com/getstarted/'; } /** * Close help modal. */ closeHelp(): void { - ModalController.instance.dismiss(); + ModalController.dismiss(); } } diff --git a/src/core/features/login/components/site-onboarding/site-onboarding.ts b/src/core/features/login/components/site-onboarding/site-onboarding.ts index 197dbe391..b0ae8e338 100644 --- a/src/core/features/login/components/site-onboarding/site-onboarding.ts +++ b/src/core/features/login/components/site-onboarding/site-onboarding.ts @@ -51,7 +51,7 @@ export class CoreLoginSiteOnboardingComponent { e.stopPropagation(); if (this.step == 0) { - ModalController.instance.dismiss(); + ModalController.dismiss(); } else { this.step--; } @@ -66,7 +66,7 @@ export class CoreLoginSiteOnboardingComponent { e.stopPropagation(); this.saveOnboardingDone(); - ModalController.instance.dismiss(); + ModalController.dismiss(); } /** @@ -79,16 +79,16 @@ export class CoreLoginSiteOnboardingComponent { this.saveOnboardingDone(); - CoreUtils.instance.openInBrowser('https://moodle.com/getstarted/'); + CoreUtils.openInBrowser('https://moodle.com/getstarted/'); - ModalController.instance.dismiss(); + ModalController.dismiss(); } /** * Saves the onboarding has finished. */ protected saveOnboardingDone(): void { - CoreConfig.instance.set(CoreLoginHelperProvider.ONBOARDING_DONE, 1); + CoreConfig.set(CoreLoginHelperProvider.ONBOARDING_DONE, 1); } } diff --git a/src/core/features/login/guards/has-sites.ts b/src/core/features/login/guards/has-sites.ts index 869ee734c..7ca80574e 100644 --- a/src/core/features/login/guards/has-sites.ts +++ b/src/core/features/login/guards/has-sites.ts @@ -42,14 +42,14 @@ export class CoreLoginHasSitesGuard implements CanActivate, CanLoad { * Check if the user has any sites stored. */ private async guard(): Promise { - const sites = await CoreUtils.instance.ignoreErrors(CoreSites.instance.getSites(), []); + const sites = await CoreUtils.ignoreErrors(CoreSites.getSites(), []); if (sites.length > 0) { return true; } - const [path, params] = CoreLoginHelper.instance.getAddSiteRouteInfo(); - const route = Router.instance.parseUrl(path); + const [path, params] = CoreLoginHelper.getAddSiteRouteInfo(); + const route = Router.parseUrl(path); route.queryParams = params; diff --git a/src/core/features/login/pages/change-password/change-password.ts b/src/core/features/login/pages/change-password/change-password.ts index 6cb928503..1c0428e4e 100644 --- a/src/core/features/login/pages/change-password/change-password.ts +++ b/src/core/features/login/pages/change-password/change-password.ts @@ -33,16 +33,16 @@ export class CoreLoginChangePasswordPage { logoutLabel: string; constructor() { - this.logoutLabel = CoreLoginHelper.instance.getLogoutLabel(); + this.logoutLabel = CoreLoginHelper.getLogoutLabel(); } /** * Show a help modal. */ showHelp(): void { - CoreDomUtils.instance.showAlert( - Translate.instance.instant('core.help'), - Translate.instance.instant('core.login.changepasswordhelp'), + CoreDomUtils.showAlert( + Translate.instant('core.help'), + Translate.instant('core.login.changepasswordhelp'), ); } @@ -50,8 +50,8 @@ export class CoreLoginChangePasswordPage { * Open the change password page in a browser. */ openChangePasswordPage(): void { - CoreLoginHelper.instance.openInAppForEdit( - CoreSites.instance.getCurrentSiteId(), + CoreLoginHelper.openInAppForEdit( + CoreSites.getCurrentSiteId(), '/login/change_password.php', undefined, true, @@ -63,7 +63,7 @@ export class CoreLoginChangePasswordPage { * Login the user. */ login(): void { - CoreNavigator.instance.navigateToSiteHome(); + CoreNavigator.navigateToSiteHome(); this.changingPassword = false; } @@ -71,7 +71,7 @@ export class CoreLoginChangePasswordPage { * Logout the user. */ logout(): void { - CoreSites.instance.logout(); + CoreSites.logout(); this.changingPassword = false; } diff --git a/src/core/features/login/pages/credentials/credentials.ts b/src/core/features/login/pages/credentials/credentials.ts index 677ef5638..803f4354d 100644 --- a/src/core/features/login/pages/credentials/credentials.ts +++ b/src/core/features/login/pages/credentials/credentials.ts @@ -62,10 +62,10 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { protected fb: FormBuilder, ) { - const canScanQR = CoreUtils.instance.canScanQR(); + const canScanQR = CoreUtils.canScanQR(); if (canScanQR) { if (typeof CoreConstants.CONFIG.displayqroncredentialscreen == 'undefined') { - this.showScanQR = CoreLoginHelper.instance.isFixedUrlSet(); + this.showScanQR = CoreLoginHelper.isFixedUrlSet(); } else { this.showScanQR = !!CoreConstants.CONFIG.displayqroncredentialscreen; } @@ -78,27 +78,27 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { * Initialize the component. */ ngOnInit(): void { - const siteUrl = CoreNavigator.instance.getRouteParam('siteUrl'); + const siteUrl = CoreNavigator.getRouteParam('siteUrl'); if (!siteUrl) { - CoreDomUtils.instance.showErrorModal('Site URL not supplied.'); - CoreNavigator.instance.back(); + CoreDomUtils.showErrorModal('Site URL not supplied.'); + CoreNavigator.back(); return; } this.siteUrl = siteUrl; - this.siteName = CoreNavigator.instance.getRouteParam('siteName'); - this.logoUrl = !CoreConstants.CONFIG.forceLoginLogo && CoreNavigator.instance.getRouteParam('logoUrl') || undefined; - this.siteConfig = CoreNavigator.instance.getRouteParam('siteConfig'); - this.urlToOpen = CoreNavigator.instance.getRouteParam('urlToOpen'); + this.siteName = CoreNavigator.getRouteParam('siteName'); + this.logoUrl = !CoreConstants.CONFIG.forceLoginLogo && CoreNavigator.getRouteParam('logoUrl') || undefined; + this.siteConfig = CoreNavigator.getRouteParam('siteConfig'); + this.urlToOpen = CoreNavigator.getRouteParam('urlToOpen'); this.credForm = this.fb.group({ - username: [CoreNavigator.instance.getRouteParam('username') || '', Validators.required], + username: [CoreNavigator.getRouteParam('username') || '', Validators.required], password: ['', Validators.required], }); this.treatSiteConfig(); - this.isFixedUrlSet = CoreLoginHelper.instance.isFixedUrlSet(); + this.isFixedUrlSet = CoreLoginHelper.isFixedUrlSet(); if (this.isFixedUrlSet) { // Fixed URL, we need to check if it uses browser SSO login. @@ -123,7 +123,7 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { const protocol = siteUrl.indexOf('http://') === 0 ? 'http://' : undefined; try { - const result = await CoreSites.instance.checkSite(siteUrl, protocol); + const result = await CoreSites.checkSite(siteUrl, protocol); this.siteChecked = true; this.siteUrl = result.siteUrl; @@ -132,16 +132,16 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { this.treatSiteConfig(); if (result && result.warning) { - CoreDomUtils.instance.showErrorModal(result.warning, true, 4000); + CoreDomUtils.showErrorModal(result.warning, true, 4000); } - if (CoreLoginHelper.instance.isSSOLoginNeeded(result.code)) { + if (CoreLoginHelper.isSSOLoginNeeded(result.code)) { // SSO. User needs to authenticate in a browser. this.isBrowserSSO = true; // Check that there's no SSO authentication ongoing and the view hasn't changed. - if (!CoreApp.instance.isSSOAuthenticationOngoing() && !this.viewLeft) { - CoreLoginHelper.instance.confirmAndOpenBrowserForSSOLogin( + if (!CoreApp.isSSOAuthenticationOngoing() && !this.viewLeft) { + CoreLoginHelper.confirmAndOpenBrowserForSSOLogin( result.siteUrl, result.code, result.service, @@ -153,7 +153,7 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { } } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { this.pageLoaded = true; } @@ -165,14 +165,14 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { protected treatSiteConfig(): void { if (this.siteConfig) { this.siteName = CoreConstants.CONFIG.sitename ? CoreConstants.CONFIG.sitename : this.siteConfig.sitename; - this.logoUrl = CoreLoginHelper.instance.getLogoUrl(this.siteConfig); - this.authInstructions = this.siteConfig.authinstructions || Translate.instance.instant('core.login.loginsteps'); + this.logoUrl = CoreLoginHelper.getLogoUrl(this.siteConfig); + this.authInstructions = this.siteConfig.authinstructions || Translate.instant('core.login.loginsteps'); - const disabledFeatures = CoreLoginHelper.instance.getDisabledFeatures(this.siteConfig); - this.identityProviders = CoreLoginHelper.instance.getValidIdentityProviders(this.siteConfig, disabledFeatures); + const disabledFeatures = CoreLoginHelper.getDisabledFeatures(this.siteConfig); + this.identityProviders = CoreLoginHelper.getValidIdentityProviders(this.siteConfig, disabledFeatures); this.canSignup = this.siteConfig.registerauth == 'email' && - !CoreLoginHelper.instance.isEmailSignupDisabled(this.siteConfig, disabledFeatures); - this.showForgottenPassword = !CoreLoginHelper.instance.isForgottenPasswordDisabled(this.siteConfig, disabledFeatures); + !CoreLoginHelper.isEmailSignupDisabled(this.siteConfig, disabledFeatures); + this.showForgottenPassword = !CoreLoginHelper.isForgottenPasswordDisabled(this.siteConfig, disabledFeatures); if (!this.eventThrown && !this.viewLeft) { this.eventThrown = true; @@ -197,7 +197,7 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { e.stopPropagation(); } - CoreApp.instance.closeKeyboard(); + CoreApp.closeKeyboard(); // Get input data. const siteUrl = this.siteUrl; @@ -217,29 +217,29 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { } if (!username) { - CoreDomUtils.instance.showErrorModal('core.login.usernamerequired', true); + CoreDomUtils.showErrorModal('core.login.usernamerequired', true); return; } if (!password) { - CoreDomUtils.instance.showErrorModal('core.login.passwordrequired', true); + CoreDomUtils.showErrorModal('core.login.passwordrequired', true); return; } - if (!CoreApp.instance.isOnline()) { - CoreDomUtils.instance.showErrorModal('core.networkerrormsg', true); + if (!CoreApp.isOnline()) { + CoreDomUtils.showErrorModal('core.networkerrormsg', true); return; } - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); // Start the authentication process. try { - const data = await CoreSites.instance.getUserToken(siteUrl, username, password); + const data = await CoreSites.getUserToken(siteUrl, username, password); - const id = await CoreSites.instance.newSite(data.siteUrl, data.token, data.privateToken); + const id = await CoreSites.newSite(data.siteUrl, data.token, data.privateToken); // Reset fields so the data is not in the view anymore. this.credForm.controls['username'].reset(); @@ -248,12 +248,12 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { this.siteId = id; // @todo test that this is working properly. - await CoreNavigator.instance.navigateToSiteHome({ params: { urlToOpen: this.urlToOpen } }); + await CoreNavigator.navigateToSiteHome({ params: { urlToOpen: this.urlToOpen } }); } catch (error) { - CoreLoginHelper.instance.treatUserTokenError(siteUrl, error, username, password); + CoreLoginHelper.treatUserTokenError(siteUrl, error, username, password); if (error.loggedout) { - CoreNavigator.instance.navigate('/login/sites', { reset: true }); + CoreNavigator.navigate('/login/sites', { reset: true }); } else if (error.errorcode == 'forcepasswordchangenotice') { // Reset password field. this.credForm.controls.password.reset(); @@ -261,7 +261,7 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { } finally { modal.dismiss(); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, true); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, true); } } @@ -269,7 +269,7 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { * Forgotten password button clicked. */ forgottenPassword(): void { - CoreLoginHelper.instance.forgottenPasswordClicked(this.siteUrl, this.credForm.value.username, this.siteConfig); + CoreLoginHelper.forgottenPasswordClicked(this.siteUrl, this.credForm.value.username, this.siteConfig); } /** @@ -278,8 +278,8 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { * @param provider The provider that was clicked. */ oauthClicked(provider: CoreSiteIdentityProvider): void { - if (!CoreLoginHelper.instance.openBrowserForOAuthLogin(this.siteUrl, provider, this.siteConfig?.launchurl)) { - CoreDomUtils.instance.showErrorModal('Invalid data.'); + if (!CoreLoginHelper.openBrowserForOAuthLogin(this.siteUrl, provider, this.siteConfig?.launchurl)) { + CoreDomUtils.showErrorModal('Invalid data.'); } } @@ -288,19 +288,19 @@ export class CoreLoginCredentialsPage implements OnInit, OnDestroy { */ showInstructionsAndScanQR(): void { // Show some instructions first. - CoreDomUtils.instance.showAlertWithOptions({ - header: Translate.instance.instant('core.login.faqwhereisqrcode'), - message: Translate.instance.instant( + CoreDomUtils.showAlertWithOptions({ + header: Translate.instant('core.login.faqwhereisqrcode'), + message: Translate.instant( 'core.login.faqwhereisqrcodeanswer', { $image: CoreLoginHelperProvider.FAQ_QRCODE_IMAGE_HTML }, ), buttons: [ { - text: Translate.instance.instant('core.cancel'), + text: Translate.instant('core.cancel'), role: 'cancel', }, { - text: Translate.instance.instant('core.next'), + text: Translate.instant('core.next'), handler: (): void => { this.scanQR(); }, diff --git a/src/core/features/login/pages/email-signup/email-signup.ts b/src/core/features/login/pages/email-signup/email-signup.ts index 973862b9c..648e51acd 100644 --- a/src/core/features/login/pages/email-signup/email-signup.ts +++ b/src/core/features/login/pages/email-signup/email-signup.ts @@ -100,11 +100,11 @@ export class CoreLoginEmailSignupPage implements OnInit { }); // Setup validation errors. - this.usernameErrors = CoreLoginHelper.instance.getErrorMessages('core.login.usernamerequired'); - this.passwordErrors = CoreLoginHelper.instance.getErrorMessages('core.login.passwordrequired'); - this.emailErrors = CoreLoginHelper.instance.getErrorMessages('core.login.missingemail'); - this.policyErrors = CoreLoginHelper.instance.getErrorMessages('core.login.policyagree'); - this.email2Errors = CoreLoginHelper.instance.getErrorMessages( + this.usernameErrors = CoreLoginHelper.getErrorMessages('core.login.usernamerequired'); + this.passwordErrors = CoreLoginHelper.getErrorMessages('core.login.passwordrequired'); + this.emailErrors = CoreLoginHelper.getErrorMessages('core.login.missingemail'); + this.policyErrors = CoreLoginHelper.getErrorMessages('core.login.policyagree'); + this.email2Errors = CoreLoginHelper.getErrorMessages( 'core.login.missingemail', undefined, 'core.login.emailnotmatch', @@ -115,10 +115,10 @@ export class CoreLoginEmailSignupPage implements OnInit { * Component initialized. */ ngOnInit(): void { - const siteUrl = CoreNavigator.instance.getRouteParam('siteUrl'); + const siteUrl = CoreNavigator.getRouteParam('siteUrl'); if (!siteUrl) { - CoreDomUtils.instance.showErrorModal('Site URL not supplied.'); - CoreNavigator.instance.back(); + CoreDomUtils.showErrorModal('Site URL not supplied.'); + CoreNavigator.back(); return; } @@ -157,15 +157,15 @@ export class CoreLoginEmailSignupPage implements OnInit { protected async fetchData(): Promise { try { // Get site config. - this.siteConfig = await CoreSites.instance.getSitePublicConfig(this.siteUrl); - this.signupUrl = CoreTextUtils.instance.concatenatePaths(this.siteConfig.httpswwwroot, 'login/signup.php'); + this.siteConfig = await CoreSites.getSitePublicConfig(this.siteUrl); + this.signupUrl = CoreTextUtils.concatenatePaths(this.siteConfig.httpswwwroot, 'login/signup.php'); if (this.treatSiteConfig()) { // Check content verification. if (typeof this.ageDigitalConsentVerification == 'undefined') { - const result = await CoreUtils.instance.ignoreErrors( - CoreWS.instance.callAjax( + const result = await CoreUtils.ignoreErrors( + CoreWS.callAjax( 'core_auth_is_age_digital_consent_verification_enabled', {}, { siteUrl: this.siteUrl }, @@ -181,7 +181,7 @@ export class CoreLoginEmailSignupPage implements OnInit { this.completeFormGroup(); } catch (error) { if (this.allRequiredSupported) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } } } @@ -192,19 +192,19 @@ export class CoreLoginEmailSignupPage implements OnInit { * @return Promise resolved when done. */ protected async getSignupSettings(): Promise { - this.settings = await CoreWS.instance.callAjax( + this.settings = await CoreWS.callAjax( 'auth_email_get_signup_settings', {}, { siteUrl: this.siteUrl }, ); - if (CoreUserProfileFieldDelegate.instance.hasRequiredUnsupportedField(this.settings.profilefields)) { + if (CoreUserProfileFieldDelegate.hasRequiredUnsupportedField(this.settings.profilefields)) { this.allRequiredSupported = false; - throw new Error(Translate.instance.instant('core.login.signuprequiredfieldnotsupported')); + throw new Error(Translate.instant('core.login.signuprequiredfieldnotsupported')); } - this.categories = CoreLoginHelper.instance.formatProfileFieldsForSignup(this.settings.profilefields); + this.categories = CoreLoginHelper.formatProfileFieldsForSignup(this.settings.profilefields); if (this.settings.recaptchapublickey) { this.captcha.recaptcharesponse = ''; // Reset captcha. @@ -217,11 +217,11 @@ export class CoreLoginEmailSignupPage implements OnInit { this.namefieldsErrors = {}; if (this.settings.namefields) { this.settings.namefields.forEach((field) => { - this.namefieldsErrors![field] = CoreLoginHelper.instance.getErrorMessages('core.login.missing' + field); + this.namefieldsErrors![field] = CoreLoginHelper.getErrorMessages('core.login.missing' + field); }); } - this.countries = await CoreUtils.instance.getCountryListSorted(); + this.countries = await CoreUtils.getCountryListSorted(); } /** @@ -230,7 +230,7 @@ export class CoreLoginEmailSignupPage implements OnInit { * @return True if success. */ protected treatSiteConfig(): boolean { - if (this.siteConfig?.registerauth == 'email' && !CoreLoginHelper.instance.isEmailSignupDisabled(this.siteConfig)) { + if (this.siteConfig?.registerauth == 'email' && !CoreLoginHelper.isEmailSignupDisabled(this.siteConfig)) { this.siteName = CoreConstants.CONFIG.sitename ? CoreConstants.CONFIG.sitename : this.siteConfig.sitename; this.authInstructions = this.siteConfig.authinstructions; this.ageDigitalConsentVerification = this.siteConfig.agedigitalconsentverification; @@ -240,13 +240,13 @@ export class CoreLoginEmailSignupPage implements OnInit { return true; } else { - CoreDomUtils.instance.showErrorModal( - Translate.instance.instant( + CoreDomUtils.showErrorModal( + Translate.instant( 'core.login.signupplugindisabled', - { $a: Translate.instance.instant('core.login.auth_email') }, + { $a: Translate.instant('core.login.auth_email') }, ), ); - CoreNavigator.instance.back(); + CoreNavigator.back(); return false; } @@ -281,34 +281,34 @@ export class CoreLoginEmailSignupPage implements OnInit { this.changeDetector.detectChanges(); // Scroll to the first element with errors. - const errorFound = CoreDomUtils.instance.scrollToInputError( + const errorFound = CoreDomUtils.scrollToInputError( this.elementRef.nativeElement, this.content, ); if (!errorFound) { // Input not found, show an error modal. - CoreDomUtils.instance.showErrorModal('core.errorinvalidform', true); + CoreDomUtils.showErrorModal('core.errorinvalidform', true); } return; } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); const params: SignupUserWSParams = { username: this.signupForm.value.username.trim().toLowerCase(), password: this.signupForm.value.password, - firstname: CoreTextUtils.instance.cleanTags(this.signupForm.value.firstname), - lastname: CoreTextUtils.instance.cleanTags(this.signupForm.value.lastname), + firstname: CoreTextUtils.cleanTags(this.signupForm.value.firstname), + lastname: CoreTextUtils.cleanTags(this.signupForm.value.lastname), email: this.signupForm.value.email.trim(), - city: CoreTextUtils.instance.cleanTags(this.signupForm.value.city), + city: CoreTextUtils.cleanTags(this.signupForm.value.city), country: this.signupForm.value.country, }; if (this.siteConfig?.launchurl) { - const service = CoreSites.instance.determineService(this.siteUrl); - params.redirect = CoreLoginHelper.instance.prepareForSSOLogin(this.siteUrl, service, this.siteConfig.launchurl); + const service = CoreSites.determineService(this.siteUrl); + params.redirect = CoreLoginHelper.prepareForSSOLogin(this.siteUrl, service, this.siteConfig.launchurl); } // Get the recaptcha response (if needed). @@ -318,14 +318,14 @@ export class CoreLoginEmailSignupPage implements OnInit { try { // Get the data for the custom profile fields. - params.customprofilefields = await CoreUserProfileFieldDelegate.instance.getDataForFields( + params.customprofilefields = await CoreUserProfileFieldDelegate.getDataForFields( this.settings?.profilefields, true, 'email', this.signupForm.value, ); - const result = await CoreWS.instance.callAjax( + const result = await CoreWS.callAjax( 'auth_email_signup_user', params, { siteUrl: this.siteUrl }, @@ -333,26 +333,26 @@ export class CoreLoginEmailSignupPage implements OnInit { if (result.success) { - CoreDomUtils.instance.triggerFormSubmittedEvent(this.signupFormElement, true); + CoreDomUtils.triggerFormSubmittedEvent(this.signupFormElement, true); // Show alert and ho back. - const message = Translate.instance.instant('core.login.emailconfirmsent', { $a: params.email }); - CoreDomUtils.instance.showAlert(Translate.instance.instant('core.success'), message); - CoreNavigator.instance.back(); + const message = Translate.instant('core.login.emailconfirmsent', { $a: params.email }); + CoreDomUtils.showAlert(Translate.instant('core.success'), message); + CoreNavigator.back(); } else { if (result.warnings && result.warnings.length) { let error = result.warnings[0].message; if (error == 'incorrect-captcha-sol') { - error = Translate.instance.instant('core.login.recaptchaincorrect'); + error = Translate.instant('core.login.recaptchaincorrect'); } - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } else { - CoreDomUtils.instance.showErrorModal('core.login.usernotaddederror', true); + CoreDomUtils.showErrorModal('core.login.usernotaddederror', true); } } } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.login.usernotaddederror', true); + CoreDomUtils.showErrorModalDefault(error, 'core.login.usernotaddederror', true); } finally { modal.dismiss(); } @@ -365,21 +365,21 @@ export class CoreLoginEmailSignupPage implements OnInit { * @return Escaped mail. */ escapeMail(text: string): string { - return CoreTextUtils.instance.escapeForRegex(text); + return CoreTextUtils.escapeForRegex(text); } /** * Show authentication instructions. */ showAuthInstructions(): void { - CoreTextUtils.instance.viewText(Translate.instance.instant('core.login.instructions'), this.authInstructions!); + CoreTextUtils.viewText(Translate.instant('core.login.instructions'), this.authInstructions!); } /** * Show contact information on site (we have to display again the age verification form). */ showContactOnSite(): void { - CoreUtils.instance.openInBrowser(CoreTextUtils.instance.concatenatePaths(this.siteUrl, '/login/verify_age_location.php')); + CoreUtils.openInBrowser(CoreTextUtils.concatenatePaths(this.siteUrl, '/login/verify_age_location.php')); } /** @@ -393,21 +393,21 @@ export class CoreLoginEmailSignupPage implements OnInit { e.stopPropagation(); if (!this.ageVerificationForm.valid) { - CoreDomUtils.instance.showErrorModal('core.errorinvalidform', true); + CoreDomUtils.showErrorModal('core.errorinvalidform', true); return; } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); const params = this.ageVerificationForm.value; params.age = parseInt(params.age, 10); // Use just the integer part. try { - const result = await CoreWS.instance.callAjax('core_auth_is_minor', params, { siteUrl: this.siteUrl }); + const result = await CoreWS.callAjax('core_auth_is_minor', params, { siteUrl: this.siteUrl }); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.ageFormElement, true); + CoreDomUtils.triggerFormSubmittedEvent(this.ageFormElement, true); if (!result.status) { if (this.countryControl.value) { @@ -422,7 +422,7 @@ export class CoreLoginEmailSignupPage implements OnInit { } } catch (error) { // Something wrong, redirect to the site. - CoreDomUtils.instance.showErrorModal('There was an error verifying your age, please try again using the browser.'); + CoreDomUtils.showErrorModal('There was an error verifying your age, please try again using the browser.'); } finally { modal.dismiss(); } diff --git a/src/core/features/login/pages/forgotten-password/forgotten-password.ts b/src/core/features/login/pages/forgotten-password/forgotten-password.ts index b3aa6ac2a..e6e8eabb6 100644 --- a/src/core/features/login/pages/forgotten-password/forgotten-password.ts +++ b/src/core/features/login/pages/forgotten-password/forgotten-password.ts @@ -45,19 +45,19 @@ export class CoreLoginForgottenPasswordPage implements OnInit { * Initialize the component. */ ngOnInit(): void { - const siteUrl = CoreNavigator.instance.getRouteParam('siteUrl'); + const siteUrl = CoreNavigator.getRouteParam('siteUrl'); if (!siteUrl) { - CoreDomUtils.instance.showErrorModal('Site URL not supplied.'); - CoreNavigator.instance.back(); + CoreDomUtils.showErrorModal('Site URL not supplied.'); + CoreNavigator.back(); return; } this.siteUrl = siteUrl; - this.autoFocus = Platform.instance.is('tablet'); + this.autoFocus = Platform.is('tablet'); this.myForm = this.formBuilder.group({ field: ['username', Validators.required], - value: [CoreNavigator.instance.getRouteParam('username') || '', Validators.required], + value: [CoreNavigator.getRouteParam('username') || '', Validators.required], }); } @@ -74,16 +74,16 @@ export class CoreLoginForgottenPasswordPage implements OnInit { const value = this.myForm.value.value; if (!value) { - CoreDomUtils.instance.showErrorModal('core.login.usernameoremail', true); + CoreDomUtils.showErrorModal('core.login.usernameoremail', true); return; } - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); const isMail = field == 'email'; try { - const response = await CoreLoginHelper.instance.requestPasswordReset( + const response = await CoreLoginHelper.requestPasswordReset( this.siteUrl, isMail ? '' : value, isMail ? value : '', @@ -94,16 +94,16 @@ export class CoreLoginForgottenPasswordPage implements OnInit { this.showError(isMail, response.warnings!); } else if (response.status == 'emailpasswordconfirmnotsent' || response.status == 'emailpasswordconfirmnoemail') { // Error, not found. - CoreDomUtils.instance.showErrorModal(response.notice); + CoreDomUtils.showErrorModal(response.notice); } else { // Success. - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, true); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, true); - CoreDomUtils.instance.showAlert(Translate.instance.instant('core.success'), response.notice); - CoreNavigator.instance.back(); + CoreDomUtils.showAlert(Translate.instant('core.success'), response.notice); + CoreNavigator.back(); } } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { modal.dismiss(); } @@ -114,7 +114,7 @@ export class CoreLoginForgottenPasswordPage implements OnInit { for (let i = 0; i < warnings.length; i++) { const warning = warnings[i]; if ((warning.item == 'email' && isMail) || (warning.item == 'username' && !isMail)) { - CoreDomUtils.instance.showErrorModal(warning.message); + CoreDomUtils.showErrorModal(warning.message); break; } } diff --git a/src/core/features/login/pages/reconnect/reconnect.ts b/src/core/features/login/pages/reconnect/reconnect.ts index 047e1cd69..25424c0d6 100644 --- a/src/core/features/login/pages/reconnect/reconnect.ts +++ b/src/core/features/login/pages/reconnect/reconnect.ts @@ -62,7 +62,7 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { protected fb: FormBuilder, ) { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); this.isLoggedOut = !!currentSite?.isLoggedOut(); this.credForm = fb.group({ @@ -74,17 +74,17 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { * Initialize the component. */ async ngOnInit(): Promise { - const siteId = CoreNavigator.instance.getRouteParam('siteId'); + const siteId = CoreNavigator.getRouteParam('siteId'); if (!siteId) { return this.cancel(); } this.siteUrl = siteId; - this.page = CoreNavigator.instance.getRouteParam('pageName'); - this.pageParams = CoreNavigator.instance.getRouteParam('pageParams'); + this.page = CoreNavigator.getRouteParam('pageName'); + this.pageParams = CoreNavigator.getRouteParam('pageParams'); try { - const site = await CoreSites.instance.getSite(this.siteId); + const site = await CoreSites.getSite(this.siteId); if (!site.infos) { throw new CoreError('Invalid site'); @@ -100,9 +100,9 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { this.isOAuth = site.isOAuth(); // Show logo instead of avatar if it's a fixed site. - this.showSiteAvatar = !!this.userAvatar && !CoreLoginHelper.instance.getFixedSites(); + this.showSiteAvatar = !!this.userAvatar && !CoreLoginHelper.getFixedSites(); - const config = await CoreUtils.instance.ignoreErrors(site.getPublicConfig()); + const config = await CoreUtils.ignoreErrors(site.getPublicConfig()); if (!config) { return; @@ -110,13 +110,13 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { this.siteConfig = config; - await CoreSites.instance.checkRequiredMinimumVersion(config); + await CoreSites.checkRequiredMinimumVersion(config); // Check logoURL if user avatar is not set. if (this.userAvatar.startsWith(this.siteUrl + '/theme/image.php')) { this.showSiteAvatar = false; } - this.logoUrl = CoreLoginHelper.instance.getLogoUrl(config); + this.logoUrl = CoreLoginHelper.getLogoUrl(config); this.getDataFromConfig(this.siteConfig); } catch (error) { @@ -139,10 +139,10 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { * @param config Config to use. */ protected getDataFromConfig(config: CoreSitePublicConfigResponse): void { - const disabledFeatures = CoreLoginHelper.instance.getDisabledFeatures(config); + const disabledFeatures = CoreLoginHelper.getDisabledFeatures(config); - this.identityProviders = CoreLoginHelper.instance.getValidIdentityProviders(config, disabledFeatures); - this.showForgottenPassword = !CoreLoginHelper.instance.isForgottenPasswordDisabled(config); + this.identityProviders = CoreLoginHelper.getValidIdentityProviders(config, disabledFeatures); + this.showForgottenPassword = !CoreLoginHelper.isForgottenPasswordDisabled(config); if (!this.eventThrown && !this.viewLeft) { this.eventThrown = true; @@ -161,7 +161,7 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { e.stopPropagation(); } - CoreSites.instance.logout(); + CoreSites.logout(); } /** @@ -173,49 +173,49 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { e.preventDefault(); e.stopPropagation(); - CoreApp.instance.closeKeyboard(); + CoreApp.closeKeyboard(); // Get input data. const password = this.credForm.value.password; if (!password) { - CoreDomUtils.instance.showErrorModal('core.login.passwordrequired', true); + CoreDomUtils.showErrorModal('core.login.passwordrequired', true); return; } - if (!CoreApp.instance.isOnline()) { - CoreDomUtils.instance.showErrorModal('core.networkerrormsg', true); + if (!CoreApp.isOnline()) { + CoreDomUtils.showErrorModal('core.networkerrormsg', true); return; } - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { // Start the authentication process. - const data = await CoreSites.instance.getUserToken(this.siteUrl, this.username, password); + const data = await CoreSites.getUserToken(this.siteUrl, this.username, password); - await CoreSites.instance.updateSiteToken(this.siteUrl, this.username, data.token, data.privateToken); + await CoreSites.updateSiteToken(this.siteUrl, this.username, data.token, data.privateToken); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, true); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, true); // Update site info too. - await CoreSites.instance.updateSiteInfoByUrl(this.siteUrl, this.username); + await CoreSites.updateSiteInfoByUrl(this.siteUrl, this.username); // Reset fields so the data is not in the view anymore. this.credForm.controls['password'].reset(); // Go to the site initial page. // @todo test that this is working properly (could we use navigateToSitePath instead?). - await CoreNavigator.instance.navigateToSiteHome({ + await CoreNavigator.navigateToSiteHome({ params: { redirectPath: this.page, redirectParams: this.pageParams, }, }); } catch (error) { - CoreLoginHelper.instance.treatUserTokenError(this.siteUrl, error, this.username, password); + CoreLoginHelper.treatUserTokenError(this.siteUrl, error, this.username, password); if (error.loggedout) { this.cancel(); @@ -232,7 +232,7 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { * Forgotten password button clicked. */ forgottenPassword(): void { - CoreLoginHelper.instance.forgottenPasswordClicked(this.siteUrl, this.username, this.siteConfig); + CoreLoginHelper.forgottenPasswordClicked(this.siteUrl, this.username, this.siteConfig); } /** @@ -241,8 +241,8 @@ export class CoreLoginReconnectPage implements OnInit, OnDestroy { * @param provider The provider that was clicked. */ oauthClicked(provider: CoreSiteIdentityProvider): void { - if (!CoreLoginHelper.instance.openBrowserForOAuthLogin(this.siteUrl, provider, this.siteConfig?.launchurl)) { - CoreDomUtils.instance.showErrorModal('Invalid data.'); + if (!CoreLoginHelper.openBrowserForOAuthLogin(this.siteUrl, provider, this.siteConfig?.launchurl)) { + CoreDomUtils.showErrorModal('Invalid data.'); } } diff --git a/src/core/features/login/pages/site-policy/site-policy.ts b/src/core/features/login/pages/site-policy/site-policy.ts index 05faec926..f4804322b 100644 --- a/src/core/features/login/pages/site-policy/site-policy.ts +++ b/src/core/features/login/pages/site-policy/site-policy.ts @@ -42,8 +42,8 @@ export class CoreLoginSitePolicyPage implements OnInit { */ ngOnInit(): void { - this.siteId = CoreNavigator.instance.getRouteParam('siteId'); - this.currentSite = CoreSites.instance.getCurrentSite(); + this.siteId = CoreNavigator.getRouteParam('siteId'); + this.currentSite = CoreSites.getCurrentSite(); if (!this.currentSite) { // Not logged in, stop. @@ -72,9 +72,9 @@ export class CoreLoginSitePolicyPage implements OnInit { */ protected async fetchSitePolicy(): Promise { try { - this.sitePolicy = await CoreLoginHelper.instance.getSitePolicy(this.siteId); + this.sitePolicy = await CoreLoginHelper.getSitePolicy(this.siteId); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting site policy.'); + CoreDomUtils.showErrorModalDefault(error, 'Error getting site policy.'); this.cancel(); return; @@ -82,9 +82,9 @@ export class CoreLoginSitePolicyPage implements OnInit { // Try to get the mime type. try { - const mimeType = await CoreUtils.instance.getMimeTypeFromUrl(this.sitePolicy); + const mimeType = await CoreUtils.getMimeTypeFromUrl(this.sitePolicy); - const extension = CoreMimetypeUtils.instance.getExtension(mimeType, this.sitePolicy); + const extension = CoreMimetypeUtils.getExtension(mimeType, this.sitePolicy); this.showInline = extension == 'html' || extension == 'htm'; } catch (error) { // Unable to get mime type, assume it's not supported. @@ -100,9 +100,9 @@ export class CoreLoginSitePolicyPage implements OnInit { * @return Promise resolved when done. */ async cancel(): Promise { - await CoreUtils.instance.ignoreErrors(CoreSites.instance.logout()); + await CoreUtils.ignoreErrors(CoreSites.logout()); - await CoreNavigator.instance.navigate('/login/sites', { reset: true }); + await CoreNavigator.navigate('/login/sites', { reset: true }); } /** @@ -111,18 +111,18 @@ export class CoreLoginSitePolicyPage implements OnInit { * @return Promise resolved when done. */ async accept(): Promise { - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); try { - await CoreLoginHelper.instance.acceptSitePolicy(this.siteId); + await CoreLoginHelper.acceptSitePolicy(this.siteId); // Success accepting, go to site initial page. // Invalidate cache since some WS don't return error if site policy is not accepted. - await CoreUtils.instance.ignoreErrors(this.currentSite!.invalidateWsCache()); + await CoreUtils.ignoreErrors(this.currentSite!.invalidateWsCache()); - await CoreNavigator.instance.navigateToSiteHome(); + await CoreNavigator.navigateToSiteHome(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error accepting site policy.'); + CoreDomUtils.showErrorModalDefault(error, 'Error accepting site policy.'); } finally { modal.dismiss(); } diff --git a/src/core/features/login/pages/site/site.ts b/src/core/features/login/pages/site/site.ts index f509eb178..3eaaf10d8 100644 --- a/src/core/features/login/pages/site/site.ts +++ b/src/core/features/login/pages/site/site.ts @@ -76,25 +76,25 @@ export class CoreLoginSitePage implements OnInit { }; // Load fixed sites if they're set. - if (CoreLoginHelper.instance.hasSeveralFixedSites()) { + if (CoreLoginHelper.hasSeveralFixedSites()) { url = this.initSiteSelector(); - } else if (CoreConstants.CONFIG.enableonboarding && !CoreApp.instance.isIOS()) { + } else if (CoreConstants.CONFIG.enableonboarding && !CoreApp.isIOS()) { this.initOnboarding(); } - this.showScanQR = CoreUtils.instance.canScanQR() && (typeof CoreConstants.CONFIG.displayqronsitescreen == 'undefined' || + this.showScanQR = CoreUtils.canScanQR() && (typeof CoreConstants.CONFIG.displayqronsitescreen == 'undefined' || !!CoreConstants.CONFIG.displayqronsitescreen); this.siteForm = this.formBuilder.group({ siteUrl: [url, this.moodleUrlValidator()], }); - this.searchFunction = CoreUtils.instance.debounce(async (search: string) => { + this.searchFunction = CoreUtils.debounce(async (search: string) => { search = search.trim(); if (search.length >= 3) { // Update the sites list. - const sites = await CoreSites.instance.findSites(search); + const sites = await CoreSites.findSites(search); // Add UI tweaks. this.sites = this.extendCoreLoginSiteInfo( sites); @@ -113,7 +113,7 @@ export class CoreLoginSitePage implements OnInit { * Initialize the component. */ ngOnInit(): void { - this.showKeyboard = !!CoreNavigator.instance.getRouteBooleanParam('showKeyboard'); + this.showKeyboard = !!CoreNavigator.getRouteBooleanParam('showKeyboard'); } /** @@ -128,7 +128,7 @@ export class CoreLoginSitePage implements OnInit { this.siteFinderSettings.displayurl = false; } - this.fixedSites = this.extendCoreLoginSiteInfo( CoreLoginHelper.instance.getFixedSites()); + this.fixedSites = this.extendCoreLoginSiteInfo( CoreLoginHelper.getFixedSites()); // Do not show images if none are set. if (!this.fixedSites.some((site) => !!site.imageurl)) { @@ -151,7 +151,7 @@ export class CoreLoginSitePage implements OnInit { * @return Promise resolved when done. */ protected async initOnboarding(): Promise { - const onboardingDone = await CoreConfig.instance.get(CoreLoginHelperProvider.ONBOARDING_DONE, false); + const onboardingDone = await CoreConfig.get(CoreLoginHelperProvider.ONBOARDING_DONE, false); if (!onboardingDone) { // Check onboarding. @@ -176,7 +176,7 @@ export class CoreLoginSitePage implements OnInit { site.title = name && alias ? name + ' (' + alias + ')' : name + alias; const country = this.siteFinderSettings.displaycountry && site.countrycode ? - CoreUtils.instance.getCountryName(site.countrycode) : ''; + CoreUtils.getCountryName(site.countrycode) : ''; const city = this.siteFinderSettings.displaycity && site.city ? site.city : ''; @@ -198,7 +198,7 @@ export class CoreLoginSitePage implements OnInit { let valid = value.length >= 3 && CoreUrl.isValidMoodleUrl(value); if (!valid) { - const demo = !!CoreSites.instance.getDemoSiteData(value); + const demo = !!CoreSites.getDemoSiteData(value); if (demo) { valid = true; @@ -213,7 +213,7 @@ export class CoreLoginSitePage implements OnInit { * Show a help modal. */ async showHelp(): Promise { - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: CoreLoginSiteHelpComponent, cssClass: 'core-modal-fullscreen', }); @@ -225,7 +225,7 @@ export class CoreLoginSitePage implements OnInit { * Show an onboarding modal. */ async showOnboarding(): Promise { - const modal = await ModalController.instance.create({ + const modal = await ModalController.create({ component: CoreLoginSiteOnboardingComponent, cssClass: 'core-modal-fullscreen', }); @@ -245,16 +245,16 @@ export class CoreLoginSitePage implements OnInit { e.preventDefault(); e.stopPropagation(); - CoreApp.instance.closeKeyboard(); + CoreApp.closeKeyboard(); if (!url) { - CoreDomUtils.instance.showErrorModal('core.login.siteurlrequired', true); + CoreDomUtils.showErrorModal('core.login.siteurlrequired', true); return; } - if (!CoreApp.instance.isOnline()) { - CoreDomUtils.instance.showErrorModal('core.networkerrormsg', true); + if (!CoreApp.isOnline()) { + CoreDomUtils.showErrorModal('core.networkerrormsg', true); return; } @@ -262,12 +262,12 @@ export class CoreLoginSitePage implements OnInit { url = url.trim(); if (url.match(/^(https?:\/\/)?campus\.example\.edu/)) { - this.showLoginIssue(null, new CoreError(Translate.instance.instant('core.login.errorexampleurl'))); + this.showLoginIssue(null, new CoreError(Translate.instant('core.login.errorexampleurl'))); return; } - const siteData = CoreSites.instance.getDemoSiteData(url); + const siteData = CoreSites.getDemoSiteData(url); if (siteData) { // It's a demo site. @@ -275,19 +275,19 @@ export class CoreLoginSitePage implements OnInit { } else { // Not a demo site. - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); let checkResult: CoreSiteCheckResponse; try { - checkResult = await CoreSites.instance.checkSite(url); + checkResult = await CoreSites.checkSite(url); } catch (error) { // Attempt guessing the domain if the initial check failed const domain = CoreUrl.guessMoodleDomain(url); if (domain && domain != url) { try { - checkResult = await CoreSites.instance.checkSite(domain); + checkResult = await CoreSites.checkSite(domain); } catch (secondError) { // Try to use the first error. modal.dismiss(); @@ -314,23 +314,23 @@ export class CoreLoginSitePage implements OnInit { * @return Promise resolved when done. */ protected async loginDemoSite(siteData: CoreSitesDemoSiteData): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { - const data = await CoreSites.instance.getUserToken(siteData.url, siteData.username, siteData.password); + const data = await CoreSites.getUserToken(siteData.url, siteData.username, siteData.password); - await CoreSites.instance.newSite(data.siteUrl, data.token, data.privateToken); + await CoreSites.newSite(data.siteUrl, data.token, data.privateToken); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, true); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, true); - await CoreNavigator.instance.navigateToSiteHome(); + await CoreNavigator.navigateToSiteHome(); return; } catch (error) { - CoreLoginHelper.instance.treatUserTokenError(siteData.url, error, siteData.username, siteData.password); + CoreLoginHelper.treatUserTokenError(siteData.url, error, siteData.username, siteData.password); if (error.loggedout) { - CoreNavigator.instance.navigate('/login/sites', { reset: true }); + CoreNavigator.navigate('/login/sites', { reset: true }); } } finally { modal.dismiss(); @@ -346,17 +346,17 @@ export class CoreLoginSitePage implements OnInit { * @return Promise resolved after logging in. */ protected async login(response: CoreSiteCheckResponse, foundSite?: CoreLoginSiteInfoExtended): Promise { - await CoreUtils.instance.ignoreErrors(CoreSites.instance.checkApplication(response)); + await CoreUtils.ignoreErrors(CoreSites.checkApplication(response)); - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, true); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, true); if (response.warning) { - CoreDomUtils.instance.showErrorModal(response.warning, true, 4000); + CoreDomUtils.showErrorModal(response.warning, true, 4000); } - if (CoreLoginHelper.instance.isSSOLoginNeeded(response.code)) { + if (CoreLoginHelper.isSSOLoginNeeded(response.code)) { // SSO. User needs to authenticate in a browser. - CoreLoginHelper.instance.confirmAndOpenBrowserForSSOLogin( + CoreLoginHelper.confirmAndOpenBrowserForSSOLogin( response.siteUrl, response.code, response.service, @@ -369,7 +369,7 @@ export class CoreLoginSitePage implements OnInit { pageParams['logoUrl'] = foundSite.imageurl; } - CoreNavigator.instance.navigate('/login/credentials', { + CoreNavigator.navigate('/login/credentials', { params: pageParams, }); } @@ -382,38 +382,38 @@ export class CoreLoginSitePage implements OnInit { * @param error Error to display. */ protected showLoginIssue(url: string | null, error: CoreError): void { - let errorMessage = CoreDomUtils.instance.getErrorMessage(error); + let errorMessage = CoreDomUtils.getErrorMessage(error); - if (errorMessage == Translate.instance.instant('core.cannotconnecttrouble')) { + if (errorMessage == Translate.instant('core.cannotconnecttrouble')) { const found = this.sites.find((site) => site.url == url); if (!found) { - errorMessage += ' ' + Translate.instance.instant('core.cannotconnectverify'); + errorMessage += ' ' + Translate.instant('core.cannotconnectverify'); } } let message = '

' + errorMessage + '

'; if (url) { - const fullUrl = CoreUrlUtils.instance.isAbsoluteURL(url) ? url : 'https://' + url; + const fullUrl = CoreUrlUtils.isAbsoluteURL(url) ? url : 'https://' + url; message += '

' + url + '

'; } const buttons = [ { - text: Translate.instance.instant('core.needhelp'), + text: Translate.instant('core.needhelp'), handler: (): void => { this.showHelp(); }, }, { - text: Translate.instance.instant('core.tryagain'), + text: Translate.instant('core.tryagain'), role: 'cancel', }, ]; // @TODO: Remove CoreSite.MINIMUM_MOODLE_VERSION, not used on translations since 3.9.0. - CoreDomUtils.instance.showAlertWithOptions({ - header: Translate.instance.instant('core.cannotconnect', { $a: CoreSite.MINIMUM_MOODLE_VERSION }), + CoreDomUtils.showAlertWithOptions({ + header: Translate.instant('core.cannotconnect', { $a: CoreSite.MINIMUM_MOODLE_VERSION }), message, buttons, }); @@ -467,19 +467,19 @@ export class CoreLoginSitePage implements OnInit { */ showInstructionsAndScanQR(): void { // Show some instructions first. - CoreDomUtils.instance.showAlertWithOptions({ - header: Translate.instance.instant('core.login.faqwhereisqrcode'), - message: Translate.instance.instant( + CoreDomUtils.showAlertWithOptions({ + header: Translate.instant('core.login.faqwhereisqrcode'), + message: Translate.instant( 'core.login.faqwhereisqrcodeanswer', { $image: CoreLoginHelperProvider.FAQ_QRCODE_IMAGE_HTML }, ), buttons: [ { - text: Translate.instance.instant('core.cancel'), + text: Translate.instant('core.cancel'), role: 'cancel', }, { - text: Translate.instance.instant('core.next'), + text: Translate.instant('core.next'), handler: (): void => { this.scanQR(); }, @@ -495,7 +495,7 @@ export class CoreLoginSitePage implements OnInit { */ async scanQR(): Promise { // Scan for a QR code. - const text = await CoreUtils.instance.scanQR(); + const text = await CoreUtils.scanQR(); if (text) { // @todo diff --git a/src/core/features/login/pages/sites/sites.ts b/src/core/features/login/pages/sites/sites.ts index a85c16a7f..3bf3222c7 100644 --- a/src/core/features/login/pages/sites/sites.ts +++ b/src/core/features/login/pages/sites/sites.ts @@ -45,7 +45,7 @@ export class CoreLoginSitesPage implements OnInit { * @return Promise resolved when done. */ async ngOnInit(): Promise { - const sites = await CoreUtils.instance.ignoreErrors(CoreSites.instance.getSortedSites(), [] as CoreSiteBasicInfo[]); + const sites = await CoreUtils.ignoreErrors(CoreSites.getSortedSites(), [] as CoreSiteBasicInfo[]); // Remove protocol from the url to show more url text. this.sites = sites.map((site) => { @@ -63,7 +63,7 @@ export class CoreLoginSitesPage implements OnInit { * Go to the page to add a site. */ add(): void { - CoreLoginHelper.instance.goToAddSite(false, true); + CoreLoginHelper.goToAddSite(false, true); } /** @@ -81,28 +81,28 @@ export class CoreLoginSitesPage implements OnInit { // @todo: Format text: siteName. try { - await CoreDomUtils.instance.showDeleteConfirm('core.login.confirmdeletesite', { sitename: siteName }); + await CoreDomUtils.showDeleteConfirm('core.login.confirmdeletesite', { sitename: siteName }); } catch (error) { // User cancelled, stop. return; } try { - await CoreSites.instance.deleteSite(site.id); + await CoreSites.deleteSite(site.id); const index = this.sites.findIndex((listedSite) => listedSite.id == site.id); index >= 0 && this.sites.splice(index, 1); this.showDelete = false; // If there are no sites left, go to add site. - const hasSites = await CoreSites.instance.hasSites(); + const hasSites = await CoreSites.hasSites(); if (!hasSites) { - CoreLoginHelper.instance.goToAddSite(true, true); + CoreLoginHelper.goToAddSite(true, true); } } catch (error) { this.logger.error('Error deleting site ' + site.id, error); - CoreDomUtils.instance.showErrorModalDefault(error, 'core.login.errordeletesite', true); + CoreDomUtils.showErrorModalDefault(error, 'core.login.errordeletesite', true); } } @@ -113,19 +113,19 @@ export class CoreLoginSitesPage implements OnInit { * @return Promise resolved when done. */ async login(siteId: string): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { - const loggedIn = await CoreSites.instance.loadSite(siteId); + const loggedIn = await CoreSites.loadSite(siteId); if (loggedIn) { - await CoreNavigator.instance.navigateToSiteHome(); + await CoreNavigator.navigateToSiteHome(); return; } } catch (error) { this.logger.error('Error loading site ' + siteId, error); - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading site.'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading site.'); } finally { modal.dismiss(); } diff --git a/src/core/features/login/services/login-helper.ts b/src/core/features/login/services/login-helper.ts index 0004cb0ac..24822d37b 100644 --- a/src/core/features/login/services/login-helper.ts +++ b/src/core/features/login/services/login-helper.ts @@ -67,7 +67,7 @@ export class CoreLoginHelperProvider { * @return Promise resolved if success, rejected if failure. */ async acceptSitePolicy(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const result = await site.write('core_user_agree_site_policy', {}); @@ -111,15 +111,15 @@ export class CoreLoginHelperProvider { * Function called when an SSO InAppBrowser is closed or the app is resumed. Check if user needs to be logged out. */ checkLogout(): void { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); if ( - !CoreApp.instance.isSSOAuthenticationOngoing() && + !CoreApp.isSSOAuthenticationOngoing() && currentSite?.isLoggedOut() && - CoreNavigator.instance.isCurrent('/login/reconnect') + CoreNavigator.isCurrent('/login/reconnect') ) { // User must reauthenticate but he closed the InAppBrowser without doing so, logout him. - CoreSites.instance.logout(); + CoreSites.logout(); } } @@ -143,7 +143,7 @@ export class CoreLoginHelperProvider { if (showConfirmation) { try { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.login.logininsiterequired')); + await CoreDomUtils.showConfirm(Translate.instant('core.login.logininsiterequired')); } catch (error) { // User canceled, stop. return; @@ -163,19 +163,19 @@ export class CoreLoginHelperProvider { async forgottenPasswordClicked(siteUrl: string, username: string, siteConfig?: CoreSitePublicConfigResponse): Promise { if (siteConfig && siteConfig.forgottenpasswordurl) { // URL set, open it. - CoreUtils.instance.openInApp(siteConfig.forgottenpasswordurl); + CoreUtils.openInApp(siteConfig.forgottenpasswordurl); return; } // Check if password reset can be done through the app. - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); try { const canReset = await this.canRequestPasswordReset(siteUrl); if (canReset) { - await CoreNavigator.instance.navigate('/login/forgottenpassword', { + await CoreNavigator.navigate('/login/forgottenpassword', { params: { siteUrl, username, @@ -234,7 +234,7 @@ export class CoreLoginHelperProvider { return ''; } - return CoreTextUtils.instance.treatDisabledFeatures(disabledFeatures); + return CoreTextUtils.treatDisabledFeatures(disabledFeatures); } /** @@ -264,28 +264,28 @@ export class CoreLoginHelperProvider { const errors: Record = {}; if (requiredMsg) { - errors.required = errors.requiredTrue = Translate.instance.instant(requiredMsg); + errors.required = errors.requiredTrue = Translate.instant(requiredMsg); } if (emailMsg) { - errors.email = Translate.instance.instant(emailMsg); + errors.email = Translate.instant(emailMsg); } if (patternMsg) { - errors.pattern = Translate.instance.instant(patternMsg); + errors.pattern = Translate.instant(patternMsg); } if (urlMsg) { - errors.url = Translate.instance.instant(urlMsg); + errors.url = Translate.instant(urlMsg); } if (minlengthMsg) { - errors.minlength = Translate.instance.instant(minlengthMsg); + errors.minlength = Translate.instant(minlengthMsg); } if (maxlengthMsg) { - errors.maxlength = Translate.instance.instant(maxlengthMsg); + errors.maxlength = Translate.instant(maxlengthMsg); } if (minMsg) { - errors.min = Translate.instance.instant(minMsg); + errors.min = Translate.instant(minMsg); } if (maxMsg) { - errors.max = Translate.instance.instant(maxMsg); + errors.max = Translate.instant(maxMsg); } return errors; @@ -308,7 +308,7 @@ export class CoreLoginHelperProvider { * @return The string key. */ getLogoutLabel(site?: CoreSite): string { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); const config = site?.getStoredConfig(); return 'core.mainmenu.' + (config && config.tool_mobile_forcelogout == '1' ? 'logout' : 'changesite'); @@ -331,7 +331,7 @@ export class CoreLoginHelperProvider { * @return Promise resolved with the site policy. */ async getSitePolicy(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); let sitePolicy: string | undefined; @@ -340,7 +340,7 @@ export class CoreLoginHelperProvider { sitePolicy = await site.getConfig('sitepolicy', true); } catch (error) { // Cannot get config, try to get the site policy using auth_email_get_signup_settings. - const settings = await CoreWS.instance.callAjax( + const settings = await CoreWS.callAjax( 'auth_email_get_signup_settings', {}, { siteUrl: site.getURL() }, @@ -382,12 +382,12 @@ export class CoreLoginHelperProvider { } const validProviders: CoreSiteIdentityProvider[] = []; - const httpUrl = CoreTextUtils.instance.concatenatePaths(siteConfig.wwwroot, 'auth/oauth2/'); - const httpsUrl = CoreTextUtils.instance.concatenatePaths(siteConfig.httpswwwroot, 'auth/oauth2/'); + const httpUrl = CoreTextUtils.concatenatePaths(siteConfig.wwwroot, 'auth/oauth2/'); + const httpsUrl = CoreTextUtils.concatenatePaths(siteConfig.httpswwwroot, 'auth/oauth2/'); if (siteConfig.identityproviders && siteConfig.identityproviders.length) { siteConfig.identityproviders.forEach((provider) => { - const urlParams = CoreUrlUtils.instance.extractUrlParams(provider.url); + const urlParams = CoreUrlUtils.extractUrlParams(provider.url); if (provider.url && (provider.url.indexOf(httpsUrl) != -1 || provider.url.indexOf(httpUrl) != -1) && !this.isFeatureDisabled('NoDelegate_IdentityProvider_' + urlParams.id, siteConfig, disabledFeatures)) { @@ -410,7 +410,7 @@ export class CoreLoginHelperProvider { async goToAddSite(setRoot?: boolean, showKeyboard?: boolean): Promise { const [path, params] = this.getAddSiteRouteInfo(showKeyboard); - await CoreNavigator.instance.navigate(path, { params, reset: setRoot }); + await CoreNavigator.navigate(path, { params, reset: setRoot }); } /** @@ -440,7 +440,7 @@ export class CoreLoginHelperProvider { * @deprecated since 3.9.5. Use CoreNavigator.navigateToLoginCredentials instead. */ async goToNoSitePage(page: string, params?: Params): Promise { - await CoreNavigator.instance.navigateToLoginCredentials(params); + await CoreNavigator.navigateToLoginCredentials(params); } /** @@ -456,7 +456,7 @@ export class CoreLoginHelperProvider { */ // eslint-disable-next-line @typescript-eslint/no-explicit-any async goToSiteInitialPage(navCtrlUnused?: unknown, page?: string, params?: any, options?: any, url?: string): Promise { - await CoreNavigator.instance.navigateToSiteHome({ + await CoreNavigator.navigateToSiteHome({ ...options, params: { redirectPath: page, @@ -478,7 +478,7 @@ export class CoreLoginHelperProvider { */ handleSSOLoginAuthentication(siteUrl: string, token: string, privateToken?: string, oauthId?: number): Promise { // Always create a new site to prevent overriding data if another user credentials were introduced. - return CoreSites.instance.newSite(siteUrl, token, privateToken, true, oauthId); + return CoreSites.newSite(siteUrl, token, privateToken, true, oauthId); } /** @@ -552,7 +552,7 @@ export class CoreLoginHelperProvider { * @return True if user is logged out, false otherwise. */ isSiteLoggedOut(pageName?: string, params?: Params): boolean { - const site = CoreSites.instance.getCurrentSite(); + const site = CoreSites.getCurrentSite(); if (!site) { return false; } @@ -585,7 +585,7 @@ export class CoreLoginHelperProvider { return sites.some((site) => CoreUrl.sameDomainAndPath(siteUrl, site.url)); } else if (CoreConstants.CONFIG.multisitesdisplay == 'sitefinder' && CoreConstants.CONFIG.onlyallowlistedsites) { // Call the sites finder to validate the site. - const result = await CoreSites.instance.findSites(siteUrl.replace(/^https?:\/\/|\.\w{2,3}\/?$/g, '')); + const result = await CoreSites.findSites(siteUrl.replace(/^https?:\/\/|\.\w{2,3}\/?$/g, '')); return result && result.some((site) => CoreUrl.sameDomainAndPath(siteUrl, site.url)); } else { @@ -622,7 +622,7 @@ export class CoreLoginHelperProvider { * @deprecated since 3.9.5. Use CoreNavigator.navigateToSitepath instead. */ loadPageInMainMenu(page: string, params?: Params): void { - CoreNavigator.instance.navigateToSitePath(page, { params }); + CoreNavigator.navigateToSitePath(page, { params }); } /** @@ -647,19 +647,19 @@ export class CoreLoginHelperProvider { return false; } - const params = CoreUrlUtils.instance.extractUrlParams(provider.url); + const params = CoreUrlUtils.extractUrlParams(provider.url); if (!params.id) { return false; } - const service = CoreSites.instance.determineService(siteUrl); + const service = CoreSites.determineService(siteUrl); const loginUrl = this.prepareForSSOLogin(siteUrl, service, launchUrl, pageName, pageParams, { oauthsso: params.id, }); // Always open it in browser because the user might have the session stored in there. - CoreUtils.instance.openInBrowser(loginUrl); + CoreUtils.openInBrowser(loginUrl); const nav = window.navigator; // eslint-disable-line @typescript-eslint/no-explicit-any nav.app?.exitApp(); @@ -688,12 +688,12 @@ export class CoreLoginHelperProvider { const loginUrl = this.prepareForSSOLogin(siteUrl, service, launchUrl, pageName, pageParams); if (this.isSSOEmbeddedBrowser(typeOfLogin)) { - CoreUtils.instance.openInApp(loginUrl, { + CoreUtils.openInApp(loginUrl, { clearsessioncache: 'yes', // Clear the session cache to allow for multiple logins. - closebuttoncaption: Translate.instance.instant('core.login.cancel'), + closebuttoncaption: Translate.instant('core.login.cancel'), }); } else { - CoreUtils.instance.openInBrowser(loginUrl); + CoreUtils.openInBrowser(loginUrl); const nav = window.navigator; // eslint-disable-line @typescript-eslint/no-explicit-any nav.app?.exitApp(); @@ -708,11 +708,11 @@ export class CoreLoginHelperProvider { * @return Promise resolved when done. */ async openChangePassword(siteUrl: string, error: string): Promise { - const alert = await CoreDomUtils.instance.showAlert(Translate.instance.instant('core.notice'), error, undefined, 3000); + const alert = await CoreDomUtils.showAlert(Translate.instant('core.notice'), error, undefined, 3000); await alert.onDidDismiss(); - CoreUtils.instance.openInApp(siteUrl + '/login/change_password.php'); + CoreUtils.openInApp(siteUrl + '/login/change_password.php'); } /** @@ -721,7 +721,7 @@ export class CoreLoginHelperProvider { * @param siteUrl URL of the site. */ openForgottenPassword(siteUrl: string): void { - CoreUtils.instance.openInApp(siteUrl + '/login/forgot_password.php'); + CoreUtils.openInApp(siteUrl + '/login/forgot_password.php'); } /** @@ -734,12 +734,12 @@ export class CoreLoginHelperProvider { * @return Promise resolved when done. */ async openInAppForEdit(siteId: string, path: string, alertMessage?: string, invalidateCache?: boolean): Promise { - if (!siteId || siteId !== CoreSites.instance.getCurrentSiteId()) { + if (!siteId || siteId !== CoreSites.getCurrentSiteId()) { // Site that triggered the event is not current site, nothing to do. return; } - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); const siteUrl = currentSite?.getURL(); if (!currentSite || !siteUrl) { @@ -755,8 +755,8 @@ export class CoreLoginHelperProvider { // Open change password. if (alertMessage) { - alertMessage = Translate.instance.instant(alertMessage) + '
' + - Translate.instance.instant('core.redirectingtosite'); + alertMessage = Translate.instant(alertMessage) + '
' + + Translate.instant('core.redirectingtosite'); } try { @@ -775,17 +775,17 @@ export class CoreLoginHelperProvider { * @param siteId The site ID. */ async passwordChangeForced(siteId: string): Promise { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); if (!currentSite || siteId !== currentSite.getId()) { return; // Site that triggered the event is not current site. } // If current page is already change password, stop. - if (CoreNavigator.instance.isCurrent('/login/changepassword')) { + if (CoreNavigator.isCurrent('/login/changepassword')) { return; } - await CoreNavigator.instance.navigate('/login/changepassword', { params: { siteId }, reset: true }); + await CoreNavigator.navigate('/login/changepassword', { params: { siteId }, reset: true }); } /** @@ -818,12 +818,12 @@ export class CoreLoginHelperProvider { loginUrl += '&urlscheme=' + CoreConstants.CONFIG.customurlscheme; if (urlParams) { - loginUrl = CoreUrlUtils.instance.addParamsToUrl(loginUrl, urlParams); + loginUrl = CoreUrlUtils.addParamsToUrl(loginUrl, urlParams); } // Store the siteurl and passport in CoreConfigProvider for persistence. // We are "configuring" the app to wait for an SSO. CoreConfigProvider shouldn't be used as a temporary storage. - CoreConfig.instance.set(CoreConstants.LOGIN_LAUNCH_DATA, JSON.stringify( { + CoreConfig.set(CoreConstants.LOGIN_LAUNCH_DATA, JSON.stringify( { siteUrl: siteUrl, passport: passport, pageName: pageName || '', @@ -844,7 +844,7 @@ export class CoreLoginHelperProvider { * @deprecated since 3.9.5. Use CoreNavigator.navigateToSitePath instead. */ async redirect(page: string, params?: Params, siteId?: string): Promise { - await CoreNavigator.instance.navigateToSitePath(page, { params, siteId }); + await CoreNavigator.navigateToSitePath(page, { params, siteId }); } /** @@ -866,7 +866,7 @@ export class CoreLoginHelperProvider { params.email = email; } - return CoreWS.instance.callAjax('core_auth_request_password_reset', params, { siteUrl }); + return CoreWS.callAjax('core_auth_request_password_reset', params, { siteUrl }); } /** @@ -877,7 +877,7 @@ export class CoreLoginHelperProvider { */ async sessionExpired(data: CoreEventSessionExpiredData): Promise { const siteId = data?.siteId; - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); const siteUrl = currentSite?.getURL(); if (!currentSite || !siteUrl) { @@ -890,19 +890,19 @@ export class CoreLoginHelperProvider { try { // Check authentication method. - const result = await CoreSites.instance.checkSite(siteUrl); + const result = await CoreSites.checkSite(siteUrl); if (result.warning) { - CoreDomUtils.instance.showErrorModal(result.warning, true, 4000); + CoreDomUtils.showErrorModal(result.warning, true, 4000); } if (this.isSSOLoginNeeded(result.code)) { // SSO. User needs to authenticate in a browser. Check if we need to display a message. - if (!CoreApp.instance.isSSOAuthenticationOngoing() && !this.isSSOConfirmShown && !this.waitingForBrowser) { + if (!CoreApp.isSSOAuthenticationOngoing() && !this.isSSOConfirmShown && !this.waitingForBrowser) { this.isSSOConfirmShown = true; if (this.shouldShowSSOConfirm(result.code)) { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.login.' + + await CoreDomUtils.showConfirm(Translate.instant('core.login.' + (currentSite.isLoggedOut() ? 'loggedoutssodescription' : 'reconnectssodescription'))); } @@ -919,7 +919,7 @@ export class CoreLoginHelperProvider { ); } catch (error) { // User cancelled, logout him. - CoreSites.instance.logout(); + CoreSites.logout(); } finally { this.isSSOConfirmShown = false; } @@ -929,24 +929,24 @@ export class CoreLoginHelperProvider { // User authenticated using an OAuth method. Check if it's still valid. const identityProviders = this.getValidIdentityProviders(result.config); const providerToUse = identityProviders.find((provider) => { - const params = CoreUrlUtils.instance.extractUrlParams(provider.url); + const params = CoreUrlUtils.extractUrlParams(provider.url); return Number(params.id) == currentSite.getOAuthId(); }); if (providerToUse) { - if (!CoreApp.instance.isSSOAuthenticationOngoing() && !this.isSSOConfirmShown && !this.waitingForBrowser) { + if (!CoreApp.isSSOAuthenticationOngoing() && !this.isSSOConfirmShown && !this.waitingForBrowser) { // Open browser to perform the OAuth. this.isSSOConfirmShown = true; - const confirmMessage = Translate.instance.instant('core.login.' + + const confirmMessage = Translate.instant('core.login.' + (currentSite.isLoggedOut() ? 'loggedoutssodescription' : 'reconnectssodescription')); try { - await CoreDomUtils.instance.showConfirm(confirmMessage); + await CoreDomUtils.showConfirm(confirmMessage); this.waitingForBrowser = true; - CoreSites.instance.unsetCurrentSite(); // Unset current site to make authentication work fine. + CoreSites.unsetCurrentSite(); // Unset current site to make authentication work fine. this.openBrowserForOAuthLogin( siteUrl, @@ -957,7 +957,7 @@ export class CoreLoginHelperProvider { ); } catch (error) { // User cancelled, logout him. - CoreSites.instance.logout(); + CoreSites.logout(); } finally { this.isSSOConfirmShown = false; } @@ -970,13 +970,13 @@ export class CoreLoginHelperProvider { const info = currentSite.getInfo(); if (typeof info != 'undefined' && typeof info.username != 'undefined' && !this.isOpeningReconnect) { // If current page is already reconnect, stop. - if (CoreNavigator.instance.isCurrent('/login/reconnect')) { + if (CoreNavigator.isCurrent('/login/reconnect')) { return; } this.isOpeningReconnect = true; - await CoreUtils.instance.ignoreErrors(CoreNavigator.instance.navigate('/login/reconnect', { + await CoreUtils.ignoreErrors(CoreNavigator.navigate('/login/reconnect', { params: { siteId, pageName: data.pageName, @@ -992,8 +992,8 @@ export class CoreLoginHelperProvider { // Error checking site. if (currentSite.isLoggedOut()) { // Site is logged out, show error and logout the user. - CoreDomUtils.instance.showErrorModalDefault(error, 'core.networkerrormsg', true); - CoreSites.instance.logout(); + CoreDomUtils.showErrorModalDefault(error, 'core.networkerrormsg', true); + CoreSites.logout(); } } } @@ -1015,9 +1015,9 @@ export class CoreLoginHelperProvider { * @param message The warning message. */ protected showWorkplaceNoticeModal(message: string): void { - const link = CoreApp.instance.getAppStoreUrl({ android: 'com.moodle.workplace', ios: 'id1470929705' }); + const link = CoreApp.getAppStoreUrl({ android: 'com.moodle.workplace', ios: 'id1470929705' }); - CoreDomUtils.instance.showDownloadAppNoticeModal(message, link); + CoreDomUtils.showDownloadAppNoticeModal(message, link); } /** @@ -1030,9 +1030,9 @@ export class CoreLoginHelperProvider { storesConfig.mobile = 'https://download.moodle.org/mobile/'; storesConfig.default = 'https://download.moodle.org/mobile/'; - const link = CoreApp.instance.getAppStoreUrl(storesConfig); + const link = CoreApp.getAppStoreUrl(storesConfig); - CoreDomUtils.instance.showDownloadAppNoticeModal(message, link); + CoreDomUtils.showDownloadAppNoticeModal(message, link); } /** @@ -1044,13 +1044,13 @@ export class CoreLoginHelperProvider { * @param password User password. If not set the button to resend email will not be shown. */ protected async showNotConfirmedModal(siteUrl: string, email?: string, username?: string, password?: string): Promise { - const title = Translate.instance.instant('core.login.mustconfirm'); + const title = Translate.instant('core.login.mustconfirm'); let message: string; let canResend = false; if (email) { - message = Translate.instance.instant('core.login.emailconfirmsent', { $a: email }); + message = Translate.instant('core.login.emailconfirmsent', { $a: email }); } else { - message = Translate.instance.instant('core.login.emailconfirmsentnoemail'); + message = Translate.instant('core.login.emailconfirmsentnoemail'); } // Check whether we need to display the resend button or not. @@ -1060,25 +1060,25 @@ export class CoreLoginHelperProvider { if (!canResend) { // Just display an informative alert. - await CoreDomUtils.instance.showAlert(title, message); + await CoreDomUtils.showAlert(title, message); return; } - const okText = Translate.instance.instant('core.login.resendemail'); - const cancelText = Translate.instance.instant('core.close'); + const okText = Translate.instant('core.login.resendemail'); + const cancelText = Translate.instant('core.close'); try { // Ask the user if he wants to resend the email. - await CoreDomUtils.instance.showConfirm(message, title, okText, cancelText); + await CoreDomUtils.showConfirm(message, title, okText, cancelText); // Call the WS to resend the confirmation email. - const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + const modal = await CoreDomUtils.showModalLoading('core.sending', true); const data = { username, password }; const preSets = { siteUrl }; try { - const result = await CoreWS.instance.callAjax( + const result = await CoreWS.callAjax( 'core_auth_resend_confirmation_email', data, preSets, @@ -1088,13 +1088,13 @@ export class CoreLoginHelperProvider { throw new CoreWSError(result.warnings?.[0]); } - const message = Translate.instance.instant('core.login.emailconfirmsentsuccess'); - CoreDomUtils.instance.showAlert(Translate.instance.instant('core.success'), message); + const message = Translate.instant('core.login.emailconfirmsentsuccess'); + CoreDomUtils.showAlert(Translate.instant('core.success'), message); } finally { modal.dismiss(); } } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } } @@ -1105,12 +1105,12 @@ export class CoreLoginHelperProvider { * @return Promise. */ protected async canResendEmail(siteUrl: string): Promise { - const modal = await CoreDomUtils.instance.showModalLoading(); + const modal = await CoreDomUtils.showModalLoading(); // We don't have site info before login, the only way to check if the WS is available is by calling it. try { // This call will always fail because we aren't sending parameters. - await CoreWS.instance.callAjax('core_auth_resend_confirmation_email', {}, { siteUrl }); + await CoreWS.callAjax('core_auth_resend_confirmation_email', {}, { siteUrl }); return true; // We should never reach here. } catch (error) { @@ -1127,23 +1127,23 @@ export class CoreLoginHelperProvider { * @param siteId Site ID. If not defined, current site. */ sitePolicyNotAgreed(siteId?: string): void { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); - if (!siteId || siteId != CoreSites.instance.getCurrentSiteId()) { + siteId = siteId || CoreSites.getCurrentSiteId(); + if (!siteId || siteId != CoreSites.getCurrentSiteId()) { // Only current site allowed. return; } - if (!CoreSites.instance.wsAvailableInCurrentSite('core_user_agree_site_policy')) { + if (!CoreSites.wsAvailableInCurrentSite('core_user_agree_site_policy')) { // WS not available, stop. return; } // If current page is already site policy, stop. - if (CoreNavigator.instance.isCurrent('/login/sitepolicy')) { + if (CoreNavigator.isCurrent('/login/sitepolicy')) { return; } - CoreNavigator.instance.navigate('/login/sitepolicy', { params: { siteId }, reset: true }); + CoreNavigator.navigate('/login/sitepolicy', { params: { siteId }, reset: true }); } /** @@ -1156,15 +1156,15 @@ export class CoreLoginHelperProvider { */ treatUserTokenError(siteUrl: string, error: CoreWSError, username?: string, password?: string): void { if (error.errorcode == 'forcepasswordchangenotice') { - this.openChangePassword(siteUrl, CoreTextUtils.instance.getErrorMessageFromError(error)!); + this.openChangePassword(siteUrl, CoreTextUtils.getErrorMessageFromError(error)!); } else if (error.errorcode == 'usernotconfirmed') { this.showNotConfirmedModal(siteUrl, undefined, username, password); } else if (error.errorcode == 'connecttomoodleapp') { - this.showMoodleAppNoticeModal(CoreTextUtils.instance.getErrorMessageFromError(error)!); + this.showMoodleAppNoticeModal(CoreTextUtils.getErrorMessageFromError(error)!); } else if (error.errorcode == 'connecttoworkplaceapp') { - this.showWorkplaceNoticeModal(CoreTextUtils.instance.getErrorMessageFromError(error)!); + this.showWorkplaceNoticeModal(CoreTextUtils.getErrorMessageFromError(error)!); } else { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } } @@ -1178,9 +1178,9 @@ export class CoreLoginHelperProvider { // Split signature:::token const params = url.split(':::'); - const serializedData = await CoreConfig.instance.get(CoreConstants.LOGIN_LAUNCH_DATA); + const serializedData = await CoreConfig.get(CoreConstants.LOGIN_LAUNCH_DATA); - const data = CoreTextUtils.instance.parseJSON(serializedData, null); + const data = CoreTextUtils.parseJSON(serializedData, null); if (data === null) { throw new CoreError('No launch data stored.'); } @@ -1189,7 +1189,7 @@ export class CoreLoginHelperProvider { let launchSiteURL = data.siteUrl; // Reset temporary values. - CoreConfig.instance.delete(CoreConstants.LOGIN_LAUNCH_DATA); + CoreConfig.delete(CoreConstants.LOGIN_LAUNCH_DATA); // Validate the signature. // We need to check both http and https. @@ -1218,13 +1218,13 @@ export class CoreLoginHelperProvider { this.logger.debug('Invalid signature in the URL request yours: ' + params[0] + ' mine: ' + signature + ' for passport ' + passport); - throw new CoreError(Translate.instance.instant('core.unexpectederror')); + throw new CoreError(Translate.instant('core.unexpectederror')); } } } -export class CoreLoginHelper extends makeSingleton(CoreLoginHelperProvider) {} +export const CoreLoginHelper = makeSingleton(CoreLoginHelperProvider); /** * Data related to a SSO authentication. diff --git a/src/core/features/mainmenu/guards/auth.ts b/src/core/features/mainmenu/guards/auth.ts index 5da99c25d..9ccedd13a 100644 --- a/src/core/features/mainmenu/guards/auth.ts +++ b/src/core/features/mainmenu/guards/auth.ts @@ -40,14 +40,14 @@ export class CoreMainMenuAuthGuard implements CanLoad, CanActivate { * Check if the current user should be redirected to the authentication page. */ private async guard(): Promise { - if (!CoreSites.instance.isLoggedIn()) { - return Router.instance.parseUrl('/login'); + if (!CoreSites.isLoggedIn()) { + return Router.parseUrl('/login'); } - if (CoreLoginHelper.instance.isSiteLoggedOut()) { - await CoreSites.instance.logout(); + if (CoreLoginHelper.isSiteLoggedOut()) { + await CoreSites.logout(); - return Router.instance.parseUrl('/login'); + return Router.parseUrl('/login'); } return true; diff --git a/src/core/features/mainmenu/mainmenu.module.ts b/src/core/features/mainmenu/mainmenu.module.ts index 2cfa7f26f..a6d3b9cf8 100644 --- a/src/core/features/mainmenu/mainmenu.module.ts +++ b/src/core/features/mainmenu/mainmenu.module.ts @@ -43,7 +43,7 @@ const appRoutes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreMainMenuDelegate.instance.registerHandler(CoreMainMenuHomeHandler.instance); + CoreMainMenuDelegate.registerHandler(CoreMainMenuHomeHandler.instance); }, }, ], diff --git a/src/core/features/mainmenu/pages/home/home.ts b/src/core/features/mainmenu/pages/home/home.ts index 1acc0bc13..bca1ae6e4 100644 --- a/src/core/features/mainmenu/pages/home/home.ts +++ b/src/core/features/mainmenu/pages/home/home.ts @@ -46,14 +46,14 @@ export class CoreMainMenuHomePage implements OnInit { ngOnInit(): void { this.loadSiteName(); - this.subscription = CoreMainMenuHomeDelegate.instance.getHandlersObservable().subscribe((handlers) => { + this.subscription = CoreMainMenuHomeDelegate.getHandlersObservable().subscribe((handlers) => { handlers && this.initHandlers(handlers); }); // Refresh the enabled flags if site is updated. this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { this.loadSiteName(); - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); } /** @@ -89,14 +89,14 @@ export class CoreMainMenuHomePage implements OnInit { this.tabs = newTabs; - this.loaded = CoreMainMenuHomeDelegate.instance.areHandlersLoaded(); + this.loaded = CoreMainMenuHomeDelegate.areHandlersLoaded(); } /** * Load the site name. */ protected loadSiteName(): void { - this.siteName = CoreSites.instance.getCurrentSite()!.getSiteName(); + this.siteName = CoreSites.getCurrentSite()!.getSiteName(); } /** diff --git a/src/core/features/mainmenu/pages/menu/menu.ts b/src/core/features/mainmenu/pages/menu/menu.ts index 66a48045f..7dfca5ad7 100644 --- a/src/core/features/mainmenu/pages/menu/menu.ts +++ b/src/core/features/mainmenu/pages/menu/menu.ts @@ -64,8 +64,8 @@ export class CoreMainMenuPage implements OnInit, OnDestroy { */ ngOnInit(): void { // @TODO this should be handled by route guards and can be removed - if (!CoreSites.instance.isLoggedIn()) { - CoreNavigator.instance.navigate('/login/init', { reset: true }); + if (!CoreSites.isLoggedIn()) { + CoreNavigator.navigate('/login/init', { reset: true }); return; } @@ -83,7 +83,7 @@ export class CoreMainMenuPage implements OnInit, OnDestroy { this.showTabs = true; - this.subscription = CoreMainMenuDelegate.instance.getHandlersObservable().subscribe((handlers) => { + this.subscription = CoreMainMenuDelegate.getHandlersObservable().subscribe((handlers) => { // Remove the handlers that should only appear in the More menu. this.allHandlers = handlers.filter((handler) => !handler.onlyInMore); @@ -102,7 +102,7 @@ export class CoreMainMenuPage implements OnInit, OnDestroy { window.addEventListener('resize', this.initHandlers.bind(this)); - if (CoreApp.instance.isIOS()) { + if (CoreApp.isIOS()) { // In iOS, the resize event is triggered before the keyboard is opened/closed and not triggered again once done. // Init handlers again once keyboard is closed since the resize event doesn't have the updated height. this.keyboardObserver = CoreEvents.on(CoreEvents.KEYBOARD_CHANGE, (kbHeight: number) => { @@ -123,9 +123,9 @@ export class CoreMainMenuPage implements OnInit, OnDestroy { */ initHandlers(): void { if (this.allHandlers) { - this.tabsPlacement = CoreMainMenu.instance.getTabPlacement(); + this.tabsPlacement = CoreMainMenu.getTabPlacement(); - const handlers = this.allHandlers.slice(0, CoreMainMenu.instance.getNumItems()); // Get main handlers. + const handlers = this.allHandlers.slice(0, CoreMainMenu.getNumItems()); // Get main handlers. // Re-build the list of tabs. If a handler is already in the list, use existing object to prevent re-creating the tab. const newTabs: CoreMainMenuHandlerToDisplay[] = []; @@ -147,7 +147,7 @@ export class CoreMainMenuPage implements OnInit, OnDestroy { // Sort them by priority so new handlers are in the right position. this.tabs.sort((a, b) => (b.priority || 0) - (a.priority || 0)); - this.loaded = CoreMainMenuDelegate.instance.areHandlersLoaded(); + this.loaded = CoreMainMenuDelegate.areHandlersLoaded(); if (this.loaded && this.mainTabs && !this.mainTabs.getSelected()) { // Select the first tab. @@ -190,7 +190,7 @@ export class CoreMainMenuPage implements OnInit, OnDestroy { if (i >= 0) { // Tab found. Open it with the params. - CoreNavigator.instance.navigate(data.redirectPath, { + CoreNavigator.navigate(data.redirectPath, { params: data.redirectParams, animated: false, }); @@ -225,10 +225,10 @@ export class CoreMainMenuPage implements OnInit, OnDestroy { return; } - const trimmedUrl = CoreTextUtils.instance.trimCharacter(this.router.url, '/'); + const trimmedUrl = CoreTextUtils.trimCharacter(this.router.url, '/'); // Current tab was clicked. Check if user is already at root level. - if (trimmedUrl == CoreTextUtils.instance.trimCharacter(page, '/')) { + if (trimmedUrl == CoreTextUtils.trimCharacter(page, '/')) { // Already at root level, nothing to do. return; } @@ -242,17 +242,17 @@ export class CoreMainMenuPage implements OnInit, OnDestroy { // Use tab's subPage to check if user is already at root level. if (tab?.subPage && trimmedUrl == - CoreTextUtils.instance.trimCharacter(CoreTextUtils.instance.concatenatePaths(tab.page, tab.subPage), '/')) { + CoreTextUtils.trimCharacter(CoreTextUtils.concatenatePaths(tab.page, tab.subPage), '/')) { // Already at root level, nothing to do. return; } if (tab?.title) { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.confirmgotabroot', { - name: Translate.instance.instant(tab.title), + await CoreDomUtils.showConfirm(Translate.instant('core.confirmgotabroot', { + name: Translate.instant(tab.title), })); } else { - await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.confirmgotabrootdefault')); + await CoreDomUtils.showConfirm(Translate.instant('core.confirmgotabrootdefault')); } // User confirmed, go to root. diff --git a/src/core/features/mainmenu/pages/more/more.ts b/src/core/features/mainmenu/pages/more/more.ts index e96ec3ff9..3c72b8885 100644 --- a/src/core/features/mainmenu/pages/more/more.ts +++ b/src/core/features/mainmenu/pages/more/more.ts @@ -56,11 +56,11 @@ export class CoreMainMenuMorePage implements OnInit, OnDestroy { this.updateSiteObserver = CoreEvents.on( CoreEvents.SITE_UPDATED, this.loadSiteInfo.bind(this), - CoreSites.instance.getCurrentSiteId(), + CoreSites.getCurrentSiteId(), ); this.loadSiteInfo(); - this.showScanQR = CoreUtils.instance.canScanQR() && - !CoreSites.instance.getCurrentSite()?.isFeatureDisabled('CoreMainMenuDelegate_QrReader'); + this.showScanQR = CoreUtils.canScanQR() && + !CoreSites.getCurrentSite()?.isFeatureDisabled('CoreMainMenuDelegate_QrReader'); } /** @@ -68,7 +68,7 @@ export class CoreMainMenuMorePage implements OnInit, OnDestroy { */ ngOnInit(): void { // Load the handlers. - this.subscription = CoreMainMenuDelegate.instance.getHandlersObservable().subscribe((handlers) => { + this.subscription = CoreMainMenuDelegate.getHandlersObservable().subscribe((handlers) => { this.allHandlers = handlers; this.initHandlers(); @@ -98,19 +98,19 @@ export class CoreMainMenuMorePage implements OnInit, OnDestroy { // Calculate the main handlers not to display them in this view. const mainHandlers = this.allHandlers .filter((handler) => !handler.onlyInMore) - .slice(0, CoreMainMenu.instance.getNumItems()); + .slice(0, CoreMainMenu.getNumItems()); // Get only the handlers that don't appear in the main view. this.handlers = this.allHandlers.filter((handler) => mainHandlers.indexOf(handler) == -1); - this.handlersLoaded = CoreMainMenuDelegate.instance.areHandlersLoaded(); + this.handlersLoaded = CoreMainMenuDelegate.areHandlersLoaded(); } /** * Load the site info required by the view. */ protected async loadSiteInfo(): Promise { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); if (!currentSite) { return; @@ -119,13 +119,13 @@ export class CoreMainMenuMorePage implements OnInit, OnDestroy { this.siteInfo = currentSite.getInfo(); this.siteName = currentSite.getSiteName(); this.siteUrl = currentSite.getURL(); - this.logoutLabel = CoreLoginHelper.instance.getLogoutLabel(currentSite); + this.logoutLabel = CoreLoginHelper.getLogoutLabel(currentSite); this.showWeb = !currentSite.isFeatureDisabled('CoreMainMenuDelegate_website'); this.showHelp = !currentSite.isFeatureDisabled('CoreMainMenuDelegate_help'); this.docsUrl = await currentSite.getDocsUrl(); - this.customItems = await CoreMainMenu.instance.getCustomMenuItems(); + this.customItems = await CoreMainMenu.getCustomMenuItems(); } /** @@ -137,7 +137,7 @@ export class CoreMainMenuMorePage implements OnInit, OnDestroy { openHandler(handler: CoreMainMenuHandlerData): void { const params = handler.pageParams; - CoreNavigator.instance.navigateToSitePath(handler.page, { params }); + CoreNavigator.navigateToSitePath(handler.page, { params }); } /** @@ -146,7 +146,7 @@ export class CoreMainMenuMorePage implements OnInit, OnDestroy { * @param item Item to open. */ openItem(item: CoreMainMenuCustomItem): void { - // @todo CoreNavigator.instance.navigateToSitePath('CoreViewerIframePage', {title: item.label, url: item.url}); + // @todo CoreNavigator.navigateToSitePath('CoreViewerIframePage', {title: item.label, url: item.url}); // eslint-disable-next-line no-console console.error('openItem not implemented', item); @@ -167,7 +167,7 @@ export class CoreMainMenuMorePage implements OnInit, OnDestroy { * Logout the user. */ logout(): void { - CoreSites.instance.logout(); + CoreSites.logout(); } } diff --git a/src/core/features/mainmenu/services/handlers/mainmenu.ts b/src/core/features/mainmenu/services/handlers/mainmenu.ts index 17226d49c..c11b6e9b4 100644 --- a/src/core/features/mainmenu/services/handlers/mainmenu.ts +++ b/src/core/features/mainmenu/services/handlers/mainmenu.ts @@ -43,7 +43,7 @@ export class CoreMainMenuHomeHandlerService implements CoreMainMenuHandler { * @return Whether or not the handler is enabled on a site level. */ async isEnabledForSite(): Promise { - return CoreMainMenuHomeDelegate.instance.getHandlers().length > 0; + return CoreMainMenuHomeDelegate.getHandlers().length > 0; } /** @@ -63,4 +63,4 @@ export class CoreMainMenuHomeHandlerService implements CoreMainMenuHandler { } -export class CoreMainMenuHomeHandler extends makeSingleton(CoreMainMenuHomeHandlerService) {} +export const CoreMainMenuHomeHandler = makeSingleton(CoreMainMenuHomeHandlerService); diff --git a/src/core/features/mainmenu/services/home-delegate.ts b/src/core/features/mainmenu/services/home-delegate.ts index 0b407ade5..588549137 100644 --- a/src/core/features/mainmenu/services/home-delegate.ts +++ b/src/core/features/mainmenu/services/home-delegate.ts @@ -94,4 +94,4 @@ export class CoreMainMenuHomeDelegateService extends CoreSortedDelegate !handler.onlyInMore) .slice(0, this.getNumItems()); } @@ -55,7 +55,7 @@ export class CoreMainMenuProvider { * @return List of custom menu items. */ async getCustomMenuItems(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const itemsString = site.getStoredConfig('tool_mobile_custommenuitems'); const map: CustomMenuItemsMap = {}; @@ -111,7 +111,7 @@ export class CoreMainMenuProvider { return result; } - const currentLang = await CoreLang.instance.getCurrentLanguage(); + const currentLang = await CoreLang.getCurrentLanguage(); const fallbackLang = CoreConstants.CONFIG.default_lang || 'en'; @@ -181,7 +181,7 @@ export class CoreMainMenuProvider { */ getTabPlacement(): string { const tablet = !!(window.innerWidth && window.innerWidth >= 576 && (window.innerHeight >= 576 || - ((CoreApp.instance.isKeyboardVisible() || CoreApp.instance.isKeyboardOpening()) && window.innerHeight >= 200))); + ((CoreApp.isKeyboardVisible() || CoreApp.isKeyboardOpening()) && window.innerHeight >= 200))); if (tablet != this.tablet) { this.tablet = tablet; @@ -226,14 +226,14 @@ export class CoreMainMenuProvider { * @return Whether it's disabled. */ protected isResponsiveMainMenuItemsDisabledInCurrentSite(): boolean { - const site = CoreSites.instance.getCurrentSite(); + const site = CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('NoDelegate_ResponsiveMainMenuItems'); } } -export class CoreMainMenu extends makeSingleton(CoreMainMenuProvider) {} +export const CoreMainMenu = makeSingleton(CoreMainMenuProvider); /** * Custom main menu item. diff --git a/src/core/features/pushnotifications/pushnotifications.module.ts b/src/core/features/pushnotifications/pushnotifications.module.ts index 8ba1ad90a..797698106 100644 --- a/src/core/features/pushnotifications/pushnotifications.module.ts +++ b/src/core/features/pushnotifications/pushnotifications.module.ts @@ -38,10 +38,10 @@ import { CorePushNotifications } from './services/pushnotifications'; deps: [], useFactory: () => async () => { // Register the handlers. - CoreCronDelegate.instance.register(CorePushNotificationsRegisterCronHandler.instance); - CoreCronDelegate.instance.register(CorePushNotificationsUnregisterCronHandler.instance); + CoreCronDelegate.register(CorePushNotificationsRegisterCronHandler.instance); + CoreCronDelegate.register(CorePushNotificationsUnregisterCronHandler.instance); - await CorePushNotifications.instance.initialize(); + await CorePushNotifications.initialize(); }, }, ], diff --git a/src/core/features/pushnotifications/services/handlers/register-cron.ts b/src/core/features/pushnotifications/services/handlers/register-cron.ts index dd31a26fa..b2dcdddc1 100644 --- a/src/core/features/pushnotifications/services/handlers/register-cron.ts +++ b/src/core/features/pushnotifications/services/handlers/register-cron.ts @@ -43,13 +43,13 @@ export class CorePushNotificationsRegisterCronHandlerService implements CoreCron * @return Promise resolved when done, rejected if failure. */ async execute(siteId?: string): Promise { - if (!siteId || !CorePushNotifications.instance.canRegisterOnMoodle()) { + if (!siteId || !CorePushNotifications.canRegisterOnMoodle()) { // It's not a specific site, don't do anything. return; } // Register the device again. - await CorePushNotifications.instance.registerDeviceOnMoodle(siteId, true); + await CorePushNotifications.registerDeviceOnMoodle(siteId, true); } /** @@ -72,4 +72,4 @@ export class CorePushNotificationsRegisterCronHandlerService implements CoreCron } -export class CorePushNotificationsRegisterCronHandler extends makeSingleton(CorePushNotificationsRegisterCronHandlerService) {} +export const CorePushNotificationsRegisterCronHandler = makeSingleton(CorePushNotificationsRegisterCronHandlerService); diff --git a/src/core/features/pushnotifications/services/handlers/unregister-cron.ts b/src/core/features/pushnotifications/services/handlers/unregister-cron.ts index 0a8eba061..1edab10d8 100644 --- a/src/core/features/pushnotifications/services/handlers/unregister-cron.ts +++ b/src/core/features/pushnotifications/services/handlers/unregister-cron.ts @@ -34,7 +34,7 @@ export class CorePushNotificationsUnregisterCronHandlerService implements CoreCr * @return Promise resolved when done, rejected if failure. */ async execute(siteId?: string): Promise { - await CorePushNotifications.instance.retryUnregisters(siteId); + await CorePushNotifications.retryUnregisters(siteId); } /** @@ -48,4 +48,4 @@ export class CorePushNotificationsUnregisterCronHandlerService implements CoreCr } -export class CorePushNotificationsUnregisterCronHandler extends makeSingleton(CorePushNotificationsUnregisterCronHandlerService) {} +export const CorePushNotificationsUnregisterCronHandler = makeSingleton(CorePushNotificationsUnregisterCronHandlerService); diff --git a/src/core/features/pushnotifications/services/push-delegate.ts b/src/core/features/pushnotifications/services/push-delegate.ts index 6a062181f..548301644 100644 --- a/src/core/features/pushnotifications/services/push-delegate.ts +++ b/src/core/features/pushnotifications/services/push-delegate.ts @@ -102,7 +102,7 @@ export class CorePushNotificationsDelegateService { } }); - await CoreUtils.instance.ignoreErrors(CoreUtils.instance.allPromises(promises)); + await CoreUtils.ignoreErrors(CoreUtils.allPromises(promises)); // Sort by priority. handlers = handlers.sort((a, b) => (a.priority || 0) <= (b.priority || 0) ? 1 : -1); @@ -124,7 +124,7 @@ export class CorePushNotificationsDelegateService { return false; } else if (handler.featureName) { // Check if the feature is disabled. - return CoreSites.instance.isFeatureDisabled(handler.featureName, siteId); + return CoreSites.isFeatureDisabled(handler.featureName, siteId); } else { return false; } @@ -215,4 +215,4 @@ export class CorePushNotificationsDelegateService { } -export class CorePushNotificationsDelegate extends makeSingleton(CorePushNotificationsDelegateService) {} +export const CorePushNotificationsDelegate = makeSingleton(CorePushNotificationsDelegateService); diff --git a/src/core/features/pushnotifications/services/pushnotifications.ts b/src/core/features/pushnotifications/services/pushnotifications.ts index 0d239834c..c6c0c6f99 100644 --- a/src/core/features/pushnotifications/services/pushnotifications.ts +++ b/src/core/features/pushnotifications/services/pushnotifications.ts @@ -101,7 +101,7 @@ export class CorePushNotificationsProvider { }); // Listen for local notification clicks (generated by the app). - CoreLocalNotifications.instance.registerClick( + CoreLocalNotifications.registerClick( CorePushNotificationsProvider.COMPONENT, (notification) => { // Log notification open event. @@ -112,7 +112,7 @@ export class CorePushNotificationsProvider { ); // Listen for local notification dismissed events. - CoreLocalNotifications.instance.registerObserver( + CoreLocalNotifications.registerObserver( 'clear', CorePushNotificationsProvider.COMPONENT, (notification) => { @@ -128,12 +128,12 @@ export class CorePushNotificationsProvider { * @return Promise resolved when done. */ protected async initializeDefaultChannel(): Promise { - await Platform.instance.ready(); + await Platform.ready(); // Create the default channel. this.createDefaultChannel(); - Translate.instance.onLangChange.subscribe(() => { + Translate.onLangChange.subscribe(() => { // Update the channel name. this.createDefaultChannel(); }); @@ -146,12 +146,12 @@ export class CorePushNotificationsProvider { */ protected async initializeDatabase(): Promise { try { - await CoreApp.instance.createTablesFromSchema(APP_SCHEMA); + await CoreApp.createTablesFromSchema(APP_SCHEMA); } catch (e) { // Ignore errors. } - this.resolveAppDB(CoreApp.instance.getDB()); + this.resolveAppDB(CoreApp.getDB()); } /** @@ -160,7 +160,7 @@ export class CorePushNotificationsProvider { * @return Whether the device can be registered in Moodle. */ canRegisterOnMoodle(): boolean { - return !!this.pushID && CoreApp.instance.isMobile(); + return !!this.pushID && CoreApp.isMobile(); } /** @@ -184,14 +184,14 @@ export class CorePushNotificationsProvider { * @return Promise resolved when done. */ protected async createDefaultChannel(): Promise { - if (!CoreApp.instance.isAndroid()) { + if (!CoreApp.isAndroid()) { return; } try { - await Push.instance.createChannel({ + await Push.createChannel({ id: 'PushPluginChannel', - description: Translate.instance.instant('core.misc'), + description: Translate.instant('core.misc'), importance: 4, }); } catch (error) { @@ -213,7 +213,7 @@ export class CorePushNotificationsProvider { return; } - const deferred = CoreUtils.instance.promiseDefer(); + const deferred = CoreUtils.promiseDefer(); win.PushNotification.enableAnalytics(deferred.resolve, (error) => { this.logger.error('Error enabling or disabling Firebase analytics', enable, error); @@ -231,8 +231,8 @@ export class CorePushNotificationsProvider { protected async getOptions(): Promise { let soundEnabled = true; - if (CoreLocalNotifications.instance.canDisableSound()) { - soundEnabled = await CoreConfig.instance.get(CoreConstants.SETTINGS_NOTIFICATION_SOUND, true); + if (CoreLocalNotifications.canDisableSound()) { + soundEnabled = await CoreConfig.get(CoreConstants.SETTINGS_NOTIFICATION_SOUND, true); } return { @@ -273,12 +273,12 @@ export class CorePushNotificationsProvider { return { appid: CoreConstants.CONFIG.app_id, - name: Device.instance.manufacturer || '', - model: Device.instance.model, - platform: Device.instance.platform + '-fcm', - version: Device.instance.version, + name: Device.manufacturer || '', + model: Device.model, + platform: Device.platform + '-fcm', + version: Device.version, pushid: this.pushID, - uuid: Device.instance.uuid, + uuid: Device.uuid, }; } @@ -309,12 +309,12 @@ export class CorePushNotificationsProvider { } // Check if the analytics is enabled by the user. - const enabled = await CoreConfig.instance.get(CoreConstants.SETTINGS_ANALYTICS_ENABLED, true); + const enabled = await CoreConfig.get(CoreConstants.SETTINGS_ANALYTICS_ENABLED, true); if (!enabled) { return; } - const deferred = CoreUtils.instance.promiseDefer(); + const deferred = CoreUtils.promiseDefer(); win.PushNotification.logEvent(deferred.resolve, (error) => { this.logger.error('Error logging firebase event', name, error); @@ -346,9 +346,9 @@ export class CorePushNotificationsProvider { data = data || {}; // Add "moodle" to the name of all extra params. - data = CoreUtils.instance.prefixKeys(data, 'moodle'); + data = CoreUtils.prefixKeys(data, 'moodle'); data.moodleaction = wsName; - data.moodlesiteid = siteId || CoreSites.instance.getCurrentSiteId(); + data.moodlesiteid = siteId || CoreSites.getCurrentSiteId(); if (itemId) { data.item_id = itemId; @@ -376,9 +376,9 @@ export class CorePushNotificationsProvider { data = data || {}; // Add "moodle" to the name of all extra params. - data = CoreUtils.instance.prefixKeys(data, 'moodle'); + data = CoreUtils.prefixKeys(data, 'moodle'); data.moodleaction = wsName; - data.moodlesiteid = siteId || CoreSites.instance.getCurrentSiteId(); + data.moodlesiteid = siteId || CoreSites.getCurrentSiteId(); if (itemCategory) { data.item_category = itemCategory; @@ -394,9 +394,9 @@ export class CorePushNotificationsProvider { * @return Promise resolved when done. */ async notificationClicked(data: CorePushNotificationsNotificationBasicData): Promise { - await ApplicationInit.instance.donePromise; + await ApplicationInit.donePromise; - CorePushNotificationsDelegate.instance.clicked(data); + CorePushNotificationsDelegate.clicked(data); } /** @@ -414,26 +414,26 @@ export class CorePushNotificationsProvider { title: notification.title, message: notification.message, customdata: typeof rawData.customdata == 'string' ? - CoreTextUtils.instance.parseJSON>(rawData.customdata, {}) : rawData.customdata, + CoreTextUtils.parseJSON>(rawData.customdata, {}) : rawData.customdata, }); let site: CoreSite | undefined; if (data.site) { - site = await CoreSites.instance.getSite(data.site); + site = await CoreSites.getSite(data.site); } else if (data.siteurl) { - site = await CoreSites.instance.getSiteByUrl(data.siteurl); + site = await CoreSites.getSiteByUrl(data.siteurl); } data.site = site?.getId(); - if (!CoreUtils.instance.isTrueOrOne(data.foreground)) { + if (!CoreUtils.isTrueOrOne(data.foreground)) { // The notification was clicked. return this.notificationClicked(data); } // If the app is in foreground when the notification is received, it's not shown. Let's show it ourselves. - if (!CoreLocalNotifications.instance.isAvailable()) { + if (!CoreLocalNotifications.isAvailable()) { return this.notifyReceived(notification, data); } @@ -444,10 +444,10 @@ export class CorePushNotificationsProvider { text: notification.message, channel: 'PushPluginChannel', }; - const isAndroid = CoreApp.instance.isAndroid(); - const extraFeatures = CoreUtils.instance.isTrueOrOne(data.extrafeatures); + const isAndroid = CoreApp.isAndroid(); + const extraFeatures = CoreUtils.isTrueOrOne(data.extrafeatures); - if (extraFeatures && isAndroid && CoreUtils.instance.isFalseOrZero(data.notif)) { + if (extraFeatures && isAndroid && CoreUtils.isFalseOrZero(data.notif)) { // It's a message, use messaging style. Ionic Native doesn't specify this option. // eslint-disable-next-line @typescript-eslint/no-explicit-any ( localNotif).text = [ @@ -472,7 +472,7 @@ export class CorePushNotificationsProvider { } } - CoreLocalNotifications.instance.schedule(localNotif, CorePushNotificationsProvider.COMPONENT, data.site || '', true); + CoreLocalNotifications.schedule(localNotif, CorePushNotificationsProvider.COMPONENT, data.site || '', true); await this.notifyReceived(notification, data); @@ -489,9 +489,9 @@ export class CorePushNotificationsProvider { notification: NotificationEventResponse, data: CorePushNotificationsNotificationBasicData, ): Promise { - await ApplicationInit.instance.donePromise; + await ApplicationInit.donePromise; - CorePushNotificationsDelegate.instance.received(data); + CorePushNotificationsDelegate.received(data); } /** @@ -501,7 +501,7 @@ export class CorePushNotificationsProvider { * @return Promise resolved when device is unregistered. */ async unregisterDeviceOnMoodle(site: CoreSite): Promise { - if (!site || !CoreApp.instance.isMobile()) { + if (!site || !CoreApp.isMobile()) { throw new CoreError('Cannot unregister device'); } @@ -510,7 +510,7 @@ export class CorePushNotificationsProvider { const db = await this.appDB; const data: CoreUserRemoveUserDeviceWSParams = { appid: CoreConstants.CONFIG.app_id, - uuid: Device.instance.uuid, + uuid: Device.uuid, }; try { @@ -520,14 +520,14 @@ export class CorePushNotificationsProvider { throw new CoreError('Cannot unregister device'); } - await CoreUtils.instance.ignoreErrors(Promise.all([ + await CoreUtils.ignoreErrors(Promise.all([ // Remove the device from the local DB. site.getDb().deleteRecords(REGISTERED_DEVICES_TABLE_NAME, this.getRegisterData()), // Remove pending unregisters for this site. db.deleteRecords(PENDING_UNREGISTER_TABLE_NAME, { siteid: site.getId() }), ])); } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { throw error; } @@ -552,11 +552,11 @@ export class CorePushNotificationsProvider { * @return Promise resolved with the stored badge counter for the addon on the site. */ async updateAddonCounter(addon: string, value: number, siteId?: string): Promise { - if (!CorePushNotificationsDelegate.instance.isCounterHandlerRegistered(addon)) { + if (!CorePushNotificationsDelegate.isCounterHandlerRegistered(addon)) { return 0; } - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); await this.saveAddonBadge(value, siteId, addon); await this.updateSiteCounter(siteId); @@ -570,19 +570,19 @@ export class CorePushNotificationsProvider { * @return Promise resolved with the stored badge counter for the site. */ async updateAppCounter(): Promise { - const sitesIds = await CoreSites.instance.getSitesIds(); + const sitesIds = await CoreSites.getSitesIds(); const counters = await Promise.all(sitesIds.map((siteId) => this.getAddonBadge(siteId))); const total = counters.reduce((previous, counter) => previous + counter, 0); - if (!CoreApp.instance.isMobile()) { + if (!CoreApp.isMobile()) { // Browser doesn't have an app badge, stop. return total; } // Set the app badge. - await Badge.instance.set(total); + await Badge.set(total); return total; } @@ -595,7 +595,7 @@ export class CorePushNotificationsProvider { * @return Promise resolved with the stored badge counter for the site. */ async updateSiteCounter(siteId: string): Promise { - const addons = CorePushNotificationsDelegate.instance.getCounterHandlers(); + const addons = CorePushNotificationsDelegate.getCounterHandlers(); const counters = await Promise.all(Object.values(addons).map((addon) => this.getAddonBadge(siteId, addon))); @@ -619,11 +619,11 @@ export class CorePushNotificationsProvider { // Check if sound is enabled for notifications. const options = await this.getOptions(); - const pushObject = Push.instance.init(options); + const pushObject = Push.init(options); pushObject.on('notification').subscribe((notification: NotificationEventResponse) => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { + NgZone.run(() => { this.logger.log('Received a notification', notification); this.onMessageReceived(notification); }); @@ -631,9 +631,9 @@ export class CorePushNotificationsProvider { pushObject.on('registration').subscribe((data: RegistrationEventResponse) => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { + NgZone.run(() => { this.pushID = data.registrationId; - if (!CoreSites.instance.isLoggedIn()) { + if (!CoreSites.isLoggedIn()) { return; } @@ -645,7 +645,7 @@ export class CorePushNotificationsProvider { pushObject.on('error').subscribe((error: Error) => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { + NgZone.run(() => { this.logger.warn('Error with Push plugin', error); }); }); @@ -670,7 +670,7 @@ export class CorePushNotificationsProvider { return Promise.reject(null); } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); try { @@ -687,12 +687,12 @@ export class CorePushNotificationsProvider { if (result.unregister) { // Unregister the device first. - await CoreUtils.instance.ignoreErrors(this.unregisterDeviceOnMoodle(site)); + await CoreUtils.ignoreErrors(this.unregisterDeviceOnMoodle(site)); } if (result.register) { // Now register the device. - await site.write('core_user_add_user_device', CoreUtils.instance.clone(data)); + await site.write('core_user_add_user_device', CoreUtils.clone(data)); CoreEvents.trigger(CoreEvents.DEVICE_REGISTERED_IN_MOODLE, {}, site.getId()); @@ -706,7 +706,7 @@ export class CorePushNotificationsProvider { } finally { // Remove pending unregisters for this site. const db = await this.appDB; - await CoreUtils.instance.ignoreErrors(db.deleteRecords(PENDING_UNREGISTER_TABLE_NAME, { siteid: site.getId() })); + await CoreUtils.ignoreErrors(db.deleteRecords(PENDING_UNREGISTER_TABLE_NAME, { siteid: site.getId() })); } } @@ -755,7 +755,7 @@ export class CorePushNotificationsProvider { result.siteid, result.siteurl, result.token, - CoreTextUtils.instance.parseJSON(result.info, null) || undefined, + CoreTextUtils.parseJSON(result.info, null) || undefined, ); await this.unregisterDeviceOnMoodle(tmpSite); @@ -771,7 +771,7 @@ export class CorePushNotificationsProvider { * @return Promise resolved with the stored badge counter for the addon or site. */ protected async saveAddonBadge(value: number, siteId?: string, addon: string = 'site'): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const entry: CorePushNotificationsBadgeDBRecord = { siteid: siteId, @@ -798,7 +798,7 @@ export class CorePushNotificationsProvider { ): Promise<{register: boolean; unregister: boolean}> { // Check if the device is already registered. - const records = await CoreUtils.instance.ignoreErrors( + const records = await CoreUtils.ignoreErrors( site.getDb().getRecords(REGISTERED_DEVICES_TABLE_NAME, { appid: data.appid, uuid: data.uuid, @@ -843,7 +843,7 @@ export class CorePushNotificationsProvider { } -export class CorePushNotifications extends makeSingleton(CorePushNotificationsProvider) {} +export const CorePushNotifications = makeSingleton(CorePushNotificationsProvider); /** * Additional data sent in push notifications. diff --git a/src/core/features/question/classes/base-behaviour-handler.ts b/src/core/features/question/classes/base-behaviour-handler.ts index e5d7b9da0..a33a83118 100644 --- a/src/core/features/question/classes/base-behaviour-handler.ts +++ b/src/core/features/question/classes/base-behaviour-handler.ts @@ -47,7 +47,7 @@ export class CoreQuestionBehaviourBaseHandler implements CoreQuestionBehaviourHa siteId?: string, // eslint-disable-line @typescript-eslint/no-unused-vars ): CoreQuestionState | Promise { // Return the current state. - return CoreQuestion.instance.getState(question.state); + return CoreQuestion.getState(question.state); } /** diff --git a/src/core/features/question/classes/base-question-component.ts b/src/core/features/question/classes/base-question-component.ts index b538aa870..5c41e753c 100644 --- a/src/core/features/question/classes/base-question-component.ts +++ b/src/core/features/question/classes/base-question-component.ts @@ -108,7 +108,7 @@ export class CoreQuestionBaseComponent { if (!label || option.name === undefined || option.value === undefined) { // Something went wrong when extracting the questions data. Abort. this.logger.warn('Aborting because of an error parsing options.', question.slot, option.name); - CoreQuestionHelper.instance.showComponentError(this.onAbort); + CoreQuestionHelper.showComponentError(this.onAbort); return true; } @@ -163,7 +163,7 @@ export class CoreQuestionBaseComponent { if (typeof optionEl.value == 'undefined') { this.logger.warn('Aborting because couldn\'t find input.', this.question?.slot); - CoreQuestionHelper.instance.showComponentError(this.onAbort); + CoreQuestionHelper.showComponentError(this.onAbort); return true; } @@ -213,19 +213,19 @@ export class CoreQuestionBaseComponent { if (!this.question) { this.logger.warn('Aborting because of no question received.'); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } this.hostElement.classList.add('core-question-container'); - const element = CoreDomUtils.instance.convertToElement(this.question.html); + const element = CoreDomUtils.convertToElement(this.question.html); // Extract question text. - this.question.text = CoreDomUtils.instance.getContentsOfElement(element, '.qtext'); + this.question.text = CoreDomUtils.getContentsOfElement(element, '.qtext'); if (typeof this.question.text == 'undefined') { this.logger.warn('Aborting because of an error parsing question.', this.question.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } return element; @@ -261,15 +261,15 @@ export class CoreQuestionBaseComponent { if (review) { // Search the answer and the attachments. - question.answer = CoreDomUtils.instance.getContentsOfElement(questionEl, '.qtype_essay_response'); + question.answer = CoreDomUtils.getContentsOfElement(questionEl, '.qtype_essay_response'); if (question.parsedSettings) { question.attachments = Array.from( - CoreQuestionHelper.instance.getResponseFileAreaFiles(question, 'attachments'), + CoreQuestionHelper.getResponseFileAreaFiles(question, 'attachments'), ); } else { - question.attachments = CoreQuestionHelper.instance.getQuestionAttachmentsFromHtml( - CoreDomUtils.instance.getContentsOfElement(questionEl, '.attachments') || '', + question.attachments = CoreQuestionHelper.getQuestionAttachmentsFromHtml( + CoreDomUtils.getContentsOfElement(questionEl, '.attachments') || '', ); } @@ -277,13 +277,13 @@ export class CoreQuestionBaseComponent { } const textarea = questionEl.querySelector('textarea[name*=_answer]'); - question.hasDraftFiles = question.allowsAnswerFiles && CoreQuestionHelper.instance.hasDraftFileUrls(questionEl.innerHTML); + question.hasDraftFiles = question.allowsAnswerFiles && CoreQuestionHelper.hasDraftFileUrls(questionEl.innerHTML); if (!textarea && (question.hasInlineText || !question.allowsAttachments)) { // Textarea not found, we might be in review. Search the answer and the attachments. - question.answer = CoreDomUtils.instance.getContentsOfElement(questionEl, '.qtype_essay_response'); - question.attachments = CoreQuestionHelper.instance.getQuestionAttachmentsFromHtml( - CoreDomUtils.instance.getContentsOfElement(questionEl, '.attachments') || '', + question.answer = CoreDomUtils.getContentsOfElement(questionEl, '.qtype_essay_response'); + question.attachments = CoreQuestionHelper.getQuestionAttachmentsFromHtml( + CoreDomUtils.getContentsOfElement(questionEl, '.attachments') || '', ); return questionEl; @@ -291,13 +291,13 @@ export class CoreQuestionBaseComponent { if (textarea) { const input = questionEl.querySelector('input[type="hidden"][name*=answerformat]'); - let content = CoreTextUtils.instance.decodeHTML(textarea.innerHTML || ''); + let content = CoreTextUtils.decodeHTML(textarea.innerHTML || ''); if (question.hasDraftFiles && question.responsefileareas) { - content = CoreTextUtils.instance.replaceDraftfileUrls( - CoreSites.instance.getCurrentSite()!.getURL(), + content = CoreTextUtils.replaceDraftfileUrls( + CoreSites.getCurrentSite()!.getURL(), content, - CoreQuestionHelper.instance.getResponseFileAreaFiles(question, 'answer'), + CoreQuestionHelper.getResponseFileAreaFiles(question, 'answer'), ).text; } @@ -340,7 +340,7 @@ export class CoreQuestionBaseComponent { } if (fileManagerUrl) { - const params = CoreUrlUtils.instance.extractUrlParams(fileManagerUrl); + const params = CoreUrlUtils.extractUrlParams(fileManagerUrl); const maxBytes = Number(params.maxbytes); const areaMaxBytes = Number(params.areamaxbytes); @@ -362,29 +362,29 @@ export class CoreQuestionBaseComponent { if (!this.question) { this.logger.warn('Aborting because of no question received.'); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } - const element = CoreDomUtils.instance.convertToElement(this.question.html); + const element = CoreDomUtils.convertToElement(this.question.html); // Get question content. const content = element.querySelector(contentSelector); if (!content) { this.logger.warn('Aborting because of an error parsing question.', this.question.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } // Remove sequencecheck and validation error. - CoreDomUtils.instance.removeElement(content, 'input[name*=sequencecheck]'); - CoreDomUtils.instance.removeElement(content, '.validationerror'); + CoreDomUtils.removeElement(content, 'input[name*=sequencecheck]'); + CoreDomUtils.removeElement(content, '.validationerror'); // Replace Moodle's correct/incorrect and feedback classes with our own. - CoreQuestionHelper.instance.replaceCorrectnessClasses(element); - CoreQuestionHelper.instance.replaceFeedbackClasses(element); + CoreQuestionHelper.replaceCorrectnessClasses(element); + CoreQuestionHelper.replaceFeedbackClasses(element); // Treat the correct/incorrect icons. - CoreQuestionHelper.instance.treatCorrectnessIcons(element); + CoreQuestionHelper.treatCorrectnessIcons(element); // Set the question text. this.question.text = content.innerHTML; @@ -409,7 +409,7 @@ export class CoreQuestionBaseComponent { if (!input) { this.logger.warn('Aborting because couldn\'t find input.', this.question!.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } question.input = { @@ -417,7 +417,7 @@ export class CoreQuestionBaseComponent { name: input.name, value: input.value, readOnly: input.readOnly, - isInline: !!CoreDomUtils.instance.closest(input, '.qtext'), // The answer can be inside the question text. + isInline: !!CoreDomUtils.closest(input, '.qtext'), // The answer can be inside the question text. }; // Check if question is marked as correct. @@ -443,8 +443,8 @@ export class CoreQuestionBaseComponent { // Handle correct/incorrect classes and icons. const content = questionEl.querySelector('.qtext'); - CoreQuestionHelper.instance.replaceCorrectnessClasses(content); - CoreQuestionHelper.instance.treatCorrectnessIcons(content); + CoreQuestionHelper.replaceCorrectnessClasses(content); + CoreQuestionHelper.treatCorrectnessIcons(content); question.text = content.innerHTML; } @@ -469,7 +469,7 @@ export class CoreQuestionBaseComponent { if (!rows || !rows.length) { this.logger.warn('Aborting because couldn\'t find any row.', question.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } question.rows = []; @@ -481,7 +481,7 @@ export class CoreQuestionBaseComponent { if (!columns || columns.length < 2) { this.logger.warn('Aborting because couldn\'t the right columns.', question.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } // Get the select and the options. @@ -491,7 +491,7 @@ export class CoreQuestionBaseComponent { if (!select || !options || !options.length) { this.logger.warn('Aborting because couldn\'t find select or options.', question.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } const rowModel: AddonModQuizQuestionMatchSelect = { @@ -516,7 +516,7 @@ export class CoreQuestionBaseComponent { if (typeof optionEl.value == 'undefined') { this.logger.warn('Aborting because couldn\'t find the value of an option.', question.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } const option: AddonModQuizQuestionSelectOption = { @@ -557,7 +557,7 @@ export class CoreQuestionBaseComponent { // Get the prompt. const question = this.question!; - question.prompt = CoreDomUtils.instance.getContentsOfElement(questionEl, '.prompt'); + question.prompt = CoreDomUtils.getContentsOfElement(questionEl, '.prompt'); // Search radio buttons first (single choice). let options = Array.from(questionEl.querySelectorAll('input[type="radio"]')); @@ -570,7 +570,7 @@ export class CoreQuestionBaseComponent { // No checkbox found either. Abort. this.logger.warn('Aborting because of no radio and checkbox found.', question.slot); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } } @@ -609,7 +609,7 @@ export class CoreQuestionBaseComponent { // Something went wrong when extracting the questions data. Abort. this.logger.warn('Aborting because of an error parsing options.', question.slot, option.name); - return CoreQuestionHelper.instance.showComponentError(this.onAbort); + return CoreQuestionHelper.showComponentError(this.onAbort); } option.text = label.innerHTML; diff --git a/src/core/features/question/components/question/question.ts b/src/core/features/question/components/question/question.ts index c7e22df4e..21afeda9f 100644 --- a/src/core/features/question/components/question/question.ts +++ b/src/core/features/question/components/question/question.ts @@ -65,18 +65,18 @@ export class CoreQuestionComponent implements OnInit { * Component being initialized. */ async ngOnInit(): Promise { - this.offlineEnabled = CoreUtils.instance.isTrueOrOne(this.offlineEnabled); + this.offlineEnabled = CoreUtils.isTrueOrOne(this.offlineEnabled); if (!this.question || (this.question.type != 'random' && - !CoreQuestionDelegate.instance.isQuestionSupported(this.question.type))) { + !CoreQuestionDelegate.isQuestionSupported(this.question.type))) { this.loaded = true; return; } // Get the component to render the question. - this.componentClass = await CoreUtils.instance.ignoreErrors( - CoreQuestionDelegate.instance.getComponentForQuestion(this.question), + this.componentClass = await CoreUtils.ignoreErrors( + CoreQuestionDelegate.getComponentForQuestion(this.question), ); if (!this.componentClass) { @@ -100,29 +100,29 @@ export class CoreQuestionComponent implements OnInit { }; // Treat the question. - CoreQuestionHelper.instance.extractQuestionScripts(this.question, this.usageId); + CoreQuestionHelper.extractQuestionScripts(this.question, this.usageId); // Handle question behaviour. - const behaviour = CoreQuestionDelegate.instance.getBehaviourForQuestion( + const behaviour = CoreQuestionDelegate.getBehaviourForQuestion( this.question, this.preferredBehaviour || '', ); - if (!CoreQuestionBehaviourDelegate.instance.isBehaviourSupported(behaviour)) { + if (!CoreQuestionBehaviourDelegate.isBehaviourSupported(behaviour)) { // Behaviour not supported, abort. this.logger.warn('Aborting question because the behaviour is not supported.', this.question.slot); - CoreQuestionHelper.instance.showComponentError( + CoreQuestionHelper.showComponentError( this.onAbort, - Translate.instance.instant('addon.mod_quiz.errorbehaviournotsupported') + ' ' + behaviour, + Translate.instant('addon.mod_quiz.errorbehaviournotsupported') + ' ' + behaviour, ); return; } // Get the sequence check (hidden input). This is required. - this.seqCheck = CoreQuestionHelper.instance.getQuestionSequenceCheckFromHtml(this.question.html); + this.seqCheck = CoreQuestionHelper.getQuestionSequenceCheckFromHtml(this.question.html); if (!this.seqCheck) { this.logger.warn('Aborting question because couldn\'t retrieve sequence check.', this.question.slot); - CoreQuestionHelper.instance.showComponentError(this.onAbort); + CoreQuestionHelper.showComponentError(this.onAbort); return; } @@ -130,31 +130,31 @@ export class CoreQuestionComponent implements OnInit { // Load local answers if offline is enabled. if (this.offlineEnabled && this.component && this.attemptId) { - await CoreQuestionHelper.instance.loadLocalAnswers(this.question, this.component, this.attemptId); + await CoreQuestionHelper.loadLocalAnswers(this.question, this.component, this.attemptId); } else { this.question.localAnswers = {}; } - CoreQuestionHelper.instance.extractQbehaviourRedoButton(this.question); + CoreQuestionHelper.extractQbehaviourRedoButton(this.question); // Extract the validation error of the question. - this.validationError = CoreQuestionHelper.instance.getValidationErrorFromHtml(this.question.html); + this.validationError = CoreQuestionHelper.getValidationErrorFromHtml(this.question.html); // Load the local answers in the HTML. - CoreQuestionHelper.instance.loadLocalAnswersInHtml(this.question); + CoreQuestionHelper.loadLocalAnswersInHtml(this.question); // Try to extract the feedback and comment for the question. - CoreQuestionHelper.instance.extractQuestionFeedback(this.question); - CoreQuestionHelper.instance.extractQuestionComment(this.question); + CoreQuestionHelper.extractQuestionFeedback(this.question); + CoreQuestionHelper.extractQuestionComment(this.question); try { // Handle behaviour. - this.behaviourComponents = await CoreQuestionBehaviourDelegate.instance.handleQuestion( + this.behaviourComponents = await CoreQuestionBehaviourDelegate.handleQuestion( this.preferredBehaviour || '', this.question, ); } finally { - this.question.html = CoreDomUtils.instance.removeElementFromHtml(this.question.html, '.im-controls'); + this.question.html = CoreDomUtils.removeElementFromHtml(this.question.html, '.im-controls'); this.loaded = true; } } diff --git a/src/core/features/question/services/behaviour-delegate.ts b/src/core/features/question/services/behaviour-delegate.ts index e48575953..e6c421565 100644 --- a/src/core/features/question/services/behaviour-delegate.ts +++ b/src/core/features/question/services/behaviour-delegate.ts @@ -89,7 +89,7 @@ export class CoreQuestionBehaviourDelegateService extends CoreDelegate { - behaviour = CoreQuestionDelegate.instance.getBehaviourForQuestion(question, behaviour); + behaviour = CoreQuestionDelegate.getBehaviourForQuestion(question, behaviour); return this.executeFunctionOnEnabled( behaviour, @@ -108,7 +108,7 @@ export class CoreQuestionBehaviourDelegateService extends CoreDelegate[] | undefined> { - behaviour = CoreQuestionDelegate.instance.getBehaviourForQuestion(question, behaviour); + behaviour = CoreQuestionDelegate.getBehaviourForQuestion(question, behaviour); return this.executeFunctionOnEnabled(behaviour, 'handleQuestion', [question]); } @@ -125,7 +125,7 @@ export class CoreQuestionBehaviourDelegateService extends CoreDelegate { - await CoreQuestionDelegate.instance.clearTmpData(question, component, componentId); + await CoreQuestionDelegate.clearTmpData(question, component, componentId); })); } @@ -87,11 +87,11 @@ export class CoreQuestionHelperProvider { componentId: string | number, siteId?: string, ): Promise { - const questionComponentId = CoreQuestion.instance.getQuestionComponentId(question, componentId); - const folderPath = CoreQuestion.instance.getQuestionFolder(question.type, component, questionComponentId, siteId); + const questionComponentId = CoreQuestion.getQuestionComponentId(question, componentId); + const folderPath = CoreQuestion.getQuestionFolder(question.type, component, questionComponentId, siteId); // Ignore errors, maybe the folder doesn't exist. - await CoreUtils.instance.ignoreErrors(CoreFile.instance.removeDir(folderPath)); + await CoreUtils.ignoreErrors(CoreFile.removeDir(folderPath)); } /** @@ -102,14 +102,14 @@ export class CoreQuestionHelperProvider { * @param selector Selector to search the buttons. By default, '.im-controls input[type="submit"]'. */ extractQbehaviourButtons(question: CoreQuestionQuestionParsed, selector?: string): void { - if (CoreQuestionDelegate.instance.getPreventSubmitMessage(question)) { + if (CoreQuestionDelegate.getPreventSubmitMessage(question)) { // The question is not fully supported, don't extract the buttons. return; } selector = selector || '.im-controls input[type="submit"]'; - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); // Search the buttons. const buttons = Array.from(element.querySelectorAll(selector)); @@ -128,7 +128,7 @@ export class CoreQuestionHelperProvider { * @return Wether the certainty is found. */ extractQbehaviourCBM(question: CoreQuestionQuestion): boolean { - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); const labels = Array.from(element.querySelectorAll('.im-controls .certaintychoices label[for*="certainty"]')); question.behaviourCertaintyOptions = []; @@ -141,7 +141,7 @@ export class CoreQuestionHelperProvider { id: input.id, name: input.name, value: input.value, - text: CoreTextUtils.instance.cleanTags(label.innerHTML), + text: CoreTextUtils.cleanTags(label.innerHTML), disabled: input.disabled, }); @@ -195,7 +195,7 @@ export class CoreQuestionHelperProvider { * @return Whether the seen input is found. */ extractQbehaviourSeenInput(question: CoreQuestionQuestion): boolean { - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); // Search the "seen" input. const seenInput = element.querySelector('input[type="hidden"][name*=seen]'); @@ -251,13 +251,13 @@ export class CoreQuestionHelperProvider { * @param attrName Name of the attribute to store the HTML in. */ protected extractQuestionLastElementNotInContent(question: CoreQuestionQuestion, selector: string, attrName: string): void { - const element = CoreDomUtils.instance.convertToElement(question.html); + const element = CoreDomUtils.convertToElement(question.html); const matches = Array.from(element.querySelectorAll(selector)); // Get the last element and check it's not in the question contents. let last = matches.pop(); while (last) { - if (!CoreDomUtils.instance.closest(last, '.formulation')) { + if (!CoreDomUtils.closest(last, '.formulation')) { // Not in question contents. Add it to a separate attribute and remove it from the HTML. question[attrName] = last.innerHTML; last.parentElement?.removeChild(last); @@ -305,7 +305,7 @@ export class CoreQuestionHelperProvider { initMatch = initMatch.substr(0, initMatch.length - 2); // Try to convert it to an object and add it to the question. - question.initObjects = CoreTextUtils.instance.parseJSON(initMatch, null); + question.initObjects = CoreTextUtils.parseJSON(initMatch, null); } const amdRegExp = new RegExp('require\\(\\[["\']qtype_' + question.type + '/question["\']\\],[^f]*' + @@ -315,7 +315,7 @@ export class CoreQuestionHelperProvider { if (amdMatch) { // Try to convert the arguments to an array and add them to the question. - question.amdArgs = CoreTextUtils.instance.parseJSON('[' + amdMatch[1] + ']', null); + question.amdArgs = CoreTextUtils.parseJSON('[' + amdMatch[1] + ']', null); } }); } @@ -329,7 +329,7 @@ export class CoreQuestionHelperProvider { * @return Object where the keys are the names. */ getAllInputNamesFromHtml(html: string): Record { - const element = CoreDomUtils.instance.convertToElement('
' + html + ''); + const element = CoreDomUtils.convertToElement('
' + html + ''); const form = element.children[0]; const answers: Record = {}; @@ -342,7 +342,7 @@ export class CoreQuestionHelperProvider { return; } - answers[CoreQuestion.instance.removeQuestionPrefix(name)] = true; + answers[CoreQuestion.removeQuestionPrefix(name)] = true; }); return answers; @@ -395,10 +395,10 @@ export class CoreQuestionHelperProvider { * @return Attachments. */ getQuestionAttachmentsFromHtml(html: string): CoreWSExternalFile[] { - const element = CoreDomUtils.instance.convertToElement(html); + const element = CoreDomUtils.convertToElement(html); // Remove the filemanager (area to attach files to a question). - CoreDomUtils.instance.removeElement(element, 'div[id*=filemanager]'); + CoreDomUtils.removeElement(element, 'div[id*=filemanager]'); // Search the anchors. const anchors = Array.from(element.querySelectorAll('a')); @@ -409,7 +409,7 @@ export class CoreQuestionHelperProvider { // Check anchor is valid. if (anchor.href && content) { - content = CoreTextUtils.instance.cleanTags(content, true).trim(); + content = CoreTextUtils.cleanTags(content, true).trim(); attachments.push({ filename: content, fileurl: anchor.href, @@ -432,7 +432,7 @@ export class CoreQuestionHelperProvider { } // Search the input holding the sequencecheck. - const element = CoreDomUtils.instance.convertToElement(html); + const element = CoreDomUtils.convertToElement(html); const input = element.querySelector('input[name*=sequencecheck]'); if (!input || input.name === undefined || input.value === undefined) { @@ -452,7 +452,7 @@ export class CoreQuestionHelperProvider { * @return State class. */ getQuestionStateClass(name: string): string { - const state = CoreQuestion.instance.getState(name); + const state = CoreQuestion.getState(name); return state ? state.class : ''; } @@ -489,10 +489,10 @@ export class CoreQuestionHelperProvider { componentId: string | number, siteId?: string, ): Promise<(FileEntry | DirectoryEntry)[]> { - const questionComponentId = CoreQuestion.instance.getQuestionComponentId(question, componentId); - const folderPath = CoreQuestion.instance.getQuestionFolder(question.type, component, questionComponentId, siteId); + const questionComponentId = CoreQuestion.getQuestionComponentId(question, componentId); + const folderPath = CoreQuestion.getQuestionFolder(question.type, component, questionComponentId, siteId); - return CoreFile.instance.getDirectoryContents(folderPath); + return CoreFile.getDirectoryContents(folderPath); } /** @@ -502,9 +502,9 @@ export class CoreQuestionHelperProvider { * @return Validation error message if present. */ getValidationErrorFromHtml(html: string): string | undefined { - const element = CoreDomUtils.instance.convertToElement(html); + const element = CoreDomUtils.convertToElement(html); - return CoreDomUtils.instance.getContentsOfElement(element, '.validationerror'); + return CoreDomUtils.getContentsOfElement(element, '.validationerror'); } /** @@ -514,7 +514,7 @@ export class CoreQuestionHelperProvider { * @return Whether it contains draft files URLs. */ hasDraftFileUrls(html: string): boolean { - let url = CoreSites.instance.getCurrentSite()?.getURL(); + let url = CoreSites.getCurrentSite()?.getURL(); if (!url) { return false; } @@ -536,12 +536,12 @@ export class CoreQuestionHelperProvider { * @return Promise resolved when done. */ async loadLocalAnswers(question: CoreQuestionQuestion, component: string, attemptId: number): Promise { - const answers = await CoreUtils.instance.ignoreErrors( - CoreQuestion.instance.getQuestionAnswers(component, attemptId, question.slot), + const answers = await CoreUtils.ignoreErrors( + CoreQuestion.getQuestionAnswers(component, attemptId, question.slot), ); if (answers) { - question.localAnswers = CoreQuestion.instance.convertAnswersArrayToObject(answers, true); + question.localAnswers = CoreQuestion.convertAnswersArrayToObject(answers, true); } else { question.localAnswers = {}; } @@ -554,7 +554,7 @@ export class CoreQuestionHelperProvider { * @param question Question. */ loadLocalAnswersInHtml(question: CoreQuestionQuestion): void { - const element = CoreDomUtils.instance.convertToElement('
' + question.html + ''); + const element = CoreDomUtils.convertToElement('
' + question.html + ''); const form = element.children[0]; // Search all input elements. @@ -567,7 +567,7 @@ export class CoreQuestionHelperProvider { } // Search if there's a local answer. - name = CoreQuestion.instance.removeQuestionPrefix(name); + name = CoreQuestion.removeQuestionPrefix(name); if (question.localAnswers[name] === undefined) { if (Object.keys(question.localAnswers).length && element.type == 'radio') { // No answer stored, but there is a sequencecheck or similar. This means the user cleared his choice. @@ -595,7 +595,7 @@ export class CoreQuestionHelperProvider { } } else if (element.type == 'checkbox') { // Check if this checkbox is checked. - if (CoreUtils.instance.isTrueOrOne(question.localAnswers[name])) { + if (CoreUtils.isTrueOrOne(question.localAnswers[name])) { element.setAttribute('checked', 'checked'); } else { element.removeAttribute('checked'); @@ -632,11 +632,11 @@ export class CoreQuestionHelperProvider { componentId = question.number; } - const files = CoreQuestionDelegate.instance.getAdditionalDownloadableFiles(question, usageId) || []; + const files = CoreQuestionDelegate.getAdditionalDownloadableFiles(question, usageId) || []; - files.push(...CoreFilepool.instance.extractDownloadableFilesFromHtmlAsFakeFileObjects(question.html)); + files.push(...CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(question.html)); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const treated: Record = {}; @@ -648,7 +648,7 @@ export class CoreQuestionHelperProvider { } treated[file.fileurl] = true; - if (!site.canDownloadFiles() && CoreUrlUtils.instance.isPluginFileUrl(file.fileurl)) { + if (!site.canDownloadFiles() && CoreUrlUtils.isPluginFileUrl(file.fileurl)) { return; } @@ -657,7 +657,7 @@ export class CoreQuestionHelperProvider { return; } - await CoreFilepool.instance.addToQueueByUrl(site.getId(), file.fileurl, component, componentId, timemodified); + await CoreFilepool.addToQueueByUrl(site.getId(), file.fileurl, component, componentId, timemodified); })); } @@ -680,8 +680,8 @@ export class CoreQuestionHelperProvider { componentId: string | number, siteId?: string, ): Promise { - await CoreUtils.instance.allPromises(questions.map(async (question) => { - await CoreQuestionDelegate.instance.prepareAnswersForQuestion( + await CoreUtils.allPromises(questions.map(async (question) => { + await CoreQuestionDelegate.prepareAnswersForQuestion( question, answers, offline, @@ -700,7 +700,7 @@ export class CoreQuestionHelperProvider { * @param element DOM element. */ replaceCorrectnessClasses(element: HTMLElement): void { - CoreDomUtils.instance.replaceClassesInElement(element, { + CoreDomUtils.replaceClassesInElement(element, { correct: 'core-question-answer-correct', incorrect: 'core-question-answer-incorrect', }); @@ -712,7 +712,7 @@ export class CoreQuestionHelperProvider { * @param element DOM element. */ replaceFeedbackClasses(element: HTMLElement): void { - CoreDomUtils.instance.replaceClassesInElement(element, { + CoreDomUtils.replaceClassesInElement(element, { outcome: 'core-question-feedback-container core-question-feedback-padding', specificfeedback: 'core-question-feedback-container core-question-feedback-inline', }); @@ -727,7 +727,7 @@ export class CoreQuestionHelperProvider { * @return Whether the button is found. */ protected searchBehaviourButton(question: CoreQuestionQuestion, htmlProperty: string, selector: string): boolean { - const element = CoreDomUtils.instance.convertToElement(question[htmlProperty]); + const element = CoreDomUtils.convertToElement(question[htmlProperty]); const button = element.querySelector(selector); if (!button) { @@ -757,7 +757,7 @@ export class CoreQuestionHelperProvider { const now = Date.now(); if (now - this.lastErrorShown > 500) { this.lastErrorShown = now; - CoreDomUtils.instance.showErrorModalDefault(error || '', 'addon.mod_quiz.errorparsequestions', true); + CoreDomUtils.showErrorModalDefault(error || '', 'addon.mod_quiz.errorparsequestions', true); } onAbort?.emit(); @@ -846,7 +846,7 @@ export class CoreQuestionHelperProvider { // @todo: Check if another attribute needs to be used now instead of tappable. const icons = Array.from(element.querySelectorAll('i.icon.questioncorrectnessicon[tappable]')); - const title = Translate.instance.instant('core.question.feedback'); + const title = Translate.instant('core.question.feedback'); icons.forEach((icon) => { // Search the feedback for the icon. @@ -858,7 +858,7 @@ export class CoreQuestionHelperProvider { // There's a hidden feedback, show it when the icon is clicked. icon.addEventListener('click', () => { - CoreTextUtils.instance.viewText(title, span.innerHTML, { + CoreTextUtils.viewText(title, span.innerHTML, { component: component, componentId: componentId, filter: true, @@ -872,7 +872,7 @@ export class CoreQuestionHelperProvider { } -export class CoreQuestionHelper extends makeSingleton(CoreQuestionHelperProvider) {} +export const CoreQuestionHelper = makeSingleton(CoreQuestionHelperProvider); /** * Question with calculated data. diff --git a/src/core/features/question/services/question.ts b/src/core/features/question/services/question.ts index b7b103533..057c1015f 100644 --- a/src/core/features/question/services/question.ts +++ b/src/core/features/question/services/question.ts @@ -141,7 +141,7 @@ export class CoreQuestionProvider { */ compareAllAnswers(prevAnswers: Record, newAnswers: Record): boolean { // Get all the keys. - const keys = CoreUtils.instance.mergeArraysWithoutDuplicates(Object.keys(prevAnswers), Object.keys(newAnswers)); + const keys = CoreUtils.mergeArraysWithoutDuplicates(Object.keys(prevAnswers), Object.keys(newAnswers)); // Check that all the keys have the same value on both objects. for (const i in keys) { @@ -149,7 +149,7 @@ export class CoreQuestionProvider { // Ignore extra answers like sequencecheck or certainty. if (!this.isExtraAnswer(key[0])) { - if (!CoreUtils.instance.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, key)) { + if (!CoreUtils.sameAtKeyMissingIsBlank(prevAnswers, newAnswers, key)) { return false; } } @@ -190,7 +190,7 @@ export class CoreQuestionProvider { * @return Promise resolved with the answer. */ async getAnswer(component: string, attemptId: number, name: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecord(QUESTION_ANSWERS_TABLE_NAME, { component, attemptid: attemptId, name }); } @@ -204,7 +204,7 @@ export class CoreQuestionProvider { * @return Promise resolved with the answers. */ async getAttemptAnswers(component: string, attemptId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecords(QUESTION_ANSWERS_TABLE_NAME, { component, attemptid: attemptId }); } @@ -218,7 +218,7 @@ export class CoreQuestionProvider { * @return Promise resolved with the questions. */ async getAttemptQuestions(component: string, attemptId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecords(QUESTION_TABLE_NAME, { component, attemptid: attemptId }); } @@ -269,7 +269,7 @@ export class CoreQuestionProvider { * @return Promise resolved with the question. */ async getQuestion(component: string, attemptId: number, slot: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecord(QUESTION_TABLE_NAME, { component, attemptid: attemptId, slot }); } @@ -291,7 +291,7 @@ export class CoreQuestionProvider { filter?: boolean, siteId?: string, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const answers = await db.getRecords( QUESTION_ANSWERS_TABLE_NAME, @@ -327,12 +327,12 @@ export class CoreQuestionProvider { * @return Folder path. */ getQuestionFolder(type: string, component: string, componentId: string, siteId?: string): string { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const siteFolderPath = CoreFile.instance.getSiteFolder(siteId); + const siteFolderPath = CoreFile.getSiteFolder(siteId); const questionFolderPath = 'offlinequestion/' + type + '/' + component + '/' + componentId; - return CoreTextUtils.instance.concatenatePaths(siteFolderPath, questionFolderPath); + return CoreTextUtils.concatenatePaths(siteFolderPath, questionFolderPath); } /** @@ -389,7 +389,7 @@ export class CoreQuestionProvider { return; } - question.parsedSettings = CoreTextUtils.instance.parseJSON(question.settings, null); + question.parsedSettings = CoreTextUtils.parseJSON(question.settings, null); }); return parsedQuestions; @@ -404,7 +404,7 @@ export class CoreQuestionProvider { * @return Promise resolved when done. */ async removeAttemptAnswers(component: string, attemptId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(QUESTION_ANSWERS_TABLE_NAME, { component, attemptid: attemptId }); } @@ -418,7 +418,7 @@ export class CoreQuestionProvider { * @return Promise resolved when done. */ async removeAttemptQuestions(component: string, attemptId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(QUESTION_TABLE_NAME, { component, attemptid: attemptId }); } @@ -433,7 +433,7 @@ export class CoreQuestionProvider { * @return Promise resolved when done. */ async removeAnswer(component: string, attemptId: number, name: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(QUESTION_ANSWERS_TABLE_NAME, { component, attemptid: attemptId, name }); } @@ -448,7 +448,7 @@ export class CoreQuestionProvider { * @return Promise resolved when done. */ async removeQuestion(component: string, attemptId: number, slot: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(QUESTION_TABLE_NAME, { component, attemptid: attemptId, slot }); } @@ -463,7 +463,7 @@ export class CoreQuestionProvider { * @return Promise resolved when done. */ async removeQuestionAnswers(component: string, attemptId: number, slot: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.getDb().deleteRecords(QUESTION_ANSWERS_TABLE_NAME, { component, attemptid: attemptId, questionslot: slot }); } @@ -503,9 +503,9 @@ export class CoreQuestionProvider { timemodified?: number, siteId?: string, ): Promise { - timemodified = timemodified || CoreTimeUtils.instance.timestamp(); + timemodified = timemodified || CoreTimeUtils.timestamp(); - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const promises: Promise[] = []; for (const name in answers) { @@ -548,7 +548,7 @@ export class CoreQuestionProvider { siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const entry: CoreQuestionDBRecord = { component, componentid: componentId, @@ -564,7 +564,7 @@ export class CoreQuestionProvider { } -export class CoreQuestion extends makeSingleton(CoreQuestionProvider) {} +export const CoreQuestion = makeSingleton(CoreQuestionProvider); /** * Question state. diff --git a/src/core/features/search/components/search-box/search-box.ts b/src/core/features/search/components/search-box/search-box.ts index b9a4984d5..260f9b266 100644 --- a/src/core/features/search/components/search-box/search-box.ts +++ b/src/core/features/search/components/search-box/search-box.ts @@ -69,10 +69,10 @@ export class CoreSearchBoxComponent implements OnInit { } ngOnInit(): void { - this.searchLabel = this.searchLabel || Translate.instance.instant('core.search'); - this.placeholder = this.placeholder || Translate.instance.instant('core.search'); - this.spellcheck = CoreUtils.instance.isTrueOrOne(this.spellcheck); - this.showClear = CoreUtils.instance.isTrueOrOne(this.showClear); + this.searchLabel = this.searchLabel || Translate.instant('core.search'); + this.placeholder = this.placeholder || Translate.instant('core.search'); + this.spellcheck = CoreUtils.isTrueOrOne(this.spellcheck); + this.showClear = CoreUtils.isTrueOrOne(this.showClear); this.searchText = this.initialSearch; if (this.searchArea) { @@ -98,7 +98,7 @@ export class CoreSearchBoxComponent implements OnInit { this.saveSearchToHistory(this.searchText); } - CoreDomUtils.instance.triggerFormSubmittedEvent(this.formElement, false, CoreSites.instance.getCurrentSiteId()); + CoreDomUtils.triggerFormSubmittedEvent(this.formElement, false, CoreSites.getCurrentSiteId()); this.historyShown = false; this.searched = this.searchText; @@ -113,7 +113,7 @@ export class CoreSearchBoxComponent implements OnInit { */ protected async saveSearchToHistory(text: string): Promise { try { - await CoreSearchHistory.instance.insertOrUpdateSearchText(this.searchArea, text.toLowerCase()); + await CoreSearchHistory.insertOrUpdateSearchText(this.searchArea, text.toLowerCase()); } finally { this.loadHistory(); } @@ -125,7 +125,7 @@ export class CoreSearchBoxComponent implements OnInit { * @return Promise resolved when done. */ protected async loadHistory(): Promise { - this.history = await CoreSearchHistory.instance.getSearchHistory(this.searchArea); + this.history = await CoreSearchHistory.getSearchHistory(this.searchArea); } /** diff --git a/src/core/features/search/services/search-history.service.ts b/src/core/features/search/services/search-history.service.ts index 32600c206..7cc77a5f3 100644 --- a/src/core/features/search/services/search-history.service.ts +++ b/src/core/features/search/services/search-history.service.ts @@ -35,7 +35,7 @@ export class CoreSearchHistoryProvider { * @return Promise resolved with the list of items when done. */ async getSearchHistory(searchArea: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const conditions = { searcharea: searchArea, }; @@ -106,7 +106,7 @@ export class CoreSearchHistoryProvider { * @return Resolved when done. */ async insertOrUpdateSearchText(searchArea: string, text: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const db = site.getDb(); const exists = await this.updateExistingItem(searchArea, text, db); @@ -128,4 +128,4 @@ export class CoreSearchHistoryProvider { } -export class CoreSearchHistory extends makeSingleton(CoreSearchHistoryProvider) {} +export const CoreSearchHistory = makeSingleton(CoreSearchHistoryProvider); diff --git a/src/core/features/settings/pages/about/about.ts b/src/core/features/settings/pages/about/about.ts index 9bf7daa68..8c84d858a 100644 --- a/src/core/features/settings/pages/about/about.ts +++ b/src/core/features/settings/pages/about/about.ts @@ -32,7 +32,7 @@ export class CoreSettingsAboutPage { privacyPolicy: string; constructor() { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); this.appName = CoreConstants.CONFIG.appname; this.versionName = CoreConstants.CONFIG.versionname; @@ -50,7 +50,7 @@ export class CoreSettingsAboutPage { openPage(page: string): void { // const navCtrl = this.svComponent ? this.svComponent.getMasterNav() : this.navCtrl; // navCtrl.push(page); - CoreNavigator.instance.navigate(page); + CoreNavigator.navigate(page); } } diff --git a/src/core/features/settings/pages/deviceinfo/deviceinfo.ts b/src/core/features/settings/pages/deviceinfo/deviceinfo.ts index e0ed13a45..889ed420e 100644 --- a/src/core/features/settings/pages/deviceinfo/deviceinfo.ts +++ b/src/core/features/settings/pages/deviceinfo/deviceinfo.ts @@ -86,8 +86,8 @@ export class CoreSettingsDeviceInfoPage implements OnDestroy { lastCommit: CoreConstants.BUILD.lastCommitHash || '', networkStatus: appProvider.isOnline() ? 'online' : 'offline', wifiConnection: appProvider.isWifi() ? 'yes' : 'no', - localNotifAvailable: CoreLocalNotifications.instance.isAvailable() ? 'yes' : 'no', - pushId: CorePushNotifications.instance.getPushId(), + localNotifAvailable: CoreLocalNotifications.isAvailable() ? 'yes' : 'no', + pushId: CorePushNotifications.getPushId(), deviceType: '', }; @@ -102,7 +102,7 @@ export class CoreSettingsDeviceInfoPage implements OnDestroy { } if (appProvider.isMobile()) { - this.deviceInfo.deviceType = Platform.instance.is('tablet') ? 'tablet' : 'phone'; + this.deviceInfo.deviceType = Platform.is('tablet') ? 'tablet' : 'phone'; if (appProvider.isAndroid()) { this.deviceInfo.deviceOs = 'android'; this.deviceOsTranslated = 'Android'; @@ -168,9 +168,9 @@ export class CoreSettingsDeviceInfoPage implements OnDestroy { this.deviceInfo.siteVersion = currentSite?.getInfo()?.release; // Refresh online status when changes. - this.onlineObserver = Network.instance.onChange().subscribe(() => { + this.onlineObserver = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { + NgZone.run(() => { this.deviceInfo!.networkStatus = appProvider.isOnline() ? 'online' : 'offline'; }); }); @@ -184,7 +184,7 @@ export class CoreSettingsDeviceInfoPage implements OnDestroy { protected async asyncInit(): Promise { const fileProvider = CoreFile.instance; - const lang = await CoreLang.instance.getCurrentLanguage(); + const lang = await CoreLang.getCurrentLanguage(); this.deviceInfo.currentLanguage = lang; this.currentLangName = CoreConstants.CONFIG.languages[lang]; @@ -199,7 +199,7 @@ export class CoreSettingsDeviceInfoPage implements OnDestroy { * Copies device info into the clipboard. */ copyInfo(): void { - CoreUtils.instance.copyToClipboard(JSON.stringify(this.deviceInfo)); + CoreUtils.copyToClipboard(JSON.stringify(this.deviceInfo)); } /** @@ -211,7 +211,7 @@ export class CoreSettingsDeviceInfoPage implements OnDestroy { const el = e.target; const text = el?.closest('ion-item')?.textContent?.trim(); - text && CoreUtils.instance.copyToClipboard(text); + text && CoreUtils.copyToClipboard(text); } /** diff --git a/src/core/features/settings/pages/general/general.ts b/src/core/features/settings/pages/general/general.ts index 3bcb997e8..593334158 100644 --- a/src/core/features/settings/pages/general/general.ts +++ b/src/core/features/settings/pages/general/general.ts @@ -62,11 +62,11 @@ export class CoreSettingsGeneralPage { } // Sort them by name. this.languages.sort((a, b) => a.name.localeCompare(b.name)); - this.selectedLanguage = await CoreLang.instance.getCurrentLanguage(); + this.selectedLanguage = await CoreLang.getCurrentLanguage(); // Configure color schemes. if (!CoreConstants.CONFIG.forceColorScheme) { - this.colorSchemeDisabled = CoreSettingsHelper.instance.isColorSchemeDisabledInSite(); + this.colorSchemeDisabled = CoreSettingsHelper.isColorSchemeDisabledInSite(); if (this.colorSchemeDisabled) { this.colorSchemes.push(CoreColorScheme.LIGHT); @@ -80,11 +80,11 @@ export class CoreSettingsGeneralPage { this.colorSchemes.push(CoreColorScheme.AUTO); } - this.selectedScheme = await CoreConfig.instance.get(CoreConstants.SETTINGS_COLOR_SCHEME, CoreColorScheme.LIGHT); + this.selectedScheme = await CoreConfig.get(CoreConstants.SETTINGS_COLOR_SCHEME, CoreColorScheme.LIGHT); } } - this.selectedFontSize = await CoreConfig.instance.get( + this.selectedFontSize = await CoreConfig.get( CoreConstants.SETTINGS_FONT_SIZE, CoreConstants.CONFIG.font_sizes[0], ); @@ -98,13 +98,13 @@ export class CoreSettingsGeneralPage { })); - this.richTextEditor = await CoreConfig.instance.get(CoreConstants.SETTINGS_RICH_TEXT_EDITOR, true); + this.richTextEditor = await CoreConfig.get(CoreConstants.SETTINGS_RICH_TEXT_EDITOR, true); - this.debugDisplay = await CoreConfig.instance.get(CoreConstants.SETTINGS_DEBUG_DISPLAY, false); + this.debugDisplay = await CoreConfig.get(CoreConstants.SETTINGS_DEBUG_DISPLAY, false); this.analyticsSupported = CoreConstants.CONFIG.enableanalytics; if (this.analyticsSupported) { - this.analyticsEnabled = await CoreConfig.instance.get(CoreConstants.SETTINGS_ANALYTICS_ENABLED, true); + this.analyticsEnabled = await CoreConfig.get(CoreConstants.SETTINGS_ANALYTICS_ENABLED, true); } } @@ -112,7 +112,7 @@ export class CoreSettingsGeneralPage { * Called when a new language is selected. */ languageChanged(): void { - CoreLang.instance.changeCurrentLanguage(this.selectedLanguage).finally(() => { + CoreLang.changeCurrentLanguage(this.selectedLanguage).finally(() => { CoreEvents.trigger(CoreEvents.LANGUAGE_CHANGED, this.selectedLanguage); }); } @@ -127,31 +127,31 @@ export class CoreSettingsGeneralPage { return fontSize; }); - CoreSettingsHelper.instance.setFontSize(this.selectedFontSize); - CoreConfig.instance.set(CoreConstants.SETTINGS_FONT_SIZE, this.selectedFontSize); + CoreSettingsHelper.setFontSize(this.selectedFontSize); + CoreConfig.set(CoreConstants.SETTINGS_FONT_SIZE, this.selectedFontSize); } /** * Called when a new color scheme is selected. */ colorSchemeChanged(): void { - CoreSettingsHelper.instance.setColorScheme(this.selectedScheme); - CoreConfig.instance.set(CoreConstants.SETTINGS_COLOR_SCHEME, this.selectedScheme); + CoreSettingsHelper.setColorScheme(this.selectedScheme); + CoreConfig.set(CoreConstants.SETTINGS_COLOR_SCHEME, this.selectedScheme); } /** * Called when the rich text editor is enabled or disabled. */ richTextEditorChanged(): void { - CoreConfig.instance.set(CoreConstants.SETTINGS_RICH_TEXT_EDITOR, this.richTextEditor ? 1 : 0); + CoreConfig.set(CoreConstants.SETTINGS_RICH_TEXT_EDITOR, this.richTextEditor ? 1 : 0); } /** * Called when the debug display setting is enabled or disabled. */ debugDisplayChanged(): void { - CoreConfig.instance.set(CoreConstants.SETTINGS_DEBUG_DISPLAY, this.debugDisplay ? 1 : 0); - CoreDomUtils.instance.setDebugDisplay(this.debugDisplay); + CoreConfig.set(CoreConstants.SETTINGS_DEBUG_DISPLAY, this.debugDisplay ? 1 : 0); + CoreDomUtils.setDebugDisplay(this.debugDisplay); } /** @@ -160,9 +160,9 @@ export class CoreSettingsGeneralPage { * @todo */ async analyticsEnabledChanged(): Promise { - await CorePushNotifications.instance.enableAnalytics(this.analyticsEnabled); + await CorePushNotifications.enableAnalytics(this.analyticsEnabled); - CoreConfig.instance.set(CoreConstants.SETTINGS_ANALYTICS_ENABLED, this.analyticsEnabled ? 1 : 0); + CoreConfig.set(CoreConstants.SETTINGS_ANALYTICS_ENABLED, this.analyticsEnabled ? 1 : 0); } } diff --git a/src/core/features/settings/pages/licenses/licenses.ts b/src/core/features/settings/pages/licenses/licenses.ts index b1c066302..fa7830aff 100644 --- a/src/core/features/settings/pages/licenses/licenses.ts +++ b/src/core/features/settings/pages/licenses/licenses.ts @@ -59,7 +59,7 @@ export class CoreSettingsLicensesPage implements OnInit { */ async ngOnInit(): Promise { try { - const licenses = await Http.instance.get(this.licensesUrl).toPromise(); + const licenses = await Http.get(this.licensesUrl).toPromise(); this.licenses = Object.keys(licenses).map((name) => { const license = licenses[name]; diff --git a/src/core/features/settings/pages/site/site.ts b/src/core/features/settings/pages/site/site.ts index 6631bba08..bfed21cdc 100644 --- a/src/core/features/settings/pages/site/site.ts +++ b/src/core/features/settings/pages/site/site.ts @@ -57,8 +57,8 @@ export class CoreSitePreferencesPage implements OnInit, OnDestroy { constructor() { - this.isIOS = CoreApp.instance.isIOS(); - this.siteId = CoreSites.instance.getCurrentSiteId(); + this.isIOS = CoreApp.isIOS(); + this.siteId = CoreSites.getCurrentSiteId(); this.sitesObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, (data: CoreEventSiteUpdatedData) => { if (data.siteId == this.siteId) { @@ -78,7 +78,7 @@ export class CoreSitePreferencesPage implements OnInit, OnDestroy { if (this.selectedPage) { this.openHandler(this.selectedPage); - } else if (CoreScreen.instance.isTablet) { + } else if (CoreScreen.isTablet) { if (this.isIOS) { // @todo // this.openHandler('CoreSharedFilesListPage', { manage: true, siteId: this.siteId, hideSitePicker: true }); @@ -93,16 +93,16 @@ export class CoreSitePreferencesPage implements OnInit, OnDestroy { * Fetch Data. */ protected async fetchData(): Promise { - this.handlers = CoreSettingsDelegate.instance.getHandlers(); + this.handlers = CoreSettingsDelegate.getHandlers(); - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); this.siteInfo = currentSite!.getInfo(); this.siteName = currentSite!.getSiteName(); this.siteUrl = currentSite!.getURL(); const promises: Promise[] = []; - promises.push(CoreSettingsHelper.instance.getSiteSpaceUsage(this.siteId) + promises.push(CoreSettingsHelper.getSiteSpaceUsage(this.siteId) .then((spaceUsage) => { this.spaceUsage = spaceUsage; @@ -110,7 +110,7 @@ export class CoreSitePreferencesPage implements OnInit, OnDestroy { })); /* if (this.isIOS) { - promises.push(CoreSharedFiles.instance.getSiteSharedFiles(this.siteId) + promises.push(CoreSharedFiles.getSiteSharedFiles(this.siteId) .then((files) => { this.iosSharedFiles = files.length; @@ -127,12 +127,12 @@ export class CoreSitePreferencesPage implements OnInit, OnDestroy { async synchronize(): Promise { try { // Using syncOnlyOnWifi false to force manual sync. - await CoreSettingsHelper.instance.synchronizeSite(false, this.siteId); + await CoreSettingsHelper.synchronizeSite(false, this.siteId); } catch (error) { if (this.isDestroyed) { return; } - CoreDomUtils.instance.showErrorModalDefault(error, 'core.settings.errorsyncsite', true); + CoreDomUtils.showErrorModalDefault(error, 'core.settings.errorsyncsite', true); } } @@ -143,7 +143,7 @@ export class CoreSitePreferencesPage implements OnInit, OnDestroy { * @return True if site is beeing synchronized, false otherwise. */ isSynchronizing(): boolean { - return !!CoreSettingsHelper.instance.getSiteSyncPromise(this.siteId); + return !!CoreSettingsHelper.getSiteSyncPromise(this.siteId); } /** @@ -164,7 +164,7 @@ export class CoreSitePreferencesPage implements OnInit, OnDestroy { */ async deleteSiteStorage(): Promise { try { - this.spaceUsage = await CoreSettingsHelper.instance.deleteSiteStorage(this.siteName || '', this.siteId); + this.spaceUsage = await CoreSettingsHelper.deleteSiteStorage(this.siteName || '', this.siteId); } catch { // Ignore cancelled confirmation modal. } @@ -179,16 +179,16 @@ export class CoreSitePreferencesPage implements OnInit, OnDestroy { openHandler(page: string, params?: Params): void { this.selectedPage = page; // this.splitviewCtrl.push(page, params); - CoreNavigator.instance.navigateToSitePath(page, { params }); + CoreNavigator.navigateToSitePath(page, { params }); } /** * Show information about space usage actions. */ showSpaceInfo(): void { - CoreDomUtils.instance.showAlert( - Translate.instance.instant('core.help'), - Translate.instance.instant('core.settings.spaceusagehelp'), + CoreDomUtils.showAlert( + Translate.instant('core.help'), + Translate.instant('core.settings.spaceusagehelp'), ); } @@ -196,9 +196,9 @@ export class CoreSitePreferencesPage implements OnInit, OnDestroy { * Show information about sync actions. */ showSyncInfo(): void { - CoreDomUtils.instance.showAlert( - Translate.instance.instant('core.help'), - Translate.instance.instant('core.settings.synchronizenowhelp'), + CoreDomUtils.showAlert( + Translate.instant('core.help'), + Translate.instant('core.settings.synchronizenowhelp'), ); } diff --git a/src/core/features/settings/pages/space-usage/space-usage.ts b/src/core/features/settings/pages/space-usage/space-usage.ts index 7a1ae657d..f214e0d70 100644 --- a/src/core/features/settings/pages/space-usage/space-usage.ts +++ b/src/core/features/settings/pages/space-usage/space-usage.ts @@ -42,10 +42,10 @@ export class CoreSettingsSpaceUsagePage implements OnInit, OnDestroy { protected sitesObserver: CoreEventObserver; constructor() { - this.currentSiteId = CoreSites.instance.getCurrentSiteId(); + this.currentSiteId = CoreSites.getCurrentSiteId(); this.sitesObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, async (data: CoreEventSiteUpdatedData) => { - const site = await CoreSites.instance.getSite(data.siteId); + const site = await CoreSites.getSite(data.siteId); const siteEntry = this.sites.find((siteEntry) => siteEntry.id == site.id); if (siteEntry) { @@ -80,7 +80,7 @@ export class CoreSettingsSpaceUsagePage implements OnInit, OnDestroy { let totalSize = 0; let totalEntries = 0; - this.sites = await CoreSites.instance.getSortedSites(); + this.sites = await CoreSites.getSortedSites(); const settingsHelper = CoreSettingsHelper.instance; @@ -117,7 +117,7 @@ export class CoreSettingsSpaceUsagePage implements OnInit, OnDestroy { */ async deleteSiteStorage(siteData: CoreSiteBasicInfoWithUsage): Promise { try { - const newInfo = await CoreSettingsHelper.instance.deleteSiteStorage(siteData.siteName || '', siteData.id); + const newInfo = await CoreSettingsHelper.deleteSiteStorage(siteData.siteName || '', siteData.id); this.totals.spaceUsage -= siteData.spaceUsage! - newInfo.spaceUsage; this.totals.spaceUsage -= siteData.cacheEntries! - newInfo.cacheEntries; @@ -133,9 +133,9 @@ export class CoreSettingsSpaceUsagePage implements OnInit, OnDestroy { * Show information about space usage actions. */ showInfo(): void { - CoreDomUtils.instance.showAlert( - Translate.instance.instant('core.help'), - Translate.instance.instant('core.settings.spaceusagehelp'), + CoreDomUtils.showAlert( + Translate.instant('core.help'), + Translate.instant('core.settings.spaceusagehelp'), ); } diff --git a/src/core/features/settings/pages/synchronization/synchronization.ts b/src/core/features/settings/pages/synchronization/synchronization.ts index a154d80bb..e55125c35 100644 --- a/src/core/features/settings/pages/synchronization/synchronization.ts +++ b/src/core/features/settings/pages/synchronization/synchronization.ts @@ -40,10 +40,10 @@ export class CoreSettingsSynchronizationPage implements OnInit, OnDestroy { constructor() { - this.currentSiteId = CoreSites.instance.getCurrentSiteId(); + this.currentSiteId = CoreSites.getCurrentSiteId(); this.sitesObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, async (data: CoreEventSiteUpdatedData) => { - const site = await CoreSites.instance.getSite(data.siteId); + const site = await CoreSites.getSite(data.siteId); const siteEntry = this.sites.find((siteEntry) => siteEntry.id == site.id); if (siteEntry) { @@ -64,21 +64,21 @@ export class CoreSettingsSynchronizationPage implements OnInit, OnDestroy { */ async ngOnInit(): Promise { try { - this.sites = await CoreSites.instance.getSortedSites(); + this.sites = await CoreSites.getSortedSites(); } catch { // Ignore errors. } this.sitesLoaded = true; - this.syncOnlyOnWifi = await CoreConfig.instance.get(CoreConstants.SETTINGS_SYNC_ONLY_ON_WIFI, true); + this.syncOnlyOnWifi = await CoreConfig.get(CoreConstants.SETTINGS_SYNC_ONLY_ON_WIFI, true); } /** * Called when sync only on wifi setting is enabled or disabled. */ syncOnlyOnWifiChanged(): void { - CoreConfig.instance.set(CoreConstants.SETTINGS_SYNC_ONLY_ON_WIFI, this.syncOnlyOnWifi ? 1 : 0); + CoreConfig.set(CoreConstants.SETTINGS_SYNC_ONLY_ON_WIFI, this.syncOnlyOnWifi ? 1 : 0); } /** @@ -89,13 +89,13 @@ export class CoreSettingsSynchronizationPage implements OnInit, OnDestroy { async synchronize(siteId: string): Promise { // Using syncOnlyOnWifi false to force manual sync. try { - await CoreSettingsHelper.instance.synchronizeSite(false, siteId); + await CoreSettingsHelper.synchronizeSite(false, siteId); } catch (error) { if (this.isDestroyed) { return; } - CoreDomUtils.instance.showErrorModalDefault(error, 'core.settings.errorsyncsite', true); + CoreDomUtils.showErrorModalDefault(error, 'core.settings.errorsyncsite', true); } } @@ -106,16 +106,16 @@ export class CoreSettingsSynchronizationPage implements OnInit, OnDestroy { * @return True if site is beeing synchronized, false otherwise. */ isSynchronizing(siteId: string): boolean { - return !!CoreSettingsHelper.instance.getSiteSyncPromise(siteId); + return !!CoreSettingsHelper.getSiteSyncPromise(siteId); } /** * Show information about sync actions. */ showInfo(): void { - CoreDomUtils.instance.showAlert( - Translate.instance.instant('core.help'), - Translate.instance.instant('core.settings.synchronizenowhelp'), + CoreDomUtils.showAlert( + Translate.instant('core.help'), + Translate.instant('core.settings.synchronizenowhelp'), ); } diff --git a/src/core/features/settings/services/settings-delegate.ts b/src/core/features/settings/services/settings-delegate.ts index c708ad16e..2d0d10fae 100644 --- a/src/core/features/settings/services/settings-delegate.ts +++ b/src/core/features/settings/services/settings-delegate.ts @@ -72,4 +72,4 @@ export class CoreSettingsDelegateService extends CoreSortedDelegate[] = cleanSchemas.map((name) => site.getDb().deleteRecords(name)); const filepoolService = CoreFilepool.instance; @@ -110,7 +110,7 @@ export class CoreSettingsHelperProvider { promises.push(site.deleteFolder().then(() => { filepoolService.clearAllPackagesStatus(siteId); filepoolService.clearFilepool(siteId); - CoreCourse.instance.clearAllCoursesStatus(siteId); + CoreCourse.clearAllCoursesStatus(siteId); siteInfo.spaceUsage = 0; @@ -122,7 +122,7 @@ export class CoreSettingsHelperProvider { siteInfo.spaceUsage = 0; } else { // Error, recalculate the site usage. - CoreDomUtils.instance.showErrorModal('core.settings.errordeletesitefiles', true); + CoreDomUtils.showErrorModal('core.settings.errordeletesitefiles', true); siteInfo.spaceUsage = await site.getSpaceUsage(); } @@ -146,7 +146,7 @@ export class CoreSettingsHelperProvider { * @return Resolved with detailed info when done. */ async getSiteSpaceUsage(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Get space usage. const siteInfo: CoreSiteSpaceUsage = { @@ -167,7 +167,7 @@ export class CoreSettingsHelperProvider { * @return If there are rows to delete or not. */ protected async calcSiteClearRows(site: CoreSite): Promise { - const clearTables = CoreSites.instance.getSiteTableSchemasToClear(site); + const clearTables = CoreSites.getSiteTableSchemasToClear(site); let totalEntries = 0; @@ -228,27 +228,27 @@ export class CoreSettingsHelperProvider { return this.syncPromises[siteId]; } - const site = await CoreSites.instance.getSite(siteId); - const hasSyncHandlers = CoreCronDelegate.instance.hasManualSyncHandlers(); + const site = await CoreSites.getSite(siteId); + const hasSyncHandlers = CoreCronDelegate.hasManualSyncHandlers(); if (site.isLoggedOut()) { // Cannot sync logged out sites. - throw new CoreError(Translate.instance.instant('core.settings.cannotsyncloggedout')); - } else if (hasSyncHandlers && !CoreApp.instance.isOnline()) { + throw new CoreError(Translate.instant('core.settings.cannotsyncloggedout')); + } else if (hasSyncHandlers && !CoreApp.isOnline()) { // We need connection to execute sync. - throw new CoreError(Translate.instance.instant('core.settings.cannotsyncoffline')); - } else if (hasSyncHandlers && syncOnlyOnWifi && CoreApp.instance.isNetworkAccessLimited()) { - throw new CoreError(Translate.instance.instant('core.settings.cannotsyncwithoutwifi')); + throw new CoreError(Translate.instant('core.settings.cannotsyncoffline')); + } else if (hasSyncHandlers && syncOnlyOnWifi && CoreApp.isNetworkAccessLimited()) { + throw new CoreError(Translate.instant('core.settings.cannotsyncwithoutwifi')); } const syncPromise = Promise.all([ // Invalidate all the site files so they are re-downloaded. - CoreUtils.instance.ignoreErrors(CoreFilepool.instance.invalidateAllFiles(siteId)), + CoreUtils.ignoreErrors(CoreFilepool.invalidateAllFiles(siteId)), // Invalidate and synchronize site data. site.invalidateWsCache(), this.checkSiteLocalMobile(site), - CoreSites.instance.updateSiteInfo(site.getId()), - CoreCronDelegate.instance.forceSyncExecution(site.getId()), + CoreSites.updateSiteInfo(site.getId()), + CoreCronDelegate.forceSyncExecution(site.getId()), // eslint-disable-next-line arrow-body-style ]).then(() => { return; @@ -281,7 +281,7 @@ export class CoreSettingsHelperProvider { // Local mobile was added. Throw invalid session to force reconnect and create a new token. CoreEvents.trigger(CoreEvents.SESSION_EXPIRED, {}, site.getId()); - throw new CoreError(Translate.instance.instant('core.lostconnection')); + throw new CoreError(Translate.instant('core.lostconnection')); } /** @@ -289,7 +289,7 @@ export class CoreSettingsHelperProvider { */ async initDomSettings(): Promise { // Set the font size based on user preference. - const fontSize = await CoreConfig.instance.get(CoreConstants.SETTINGS_FONT_SIZE, CoreConstants.CONFIG.font_sizes[0]); + const fontSize = await CoreConfig.get(CoreConstants.SETTINGS_FONT_SIZE, CoreConstants.CONFIG.font_sizes[0]); this.setFontSize(fontSize); this.initColorScheme(); @@ -302,7 +302,7 @@ export class CoreSettingsHelperProvider { if (CoreConstants.CONFIG.forceColorScheme) { this.setColorScheme(CoreConstants.CONFIG.forceColorScheme); } else { - const scheme = await CoreConfig.instance.get(CoreConstants.SETTINGS_COLOR_SCHEME, CoreColorScheme.LIGHT); + const scheme = await CoreConfig.get(CoreConstants.SETTINGS_COLOR_SCHEME, CoreColorScheme.LIGHT); this.setColorScheme(scheme); } } @@ -314,7 +314,7 @@ export class CoreSettingsHelperProvider { * @return Promise resolved with whether color scheme is disabled. */ async isColorSchemeDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isColorSchemeDisabledInSite(site); } @@ -326,7 +326,7 @@ export class CoreSettingsHelperProvider { * @return Whether color scheme is disabled. */ isColorSchemeDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return site ? site.isFeatureDisabled('NoDelegate_DarkMode') : false; } @@ -380,4 +380,4 @@ export class CoreSettingsHelperProvider { } -export class CoreSettingsHelper extends makeSingleton(CoreSettingsHelperProvider) {} +export const CoreSettingsHelper = makeSingleton(CoreSettingsHelperProvider); diff --git a/src/core/features/settings/settings-lazy.module.ts b/src/core/features/settings/settings-lazy.module.ts index 1a8f6d517..e5589cebb 100644 --- a/src/core/features/settings/settings-lazy.module.ts +++ b/src/core/features/settings/settings-lazy.module.ts @@ -67,8 +67,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), { path: 'about/deviceinfo', loadChildren: () => import('./pages/deviceinfo/deviceinfo.module').then(m => m.CoreSettingsDeviceInfoPageModule), diff --git a/src/core/features/sitehome/pages/index/index.ts b/src/core/features/sitehome/pages/index/index.ts index b70d4b024..34b227618 100644 --- a/src/core/features/sitehome/pages/index/index.ts +++ b/src/core/features/sitehome/pages/index/index.ts @@ -62,26 +62,26 @@ export class CoreSiteHomeIndexPage implements OnInit, OnDestroy { * Page being initialized. */ ngOnInit(): void { - this.searchEnabled = !CoreCourses.instance.isSearchCoursesDisabledInSite(); - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.searchEnabled = !CoreCourses.isSearchCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); // Refresh the enabled flags if site is updated. this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { - this.searchEnabled = !CoreCourses.instance.isSearchCoursesDisabledInSite(); - this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); - this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); + this.searchEnabled = !CoreCourses.isSearchCoursesDisabledInSite(); + this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite(); + this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite(); this.switchDownload(this.downloadEnabled && this.downloadCourseEnabled && this.downloadCoursesEnabled); - }, CoreSites.instance.getCurrentSiteId()); + }, CoreSites.getCurrentSiteId()); - this.currentSite = CoreSites.instance.getCurrentSite()!; - this.siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); + this.currentSite = CoreSites.getCurrentSite()!; + this.siteHomeId = CoreSites.getCurrentSiteHomeId(); - const module = CoreNavigator.instance.getRouteParam('module'); + const module = CoreNavigator.getRouteParam('module'); if (module) { - const modParams = CoreNavigator.instance.getRouteParam('modParams'); - CoreCourseHelper.instance.openModule(module, this.siteHomeId, undefined, modParams); + const modParams = CoreNavigator.getRouteParam('modParams'); + CoreCourseHelper.openModule(module, this.siteHomeId, undefined, modParams); } this.loadContent().finally(() => { @@ -99,15 +99,15 @@ export class CoreSiteHomeIndexPage implements OnInit, OnDestroy { const config = this.currentSite!.getStoredConfig() || { numsections: 1, frontpageloggedin: undefined }; - this.items = await CoreSiteHome.instance.getFrontPageItems(config.frontpageloggedin); + this.items = await CoreSiteHome.getFrontPageItems(config.frontpageloggedin); this.hasContent = this.items.length > 0; if (this.items.some((item) => item == 'NEWS_ITEMS')) { // Get the news forum. try { - const forum = await CoreSiteHome.instance.getNewsForum(); - this.newsForumModule = await CoreCourse.instance.getModuleBasicInfo(forum.cmid); - this.newsForumModule.handlerData = CoreCourseModuleDelegate.instance.getModuleDataFor( + const forum = await CoreSiteHome.getNewsForum(); + this.newsForumModule = await CoreCourse.getModuleBasicInfo(forum.cmid); + this.newsForumModule.handlerData = CoreCourseModuleDelegate.getModuleDataFor( this.newsForumModule.modname, this.newsForumModule, this.siteHomeId, @@ -120,12 +120,12 @@ export class CoreSiteHomeIndexPage implements OnInit, OnDestroy { } try { - const sections = await CoreCourse.instance.getSections(this.siteHomeId!, false, true); + const sections = await CoreCourse.getSections(this.siteHomeId!, false, true); // Check "Include a topic section" setting from numsections. this.section = config.numsections ? sections.find((section) => section.section == 1) : undefined; if (this.section) { - const result = CoreCourseHelper.instance.addHandlerDataForModules( + const result = CoreCourseHelper.addHandlerDataForModules( [this.section], this.siteHomeId, undefined, @@ -136,7 +136,7 @@ export class CoreSiteHomeIndexPage implements OnInit, OnDestroy { } // Add log in Moodle. - CoreCourse.instance.logView( + CoreCourse.logView( this.siteHomeId!, undefined, undefined, @@ -145,7 +145,7 @@ export class CoreSiteHomeIndexPage implements OnInit, OnDestroy { // Ignore errors. }); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.couldnotloadsectioncontent', true); + CoreDomUtils.showErrorModalDefault(error, 'core.course.couldnotloadsectioncontent', true); } } @@ -157,7 +157,7 @@ export class CoreSiteHomeIndexPage implements OnInit, OnDestroy { doRefresh(refresher?: CustomEvent): void { const promises: Promise[] = []; - promises.push(CoreCourse.instance.invalidateSections(this.siteHomeId!)); + promises.push(CoreCourse.invalidateSections(this.siteHomeId!)); promises.push(this.currentSite!.invalidateConfig().then(async () => { // Config invalidated, fetch it again. const config: CoreSiteConfig = await this.currentSite!.getConfig(); @@ -168,7 +168,7 @@ export class CoreSiteHomeIndexPage implements OnInit, OnDestroy { if (this.section && this.section.modules) { // Invalidate modules prefetch data. - promises.push(CoreCourseModulePrefetchDelegate.instance.invalidateModules(this.section.modules, this.siteHomeId)); + promises.push(CoreCourseModulePrefetchDelegate.invalidateModules(this.section.modules, this.siteHomeId)); } if (this.courseBlocksComponent) { @@ -218,7 +218,7 @@ export class CoreSiteHomeIndexPage implements OnInit, OnDestroy { * Go to search courses. */ openSearch(): void { - CoreNavigator.instance.navigateToSitePath('courses/search'); + CoreNavigator.navigateToSitePath('courses/search'); } /** diff --git a/src/core/features/sitehome/services/handlers/index-link.ts b/src/core/features/sitehome/services/handlers/index-link.ts index 1bde3303e..fbc73a2f0 100644 --- a/src/core/features/sitehome/services/handlers/index-link.ts +++ b/src/core/features/sitehome/services/handlers/index-link.ts @@ -44,7 +44,7 @@ export class CoreSiteHomeIndexLinkHandlerService extends CoreContentLinksHandler return [{ action: (siteId: string): void => { // @todo This should open the 'sitehome' setting as well. - CoreNavigator.instance.navigateToSiteHome({ siteId }); + CoreNavigator.navigateToSiteHome({ siteId }); }, }]; } @@ -65,15 +65,15 @@ export class CoreSiteHomeIndexLinkHandlerService extends CoreContentLinksHandler return false; } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (courseId != site.getSiteHomeId()) { // The course is not site home. return false; } - return CoreSiteHome.instance.isAvailable(siteId).then(() => true).catch(() => false); + return CoreSiteHome.isAvailable(siteId).then(() => true).catch(() => false); } } -export class CoreSiteHomeIndexLinkHandler extends makeSingleton(CoreSiteHomeIndexLinkHandlerService) {} +export const CoreSiteHomeIndexLinkHandler = makeSingleton(CoreSiteHomeIndexLinkHandlerService); diff --git a/src/core/features/sitehome/services/handlers/sitehome-home.ts b/src/core/features/sitehome/services/handlers/sitehome-home.ts index 96b64d941..f5866cda7 100644 --- a/src/core/features/sitehome/services/handlers/sitehome-home.ts +++ b/src/core/features/sitehome/services/handlers/sitehome-home.ts @@ -45,7 +45,7 @@ export class CoreSiteHomeHomeHandlerService implements CoreMainMenuHomeHandler { * @return Whether or not the handler is enabled on a site level. */ async isEnabledForSite(siteId?: string): Promise { - return CoreSiteHome.instance.isAvailable(siteId); + return CoreSiteHome.isAvailable(siteId); } /** @@ -54,7 +54,7 @@ export class CoreSiteHomeHomeHandlerService implements CoreMainMenuHomeHandler { * @return Data needed to render the handler. */ getDisplayData(): CoreMainMenuHomeHandlerToDisplay { - const site = CoreSites.instance.getCurrentSite(); + const site = CoreSites.getCurrentSite(); const displaySiteHome = site?.getInfo() && site?.getInfo()?.userhomepage === 0; return { @@ -68,4 +68,4 @@ export class CoreSiteHomeHomeHandlerService implements CoreMainMenuHomeHandler { } -export class CoreSiteHomeHomeHandler extends makeSingleton(CoreSiteHomeHomeHandlerService) {} +export const CoreSiteHomeHomeHandler = makeSingleton(CoreSiteHomeHomeHandlerService); diff --git a/src/core/features/sitehome/services/sitehome.ts b/src/core/features/sitehome/services/sitehome.ts index 85c75ba51..ae359b2f2 100644 --- a/src/core/features/sitehome/services/sitehome.ts +++ b/src/core/features/sitehome/services/sitehome.ts @@ -47,10 +47,10 @@ export class CoreSiteHomeProvider { */ async getNewsForum(siteHomeId?: number): Promise { if (!siteHomeId) { - siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); + siteHomeId = CoreSites.getCurrentSiteHomeId(); } - const forums = await AddonModForum.instance.getCourseForums(siteHomeId); + const forums = await AddonModForum.getCourseForums(siteHomeId); const forum = forums.find((forum) => forum.type == 'news'); if (forum) { @@ -67,7 +67,7 @@ export class CoreSiteHomeProvider { * @return Promise resolved when invalidated. */ async invalidateNewsForum(siteHomeId: number): Promise { - await AddonModForum.instance.invalidateForumData(siteHomeId); + await AddonModForum.invalidateForumData(siteHomeId); } /** @@ -78,7 +78,7 @@ export class CoreSiteHomeProvider { */ async isAvailable(siteId?: string): Promise { try { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // First check if it's disabled. if (this.isDisabledInSite(site)) { @@ -90,7 +90,7 @@ export class CoreSiteHomeProvider { const preSets: CoreSiteWSPreSets = { emergencyCache: false }; try { - const sections = await CoreCourse.instance.getSections(siteHomeId, false, true, preSets, site.id); + const sections = await CoreCourse.getSections(siteHomeId, false, true, preSets, site.id); if (!sections || !sections.length) { throw Error('No sections found'); @@ -127,7 +127,7 @@ export class CoreSiteHomeProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isDisabledInSite(site); } @@ -139,7 +139,7 @@ export class CoreSiteHomeProvider { * @return Whether it's disabled. */ isDisabledInSite(site: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return site.isFeatureDisabled('CoreMainMenuDelegate_CoreSiteHome'); } @@ -166,25 +166,25 @@ export class CoreSiteHomeProvider { switch (itemNumber) { case FrontPageItemNames['NEWS_ITEMS']: // Get number of news items to show. - add = !!CoreSites.instance.getCurrentSite()?.getStoredConfig('newsitems'); + add = !!CoreSites.getCurrentSite()?.getStoredConfig('newsitems'); break; case FrontPageItemNames['LIST_OF_CATEGORIES']: case FrontPageItemNames['COMBO_LIST']: case FrontPageItemNames['LIST_OF_COURSE']: - add = CoreCourses.instance.isGetCoursesByFieldAvailable(); + add = CoreCourses.isGetCoursesByFieldAvailable(); if (add && itemNumber == FrontPageItemNames['COMBO_LIST']) { itemNumber = FrontPageItemNames['LIST_OF_CATEGORIES']; } break; case FrontPageItemNames['ENROLLED_COURSES']: - if (!CoreCourses.instance.isMyCoursesDisabledInSite()) { - const courses = await CoreCourses.instance.getUserCourses(); + if (!CoreCourses.isMyCoursesDisabledInSite()) { + const courses = await CoreCourses.getUserCourses(); add = courses.length > 0; } break; case FrontPageItemNames['COURSE_SEARCH_BOX']: - add = !CoreCourses.instance.isSearchCoursesDisabledInSite(); + add = !CoreCourses.isSearchCoursesDisabledInSite(); break; default: break; @@ -201,4 +201,4 @@ export class CoreSiteHomeProvider { } -export class CoreSiteHome extends makeSingleton(CoreSiteHomeProvider) {} +export const CoreSiteHome = makeSingleton(CoreSiteHomeProvider); diff --git a/src/core/features/sitehome/sitehome.module.ts b/src/core/features/sitehome/sitehome.module.ts index b302ff2d8..0b80ab422 100644 --- a/src/core/features/sitehome/sitehome.module.ts +++ b/src/core/features/sitehome/sitehome.module.ts @@ -37,8 +37,8 @@ const mainMenuHomeRoutes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreContentLinksDelegate.instance.registerHandler(CoreSiteHomeIndexLinkHandler.instance); - CoreMainMenuHomeDelegate.instance.registerHandler(CoreSiteHomeHomeHandler.instance); + CoreContentLinksDelegate.registerHandler(CoreSiteHomeIndexLinkHandler.instance); + CoreMainMenuHomeDelegate.registerHandler(CoreSiteHomeHomeHandler.instance); }, }, ], diff --git a/src/core/features/tag/components/list/list.ts b/src/core/features/tag/components/list/list.ts index 23dac9ccf..dfcdcb931 100644 --- a/src/core/features/tag/components/list/list.ts +++ b/src/core/features/tag/components/list/list.ts @@ -41,7 +41,7 @@ export class CoreTagListComponent { }; // @todo: Check split view to navigate on the outlet if any. - CoreNavigator.instance.navigateToSitePath('/tag/index', { params, preferCurrentTab: false }); + CoreNavigator.navigateToSitePath('/tag/index', { params, preferCurrentTab: false }); } } diff --git a/src/core/features/tag/pages/index-area/index-area.page.ts b/src/core/features/tag/pages/index-area/index-area.page.ts index c57826de4..d8a1693ee 100644 --- a/src/core/features/tag/pages/index-area/index-area.page.ts +++ b/src/core/features/tag/pages/index-area/index-area.page.ts @@ -61,28 +61,28 @@ export class CoreTagIndexAreaPage implements OnInit { this.route.queryParams.subscribe(async () => { this.loaded = false; - this.tagId = CoreNavigator.instance.getRouteNumberParam('tagId') || this.tagId; - this.tagName = CoreNavigator.instance.getRouteParam('tagName') || this.tagName; - this.collectionId = CoreNavigator.instance.getRouteNumberParam('collectionId') || this.collectionId; - this.areaId = CoreNavigator.instance.getRouteNumberParam('areaId') || this.areaId; - this.fromContextId = CoreNavigator.instance.getRouteNumberParam('fromContextId') || this.fromContextId; - this.contextId = CoreNavigator.instance.getRouteNumberParam('contextId') || this.contextId; - this.recursive = CoreNavigator.instance.getRouteBooleanParam('recursive') ?? true; + this.tagId = CoreNavigator.getRouteNumberParam('tagId') || this.tagId; + this.tagName = CoreNavigator.getRouteParam('tagName') || this.tagName; + this.collectionId = CoreNavigator.getRouteNumberParam('collectionId') || this.collectionId; + this.areaId = CoreNavigator.getRouteNumberParam('areaId') || this.areaId; + this.fromContextId = CoreNavigator.getRouteNumberParam('fromContextId') || this.fromContextId; + this.contextId = CoreNavigator.getRouteNumberParam('contextId') || this.contextId; + this.recursive = CoreNavigator.getRouteBooleanParam('recursive') ?? true; - this.areaNameKey = CoreNavigator.instance.getRouteParam('areaNameKey') || ''; + this.areaNameKey = CoreNavigator.getRouteParam('areaNameKey') || ''; // Pass the the following parameters to avoid fetching the first page. - this.componentName = CoreNavigator.instance.getRouteParam('componentName'); - this.itemType = CoreNavigator.instance.getRouteParam('itemType'); - this.items = CoreNavigator.instance.getRouteParam('items') || []; - this.nextPage = CoreNavigator.instance.getRouteNumberParam('nextPage') || 0; - this.canLoadMore = CoreNavigator.instance.getRouteBooleanParam('canLoadMore') || false; + this.componentName = CoreNavigator.getRouteParam('componentName'); + this.itemType = CoreNavigator.getRouteParam('itemType'); + this.items = CoreNavigator.getRouteParam('items') || []; + this.nextPage = CoreNavigator.getRouteNumberParam('nextPage') || 0; + this.canLoadMore = CoreNavigator.getRouteBooleanParam('canLoadMore') || false; try { if (!this.componentName || !this.itemType || !this.items.length || this.nextPage == 0) { await this.fetchData(true); } - this.areaComponent = await CoreTagAreaDelegate.instance.getComponent(this.componentName!, this.itemType!); + this.areaComponent = await CoreTagAreaDelegate.getComponent(this.componentName!, this.itemType!); } finally { this.loaded = true; } @@ -100,7 +100,7 @@ export class CoreTagIndexAreaPage implements OnInit { const page = refresh ? 0 : this.nextPage; try { - const areas = await CoreTag.instance.getTagIndexPerArea( + const areas = await CoreTag.getTagIndexPerArea( this.tagId, this.tagName, this.collectionId, @@ -112,10 +112,10 @@ export class CoreTagIndexAreaPage implements OnInit { ); const area = areas[0]; - const items = await CoreTagAreaDelegate.instance.parseContent(area.component, area.itemtype, area.content); + const items = await CoreTagAreaDelegate.parseContent(area.component, area.itemtype, area.content); if (!items || !items.length) { // Tag area not supported. - throw Translate.instance.instant('core.tag.errorareanotsupported'); + throw Translate.instant('core.tag.errorareanotsupported'); } if (page == 0) { @@ -125,12 +125,12 @@ export class CoreTagIndexAreaPage implements OnInit { } this.componentName = area.component; this.itemType = area.itemtype; - this.areaNameKey = CoreTagAreaDelegate.instance.getDisplayNameKey(area.component, area.itemtype); + this.areaNameKey = CoreTagAreaDelegate.getDisplayNameKey(area.component, area.itemtype); this.canLoadMore = !!area.nextpageurl; this.nextPage = page + 1; } catch (error) { this.loadMoreError = true; // Set to prevent infinite calls with infinite-loading. - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading tag index'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading tag index'); } } @@ -155,7 +155,7 @@ export class CoreTagIndexAreaPage implements OnInit { */ async refreshData(refresher?: CustomEvent): Promise { try { - await CoreTag.instance.invalidateTagIndexPerArea( + await CoreTag.invalidateTagIndexPerArea( this.tagId, this.tagName, this.collectionId, diff --git a/src/core/features/tag/pages/index/index.page.module.ts b/src/core/features/tag/pages/index/index.page.module.ts index 74d88d961..beb24c864 100644 --- a/src/core/features/tag/pages/index/index.page.module.ts +++ b/src/core/features/tag/pages/index/index.page.module.ts @@ -40,8 +40,8 @@ const tabletRoutes: Routes = [ ]; const routes: Routes = [ - ...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), - ...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), + ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile), + ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet), ]; @NgModule({ diff --git a/src/core/features/tag/pages/index/index.page.ts b/src/core/features/tag/pages/index/index.page.ts index f7fc03140..15f36f5a0 100644 --- a/src/core/features/tag/pages/index/index.page.ts +++ b/src/core/features/tag/pages/index/index.page.ts @@ -46,17 +46,17 @@ export class CoreTagIndexPage implements OnInit { * View loaded. */ async ngOnInit(): Promise { - this.tagId = CoreNavigator.instance.getRouteNumberParam('tagId') || this.tagId; - this.tagName = CoreNavigator.instance.getRouteParam('tagName') || this.tagName; - this.collectionId = CoreNavigator.instance.getRouteNumberParam('collectionId') || this.collectionId; - this.areaId = CoreNavigator.instance.getRouteNumberParam('areaId') || this.areaId; - this.fromContextId = CoreNavigator.instance.getRouteNumberParam('fromContextId') || this.fromContextId; - this.contextId = CoreNavigator.instance.getRouteNumberParam('contextId') || this.contextId; - this.recursive = CoreNavigator.instance.getRouteBooleanParam('recursive') ?? true; + this.tagId = CoreNavigator.getRouteNumberParam('tagId') || this.tagId; + this.tagName = CoreNavigator.getRouteParam('tagName') || this.tagName; + this.collectionId = CoreNavigator.getRouteNumberParam('collectionId') || this.collectionId; + this.areaId = CoreNavigator.getRouteNumberParam('areaId') || this.areaId; + this.fromContextId = CoreNavigator.getRouteNumberParam('fromContextId') || this.fromContextId; + this.contextId = CoreNavigator.getRouteNumberParam('contextId') || this.contextId; + this.recursive = CoreNavigator.getRouteBooleanParam('recursive') ?? true; try { await this.fetchData(); - if (CoreScreen.instance.isTablet && this.areas && this.areas.length > 0) { + if (CoreScreen.isTablet && this.areas && this.areas.length > 0) { const area = this.areas.find((area) => area.id == this.areaId); this.openArea(area || this.areas[0]); } @@ -72,7 +72,7 @@ export class CoreTagIndexPage implements OnInit { */ async fetchData(): Promise { try { - const areas = await CoreTag.instance.getTagIndexPerArea( + const areas = await CoreTag.getTagIndexPerArea( this.tagId, this.tagName, this.collectionId, @@ -89,7 +89,7 @@ export class CoreTagIndexPage implements OnInit { const areasDisplay: CoreTagAreaDisplay[] = []; await Promise.all(areas.map(async (area) => { - const items = await CoreTagAreaDelegate.instance.parseContent(area.component, area.itemtype, area.content); + const items = await CoreTagAreaDelegate.parseContent(area.component, area.itemtype, area.content); if (!items || !items.length) { // Tag area not supported, skip. @@ -102,7 +102,7 @@ export class CoreTagIndexPage implements OnInit { id: area.ta, componentName: area.component, itemType: area.itemtype, - nameKey: CoreTagAreaDelegate.instance.getDisplayNameKey(area.component, area.itemtype), + nameKey: CoreTagAreaDelegate.getDisplayNameKey(area.component, area.itemtype), items, canLoadMore: !!area.nextpageurl, badge: items && items.length ? items.length + (area.nextpageurl ? '+' : '') : '', @@ -112,7 +112,7 @@ export class CoreTagIndexPage implements OnInit { this.areas = areasDisplay; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading tag index'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading tag index'); } } @@ -122,7 +122,7 @@ export class CoreTagIndexPage implements OnInit { * @param refresher Refresher. */ refreshData(refresher?: CustomEvent): void { - CoreTag.instance.invalidateTagIndexPerArea( + CoreTag.invalidateTagIndexPerArea( this.tagId, this.tagName, this.collectionId, @@ -161,10 +161,10 @@ export class CoreTagIndexPage implements OnInit { nextPage: 1, }; - const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/tag/index/index-area'); + const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/tag/index/index-area'); const path = (splitViewLoaded ? '../' : '') + 'index-area'; - CoreNavigator.instance.navigate(path, { params }); + CoreNavigator.navigate(path, { params }); } } diff --git a/src/core/features/tag/pages/search/search.page.ts b/src/core/features/tag/pages/search/search.page.ts index fd6459e69..fcd51cd88 100644 --- a/src/core/features/tag/pages/search/search.page.ts +++ b/src/core/features/tag/pages/search/search.page.ts @@ -45,8 +45,8 @@ export class CoreTagSearchPage implements OnInit { * View loaded. */ ngOnInit(): void { - this.collectionId = CoreNavigator.instance.getRouteNumberParam('collectionId') || 0; - this.query = CoreNavigator.instance.getRouteParam('query') || ''; + this.collectionId = CoreNavigator.getRouteNumberParam('collectionId') || 0; + this.query = CoreNavigator.getRouteParam('query') || ''; this.fetchData().finally(() => { this.loaded = true; @@ -60,7 +60,7 @@ export class CoreTagSearchPage implements OnInit { this.fetchTags(), ]); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading tags.'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading tags.'); } } @@ -70,11 +70,11 @@ export class CoreTagSearchPage implements OnInit { * @return Resolved when done. */ async fetchCollections(): Promise { - const collections = await CoreTag.instance.getTagCollections(); + const collections = await CoreTag.getTagCollections(); collections.forEach((collection) => { if (!collection.name && collection.isdefault) { - collection.name = Translate.instance.instant('core.tag.defautltagcoll'); + collection.name = Translate.instant('core.tag.defautltagcoll'); } }); @@ -87,15 +87,15 @@ export class CoreTagSearchPage implements OnInit { * @return Resolved when done. */ async fetchTags(): Promise { - this.cloud = await CoreTag.instance.getTagCloud(this.collectionId, undefined, undefined, this.query); + this.cloud = await CoreTag.getTagCloud(this.collectionId, undefined, undefined, this.query); } /** * Go to tag index page. */ openTag(tag: CoreTagCloudTag): void { - const url = CoreTextUtils.instance.decodeURI(tag.viewurl); - CoreContentLinksHelper.instance.handleLink(url); + const url = CoreTextUtils.decodeURI(tag.viewurl); + CoreContentLinksHelper.handleLink(url); } /** @@ -104,9 +104,9 @@ export class CoreTagSearchPage implements OnInit { * @param refresher Refresher event. */ refreshData(refresher?: CustomEvent): void { - CoreUtils.instance.allPromises([ - CoreTag.instance.invalidateTagCollections(), - CoreTag.instance.invalidateTagCloud(this.collectionId, undefined, undefined, this.query), + CoreUtils.allPromises([ + CoreTag.invalidateTagCollections(), + CoreTag.invalidateTagCloud(this.collectionId, undefined, undefined, this.query), ]).finally(() => this.fetchData().finally(() => { refresher?.detail.complete(); })); @@ -121,10 +121,10 @@ export class CoreTagSearchPage implements OnInit { searchTags(query: string): Promise { this.searching = true; this.query = query; - CoreApp.instance.closeKeyboard(); + CoreApp.closeKeyboard(); return this.fetchTags().catch((error) => { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading tags.'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading tags.'); }).finally(() => { this.searching = false; }); diff --git a/src/core/features/tag/services/handlers/index-link.ts b/src/core/features/tag/services/handlers/index-link.ts index 01c858693..6454bbdb9 100644 --- a/src/core/features/tag/services/handlers/index-link.ts +++ b/src/core/features/tag/services/handlers/index-link.ts @@ -57,11 +57,11 @@ export class CoreTagIndexLinkHandlerService extends CoreContentLinksHandlerBase }; if (!pageParams.tagId && (!pageParams.tagName || !pageParams.collectionId)) { - CoreNavigator.instance.navigateToSitePath('/tag/search', { siteId }); + CoreNavigator.navigateToSitePath('/tag/search', { siteId }); } else if (pageParams.areaId) { - CoreNavigator.instance.navigateToSitePath('/tag/index-area', { params: pageParams, siteId }); + CoreNavigator.navigateToSitePath('/tag/index-area', { params: pageParams, siteId }); } else { - CoreNavigator.instance.navigateToSitePath('/tag/index', { params: pageParams, siteId }); + CoreNavigator.navigateToSitePath('/tag/index', { params: pageParams, siteId }); } }, }]; @@ -78,9 +78,9 @@ export class CoreTagIndexLinkHandlerService extends CoreContentLinksHandlerBase * @return Whether the handler is enabled for the URL and site. */ async isEnabled(siteId: string): Promise { - return CoreTag.instance.areTagsAvailable(siteId); + return CoreTag.areTagsAvailable(siteId); } } -export class CoreTagIndexLinkHandler extends makeSingleton(CoreTagIndexLinkHandlerService) {} +export const CoreTagIndexLinkHandler = makeSingleton(CoreTagIndexLinkHandlerService); diff --git a/src/core/features/tag/services/handlers/mainmenu.ts b/src/core/features/tag/services/handlers/mainmenu.ts index 7c4e28631..6a434dccf 100644 --- a/src/core/features/tag/services/handlers/mainmenu.ts +++ b/src/core/features/tag/services/handlers/mainmenu.ts @@ -35,13 +35,13 @@ export class CoreTagMainMenuHandlerService implements CoreMainMenuHandler { * @return Whether or not the handler is enabled on a site level. */ async isEnabled(): Promise { - const available = await CoreTag.instance.areTagsAvailable(); + const available = await CoreTag.areTagsAvailable(); if (!available) { return false; } // The only way to check whether tags are enabled on web is to perform a WS call. - return CoreUtils.instance.promiseWorks(CoreTag.instance.getTagCollections()); + return CoreUtils.promiseWorks(CoreTag.getTagCollections()); } /** @@ -60,4 +60,4 @@ export class CoreTagMainMenuHandlerService implements CoreMainMenuHandler { } -export class CoreTagMainMenuHandler extends makeSingleton(CoreTagMainMenuHandlerService) {} +export const CoreTagMainMenuHandler = makeSingleton(CoreTagMainMenuHandlerService); diff --git a/src/core/features/tag/services/handlers/search-link.ts b/src/core/features/tag/services/handlers/search-link.ts index fcd491852..1749af16a 100644 --- a/src/core/features/tag/services/handlers/search-link.ts +++ b/src/core/features/tag/services/handlers/search-link.ts @@ -51,7 +51,7 @@ export class CoreTagSearchLinkHandlerService extends CoreContentLinksHandlerBase query: params.query || '', }; - CoreNavigator.instance.navigateToSitePath('/tag/search', { params: pageParams, siteId }); + CoreNavigator.navigateToSitePath('/tag/search', { params: pageParams, siteId }); }, }]; } @@ -64,9 +64,9 @@ export class CoreTagSearchLinkHandlerService extends CoreContentLinksHandlerBase * @return Whether the handler is enabled for the URL and site. */ async isEnabled(siteId: string): Promise { - return CoreTag.instance.areTagsAvailable(siteId); + return CoreTag.areTagsAvailable(siteId); } } -export class CoreTagSearchLinkHandler extends makeSingleton(CoreTagSearchLinkHandlerService) {} +export const CoreTagSearchLinkHandler = makeSingleton(CoreTagSearchLinkHandlerService); diff --git a/src/core/features/tag/services/tag-area-delegate.ts b/src/core/features/tag/services/tag-area-delegate.ts index fbe1f14c3..0ef6d446f 100644 --- a/src/core/features/tag/services/tag-area-delegate.ts +++ b/src/core/features/tag/services/tag-area-delegate.ts @@ -95,4 +95,4 @@ export class CoreTagAreaDelegateService extends CoreDelegate } -export class CoreTagAreaDelegate extends makeSingleton(CoreTagAreaDelegateService) {} +export const CoreTagAreaDelegate = makeSingleton(CoreTagAreaDelegateService); diff --git a/src/core/features/tag/services/tag-helper.ts b/src/core/features/tag/services/tag-helper.ts index 5219d08cf..40646c719 100644 --- a/src/core/features/tag/services/tag-helper.ts +++ b/src/core/features/tag/services/tag-helper.ts @@ -30,7 +30,7 @@ export class CoreTagHelperProvider { */ parseFeedContent(content: string): CoreTagFeedElement[] { const items: CoreTagFeedElement[] = []; - const element = CoreDomUtils.instance.convertToElement(content); + const element = CoreDomUtils.convertToElement(content); Array.from(element.querySelectorAll('ul.tag_feed > li.media')).forEach((itemElement) => { const item: CoreTagFeedElement = { details: [] }; @@ -80,7 +80,7 @@ export class CoreTagHelperProvider { } -export class CoreTagHelper extends makeSingleton(CoreTagHelperProvider) {} +export const CoreTagHelper = makeSingleton(CoreTagHelperProvider); /** * Feed area element type. diff --git a/src/core/features/tag/services/tag.ts b/src/core/features/tag/services/tag.ts index 0c25ee61d..13018d59e 100644 --- a/src/core/features/tag/services/tag.ts +++ b/src/core/features/tag/services/tag.ts @@ -37,7 +37,7 @@ export class CoreTagProvider { * @since 3.7 */ async areTagsAvailable(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.areTagsAvailableInSite(site); } @@ -49,7 +49,7 @@ export class CoreTagProvider { * @return True if available. */ areTagsAvailableInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site && site.wsAvailable('core_tag_get_tagindex_per_area') && site.wsAvailable('core_tag_get_tag_cloud') && @@ -85,7 +85,7 @@ export class CoreTagProvider { ): Promise { limit = limit || CoreTagProvider.SEARCH_LIMIT; - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreTagGetTagCloudWSParams = { tagcollid: collectionId, isstandard: isStandard, @@ -113,7 +113,7 @@ export class CoreTagProvider { * @since 3.7 */ async getTagCollections(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { updateFrequency: CoreSite.FREQUENCY_RARELY, cacheKey: this.getTagCollectionsKey(), @@ -154,7 +154,7 @@ export class CoreTagProvider { page: number = 0, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreTagGetTagindexPerAreaWSParams = { tagindex: { id, @@ -179,7 +179,7 @@ export class CoreTagProvider { } catch (error) { // Workaround for WS not passing parameter to error string. if (error && error.errorcode == 'notagsfound') { - error.message = Translate.instance.instant('core.tag.notagsfound', { $a: name || id || '' }); + error.message = Translate.instant('core.tag.notagsfound', { $a: name || id || '' }); } throw error; @@ -214,7 +214,7 @@ export class CoreTagProvider { recursive: boolean = true, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const key = this.getTagCloudKey(collectionId, isStandard, sort, search, fromContextId, contextId, recursive); return site.invalidateWsCacheForKey(key); @@ -226,7 +226,7 @@ export class CoreTagProvider { * @return Promise resolved when the data is invalidated. */ async invalidateTagCollections(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const key = this.getTagCollectionsKey(); return site.invalidateWsCacheForKey(key); @@ -254,7 +254,7 @@ export class CoreTagProvider { recursive: boolean = true, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const key = this.getTagIndexPerAreaKey(id, name, collectionId, areaId, fromContextId, contextId, recursive); return site.invalidateWsCacheForKey(key); @@ -331,7 +331,7 @@ export class CoreTagProvider { } -export class CoreTag extends makeSingleton(CoreTagProvider) {} +export const CoreTag = makeSingleton(CoreTagProvider); /** * Params of core_tag_get_tag_cloud WS. diff --git a/src/core/features/tag/tag.module.ts b/src/core/features/tag/tag.module.ts index fc46121d3..13b957682 100644 --- a/src/core/features/tag/tag.module.ts +++ b/src/core/features/tag/tag.module.ts @@ -42,9 +42,9 @@ const routes: Routes = [ provide: APP_INITIALIZER, multi: true, useValue: () => { - CoreMainMenuDelegate.instance.registerHandler(CoreTagMainMenuHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(CoreTagIndexLinkHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(CoreTagSearchLinkHandler.instance); + CoreMainMenuDelegate.registerHandler(CoreTagMainMenuHandler.instance); + CoreContentLinksDelegate.registerHandler(CoreTagIndexLinkHandler.instance); + CoreContentLinksDelegate.registerHandler(CoreTagSearchLinkHandler.instance); }, }, ], diff --git a/src/core/features/user/components/user-profile-field/user-profile-field.ts b/src/core/features/user/components/user-profile-field/user-profile-field.ts index 678f7b200..9f32d4591 100644 --- a/src/core/features/user/components/user-profile-field/user-profile-field.ts +++ b/src/core/features/user/components/user-profile-field/user-profile-field.ts @@ -48,13 +48,13 @@ export class CoreUserProfileFieldComponent implements OnInit { return; } - this.componentClass = await CoreUserProfileFieldDelegate.instance.getComponent(this.field, this.signup); + this.componentClass = await CoreUserProfileFieldDelegate.getComponent(this.field, this.signup); this.data.field = this.field; - this.data.edit = CoreUtils.instance.isTrueOrOne(this.edit); + this.data.edit = CoreUtils.isTrueOrOne(this.edit); if (this.edit) { - this.data.signup = CoreUtils.instance.isTrueOrOne(this.signup); - this.data.disabled = CoreUtils.instance.isTrueOrOne(this.field.locked); + this.data.signup = CoreUtils.isTrueOrOne(this.signup); + this.data.disabled = CoreUtils.isTrueOrOne(this.field.locked); this.data.form = this.form; this.data.registerAuth = this.registerAuth; this.data.contextLevel = this.contextLevel; diff --git a/src/core/features/user/pages/about/about.page.ts b/src/core/features/user/pages/about/about.page.ts index aab8c18cb..8598109cd 100644 --- a/src/core/features/user/pages/about/about.page.ts +++ b/src/core/features/user/pages/about/about.page.ts @@ -47,7 +47,7 @@ export class CoreUserAboutPage implements OnInit { encodedAddress?: SafeUrl; constructor() { - this.siteId = CoreSites.instance.getCurrentSiteId(); + this.siteId = CoreSites.getCurrentSiteId(); } /** @@ -56,8 +56,8 @@ export class CoreUserAboutPage implements OnInit { * @return Promise resolved when done. */ async ngOnInit(): Promise { - this.userId = CoreNavigator.instance.getRouteNumberParam('userId') || 0; - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || 0; + this.userId = CoreNavigator.getRouteNumberParam('userId') || 0; + this.courseId = CoreNavigator.getRouteNumberParam('courseId') || 0; this.fetchUser().finally(() => { this.userLoaded = true; @@ -71,11 +71,11 @@ export class CoreUserAboutPage implements OnInit { */ async fetchUser(): Promise { try { - const user = await CoreUser.instance.getProfile(this.userId, this.courseId); + const user = await CoreUser.getProfile(this.userId, this.courseId); if (user.address) { - this.formattedAddress = CoreUserHelper.instance.formatAddress(user.address, user.city, user.country); - this.encodedAddress = CoreTextUtils.instance.buildAddressURL(user.address); + this.formattedAddress = CoreUserHelper.formatAddress(user.address, user.city, user.country); + this.encodedAddress = CoreTextUtils.buildAddressURL(user.address); } this.hasContact = !!(user.email || user.phone1 || user.phone2 || user.city || user.country || user.address); @@ -84,7 +84,7 @@ export class CoreUserAboutPage implements OnInit { this.user = user; this.title = user.fullname; } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'core.user.errorloaduser', true); + CoreDomUtils.showErrorModalDefault(error, 'core.user.errorloaduser', true); } } @@ -95,7 +95,7 @@ export class CoreUserAboutPage implements OnInit { * @return Promise resolved when done. */ async refreshUser(event?: CustomEvent): Promise { - await CoreUtils.instance.ignoreErrors(CoreUser.instance.invalidateUserCache(this.userId)); + await CoreUtils.ignoreErrors(CoreUser.invalidateUserCache(this.userId)); await this.fetchUser(); diff --git a/src/core/features/user/pages/participants/participants.ts b/src/core/features/user/pages/participants/participants.ts index ee568a417..9757e5053 100644 --- a/src/core/features/user/pages/participants/participants.ts +++ b/src/core/features/user/pages/participants/participants.ts @@ -53,7 +53,7 @@ export class CoreUserParticipantsPage implements OnInit, AfterViewInit, OnDestro * @inheritdoc */ async ngOnInit(): Promise { - this.searchEnabled = await CoreUser.instance.canSearchParticipantsInSite(); + this.searchEnabled = await CoreUser.canSearchParticipantsInSite(); } /** @@ -108,7 +108,7 @@ export class CoreUserParticipantsPage implements OnInit, AfterViewInit, OnDestro * @param query Text to search for. */ async search(query: string): Promise { - CoreApp.instance.closeKeyboard(); + CoreApp.closeKeyboard(); this.searchInProgress = true; this.searchQuery = query; @@ -125,8 +125,8 @@ export class CoreUserParticipantsPage implements OnInit, AfterViewInit, OnDestro * @param refresher Refresher. */ async refreshParticipants(refresher: IonRefresher): Promise { - await CoreUtils.instance.ignoreErrors(CoreUser.instance.invalidateParticipantsList(this.participants.courseId)); - await CoreUtils.instance.ignoreErrors(this.fetchParticipants()); + await CoreUtils.ignoreErrors(CoreUser.invalidateParticipantsList(this.participants.courseId)); + await CoreUtils.ignoreErrors(this.fetchParticipants()); refresher?.complete(); } @@ -140,7 +140,7 @@ export class CoreUserParticipantsPage implements OnInit, AfterViewInit, OnDestro try { await this.fetchParticipants(this.participants.items); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading more participants'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading more participants'); this.fetchMoreParticipantsFailed = true; } @@ -155,7 +155,7 @@ export class CoreUserParticipantsPage implements OnInit, AfterViewInit, OnDestro try { await this.fetchParticipants(); } catch (error) { - CoreDomUtils.instance.showErrorModalDefault(error, 'Error loading participants'); + CoreDomUtils.showErrorModalDefault(error, 'Error loading participants'); this.participants.setItems([]); } @@ -168,7 +168,7 @@ export class CoreUserParticipantsPage implements OnInit, AfterViewInit, OnDestro */ private async fetchParticipants(loadedParticipants: CoreUserParticipant[] | CoreUserData[] = []): Promise { if (this.searchQuery) { - const { participants, canLoadMore } = await CoreUser.instance.searchParticipants( + const { participants, canLoadMore } = await CoreUser.searchParticipants( this.participants.courseId, this.searchQuery, true, @@ -178,7 +178,7 @@ export class CoreUserParticipantsPage implements OnInit, AfterViewInit, OnDestro this.participants.setItems((loadedParticipants as CoreUserData[]).concat(participants), canLoadMore); } else { - const { participants, canLoadMore } = await CoreUser.instance.getParticipants( + const { participants, canLoadMore } = await CoreUser.getParticipants( this.participants.courseId, loadedParticipants.length, ); @@ -208,8 +208,8 @@ class CoreUserParticipantsManager extends CorePageItemsListManager { - if (CoreScreen.instance.isMobile) { - await CoreNavigator.instance.navigateToSitePath('/user/profile', { params: { userId: participant.id } }); + if (CoreScreen.isMobile) { + await CoreNavigator.navigateToSitePath('/user/profile', { params: { userId: participant.id } }); return; } @@ -235,7 +235,7 @@ class CoreUserParticipantsManager extends CorePageItemsListManager { - await CoreUser.instance.logParticipantsView(this.courseId); + await CoreUser.logParticipantsView(this.courseId); } } diff --git a/src/core/features/user/pages/profile/profile.page.ts b/src/core/features/user/pages/profile/profile.page.ts index 883acfe1c..37764fec0 100644 --- a/src/core/features/user/pages/profile/profile.page.ts +++ b/src/core/features/user/pages/profile/profile.page.ts @@ -68,24 +68,24 @@ export class CoreUserProfilePage implements OnInit, OnDestroy { } this.user.email = data.user.email; - this.user.address = CoreUserHelper.instance.formatAddress('', data.user.city, data.user.country); - }, CoreSites.instance.getCurrentSiteId()); + this.user.address = CoreUserHelper.formatAddress('', data.user.city, data.user.country); + }, CoreSites.getCurrentSiteId()); } /** * On init. */ async ngOnInit(): Promise { - this.site = CoreSites.instance.getCurrentSite(); - this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId'); - const userId = CoreNavigator.instance.getRouteNumberParam('userId'); + this.site = CoreSites.getCurrentSite(); + this.courseId = CoreNavigator.getRouteNumberParam('courseId'); + const userId = CoreNavigator.getRouteNumberParam('userId'); if (!this.site) { return; } if (userId === undefined) { - CoreDomUtils.instance.showErrorModal('User ID not supplied'); - CoreNavigator.instance.back(); + CoreDomUtils.showErrorModal('User ID not supplied'); + CoreNavigator.back(); return; } @@ -97,14 +97,14 @@ export class CoreUserProfilePage implements OnInit, OnDestroy { (!this.courseId || this.courseId == this.site.getSiteHomeId()) && this.userId == this.site.getUserId() && this.site.canUploadFiles() && - CoreUser.instance.canUpdatePictureInSite(this.site) && - !CoreUser.instance.isUpdatePictureDisabledInSite(this.site); + CoreUser.canUpdatePictureInSite(this.site) && + !CoreUser.isUpdatePictureDisabledInSite(this.site); try { await this.fetchUser(); try { - await CoreUser.instance.logView(this.userId, this.courseId, this.user!.fullname); + await CoreUser.logView(this.userId, this.courseId, this.user!.fullname); } catch (error) { this.isDeleted = error?.errorcode === 'userdeleted'; this.isEnrolled = error?.errorcode !== 'notenrolledprofile'; @@ -119,10 +119,10 @@ export class CoreUserProfilePage implements OnInit, OnDestroy { */ async fetchUser(): Promise { try { - const user = await CoreUser.instance.getProfile(this.userId, this.courseId); + const user = await CoreUser.getProfile(this.userId, this.courseId); - user.address = CoreUserHelper.instance.formatAddress('', user.city, user.country); - this.rolesFormatted = 'roles' in user ? CoreUserHelper.instance.formatRoleList(user.roles) : ''; + user.address = CoreUserHelper.formatAddress('', user.city, user.country); + this.rolesFormatted = 'roles' in user ? CoreUserHelper.formatRoleList(user.roles) : ''; this.user = user; this.title = user.fullname; @@ -130,7 +130,7 @@ export class CoreUserProfilePage implements OnInit, OnDestroy { // If there's already a subscription, unsubscribe because we'll get a new one. this.subscription?.unsubscribe(); - this.subscription = CoreUserDelegate.instance.getProfileHandlersFor(user, this.courseId).subscribe((handlers) => { + this.subscription = CoreUserDelegate.getProfileHandlersFor(user, this.courseId).subscribe((handlers) => { this.actionHandlers = []; this.newPageHandlers = []; this.communicationHandlers = []; @@ -149,14 +149,14 @@ export class CoreUserProfilePage implements OnInit, OnDestroy { } }); - this.isLoadingHandlers = !CoreUserDelegate.instance.areHandlersLoaded(user.id); + this.isLoadingHandlers = !CoreUserDelegate.areHandlersLoaded(user.id); }); await this.checkUserImageUpdated(); } catch (error) { // Error is null for deleted users, do not show the modal. - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } } @@ -178,7 +178,7 @@ export class CoreUserProfilePage implements OnInit, OnDestroy { // The current user image received is different than the one stored in site info. Assume the image was updated. // Update the site info to get the right avatar in there. try { - await CoreSites.instance.updateSiteInfo(this.site.getId()); + await CoreSites.updateSiteInfo(this.site.getId()); } catch { // Cannot update site info. Assume the profile image is the right one. CoreEvents.trigger(CoreUserProvider.PROFILE_PICTURE_UPDATED, { @@ -204,27 +204,27 @@ export class CoreUserProfilePage implements OnInit, OnDestroy { */ async changeProfilePicture(): Promise { const maxSize = -1; - const title = Translate.instance.instant('core.user.newpicture'); - const mimetypes = CoreMimetypeUtils.instance.getGroupMimeInfo('image', 'mimetypes'); + const title = Translate.instant('core.user.newpicture'); + const mimetypes = CoreMimetypeUtils.getGroupMimeInfo('image', 'mimetypes'); let modal: CoreIonLoadingElement | undefined; try { - const result = await CoreFileUploaderHelper.instance.selectAndUploadFile(maxSize, title, mimetypes); + const result = await CoreFileUploaderHelper.selectAndUploadFile(maxSize, title, mimetypes); - modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); + modal = await CoreDomUtils.showModalLoading('core.sending', true); - const profileImageURL = await CoreUser.instance.changeProfilePicture(result.itemid, this.userId, this.site!.getId()); + const profileImageURL = await CoreUser.changeProfilePicture(result.itemid, this.userId, this.site!.getId()); CoreEvents.trigger(CoreUserProvider.PROFILE_PICTURE_UPDATED, { userId: this.userId, picture: profileImageURL, }, this.site!.getId()); - CoreSites.instance.updateSiteInfo(this.site!.getId()); + CoreSites.updateSiteInfo(this.site!.getId()); this.refreshUser(); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } finally { modal?.dismiss(); } @@ -237,8 +237,8 @@ export class CoreUserProfilePage implements OnInit, OnDestroy { * @return Promise resolved when done. */ async refreshUser(event?: CustomEvent): Promise { - await CoreUtils.instance.ignoreErrors(Promise.all([ - CoreUser.instance.invalidateUserCache(this.userId), + await CoreUtils.ignoreErrors(Promise.all([ + CoreUser.invalidateUserCache(this.userId), // @todo this.coursesProvider.invalidateUserNavigationOptions(), // this.coursesProvider.invalidateUserAdministrationOptions() ])); @@ -261,7 +261,7 @@ export class CoreUserProfilePage implements OnInit, OnDestroy { */ openUserDetails(): void { // @todo: Navigate out of split view if this page is in the right pane. - CoreNavigator.instance.navigate('../about', { + CoreNavigator.navigate('../about', { params: { courseId: this.courseId, userId: this.userId, diff --git a/src/core/features/user/services/handlers/course-option.ts b/src/core/features/user/services/handlers/course-option.ts index 0ec75f4ca..9be660d77 100644 --- a/src/core/features/user/services/handlers/course-option.ts +++ b/src/core/features/user/services/handlers/course-option.ts @@ -46,7 +46,7 @@ export class CoreUserCourseOptionHandlerService implements CoreCourseOptionsHand return Promise.resolve(); } - return CoreUser.instance.invalidateParticipantsList(courseId); + return CoreUser.invalidateParticipantsList(courseId); } /** @@ -79,7 +79,7 @@ export class CoreUserCourseOptionHandlerService implements CoreCourseOptionsHand return navOptions.participants; } - return CoreUser.instance.isPluginEnabledForCourse(courseId); + return CoreUser.isPluginEnabledForCourse(courseId); } /** @@ -104,7 +104,7 @@ export class CoreUserCourseOptionHandlerService implements CoreCourseOptionsHand let canLoadMore = true; do { - const result = await CoreUser.instance.getParticipants(course.id, offset, undefined, undefined, true); + const result = await CoreUser.getParticipants(course.id, offset, undefined, undefined, true); offset += result.participants.length; canLoadMore = result.canLoadMore; @@ -113,4 +113,4 @@ export class CoreUserCourseOptionHandlerService implements CoreCourseOptionsHand } -export class CoreUserCourseOptionHandler extends makeSingleton(CoreUserCourseOptionHandlerService) {} +export const CoreUserCourseOptionHandler = makeSingleton(CoreUserCourseOptionHandlerService); diff --git a/src/core/features/user/services/handlers/profile-link.ts b/src/core/features/user/services/handlers/profile-link.ts index 805705dfe..b7eb0ad5b 100644 --- a/src/core/features/user/services/handlers/profile-link.ts +++ b/src/core/features/user/services/handlers/profile-link.ts @@ -53,7 +53,7 @@ export class CoreUserProfileLinkHandlerService extends CoreContentLinksHandlerBa userId: parseInt(params.id, 10), }; - CoreNavigator.instance.navigateToSitePath('/user', { params: pageParams, siteId }); + CoreNavigator.navigateToSitePath('/user', { params: pageParams, siteId }); }, }]; } @@ -75,4 +75,4 @@ export class CoreUserProfileLinkHandlerService extends CoreContentLinksHandlerBa } -export class CoreUserProfileLinkHandler extends makeSingleton(CoreUserProfileLinkHandlerService) {} +export const CoreUserProfileLinkHandler = makeSingleton(CoreUserProfileLinkHandlerService); diff --git a/src/core/features/user/services/handlers/profile-mail.ts b/src/core/features/user/services/handlers/profile-mail.ts index a240fc59a..2af4d8f8f 100644 --- a/src/core/features/user/services/handlers/profile-mail.ts +++ b/src/core/features/user/services/handlers/profile-mail.ts @@ -50,7 +50,7 @@ export class CoreUserProfileMailHandlerService implements CoreUserProfileHandler */ // eslint-disable-next-line @typescript-eslint/no-unused-vars async isEnabledForUser(user: CoreUserProfile, courseId: number, navOptions?: unknown, admOptions?: unknown): Promise { - return user.id != CoreSites.instance.getCurrentSiteUserId() && !!user.email; + return user.id != CoreSites.getCurrentSiteUserId() && !!user.email; } /** @@ -68,11 +68,11 @@ export class CoreUserProfileMailHandlerService implements CoreUserProfileHandler event.preventDefault(); event.stopPropagation(); - CoreUtils.instance.openInBrowser('mailto:' + user.email); + CoreUtils.openInBrowser('mailto:' + user.email); }, }; } } -export class CoreUserProfileMailHandler extends makeSingleton(CoreUserProfileMailHandlerService) {} +export const CoreUserProfileMailHandler = makeSingleton(CoreUserProfileMailHandlerService); diff --git a/src/core/features/user/services/handlers/sync-cron.ts b/src/core/features/user/services/handlers/sync-cron.ts index b188d8d59..833e97ba6 100644 --- a/src/core/features/user/services/handlers/sync-cron.ts +++ b/src/core/features/user/services/handlers/sync-cron.ts @@ -36,7 +36,7 @@ export class CoreUserSyncCronHandlerService implements CoreCronHandler { */ // eslint-disable-next-line @typescript-eslint/no-unused-vars execute(siteId?: string, force?: boolean): Promise { - return CoreUserSync.instance.syncPreferences(siteId); + return CoreUserSync.syncPreferences(siteId); } /** @@ -50,4 +50,4 @@ export class CoreUserSyncCronHandlerService implements CoreCronHandler { } -export class CoreUserSyncCronHandler extends makeSingleton(CoreUserSyncCronHandlerService) {} +export const CoreUserSyncCronHandler = makeSingleton(CoreUserSyncCronHandlerService); diff --git a/src/core/features/user/services/handlers/tag-area.ts b/src/core/features/user/services/handlers/tag-area.ts index 5b51db223..d4334817f 100644 --- a/src/core/features/user/services/handlers/tag-area.ts +++ b/src/core/features/user/services/handlers/tag-area.ts @@ -47,7 +47,7 @@ export class CoreUserTagAreaHandlerService implements CoreTagAreaHandler { */ parseContent(content: string): CoreUserTagFeedElement[] { const items: CoreUserTagFeedElement[] = []; - const element = CoreDomUtils.instance.convertToElement(content); + const element = CoreDomUtils.convertToElement(content); Array.from(element.querySelectorAll('div.user-box')).forEach((userbox: HTMLElement) => { const avatarLink = userbox.querySelector('a:first-child'); @@ -90,7 +90,7 @@ export class CoreUserTagAreaHandlerService implements CoreTagAreaHandler { } -export class CoreUserTagAreaHandler extends makeSingleton(CoreUserTagAreaHandlerService) {} +export const CoreUserTagAreaHandler = makeSingleton(CoreUserTagAreaHandlerService); export type CoreUserTagFeedElement = CoreTagFeedElement & { user: CoreUserBasicData; diff --git a/src/core/features/user/services/user-delegate.ts b/src/core/features/user/services/user-delegate.ts index 68118bdaf..00eb18b9a 100644 --- a/src/core/features/user/services/user-delegate.ts +++ b/src/core/features/user/services/user-delegate.ts @@ -248,7 +248,7 @@ export class CoreUserDelegateService extends CoreDelegate { + await CoreUtils.allPromises(Object.keys(this.enabledHandlers).map(async (name) => { // Checks if the handler is enabled for the user. const handler = this.handlers[name]; @@ -276,7 +276,7 @@ export class CoreUserDelegateService extends CoreDelegate value && value.length > 0); @@ -51,10 +51,10 @@ export class CoreUserHelperProvider { return ''; } - const separator = Translate.instance.instant('core.listsep'); + const separator = Translate.instant('core.listsep'); return roles.map((value) => { - const translation = Translate.instance.instant('core.user.' + value.shortname); + const translation = Translate.instant('core.user.' + value.shortname); return translation.indexOf('core.user.') < 0 ? translation : value.shortname; }).join(separator + ' '); @@ -62,4 +62,4 @@ export class CoreUserHelperProvider { } -export class CoreUserHelper extends makeSingleton(CoreUserHelperProvider) {} +export const CoreUserHelper = makeSingleton(CoreUserHelperProvider); diff --git a/src/core/features/user/services/user-offline.ts b/src/core/features/user/services/user-offline.ts index ebe3c8e3e..4fd5f1c6a 100644 --- a/src/core/features/user/services/user-offline.ts +++ b/src/core/features/user/services/user-offline.ts @@ -31,7 +31,7 @@ export class CoreUserOfflineProvider { * @return Promise resolved with list of preferences. */ async getChangedPreferences(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecordsSelect(PREFERENCES_TABLE_NAME, 'value != onlineValue'); } @@ -44,7 +44,7 @@ export class CoreUserOfflineProvider { * @return Promise resolved with the preference, rejected if not found. */ async getPreference(name: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecord(PREFERENCES_TABLE_NAME, { name }); } @@ -59,7 +59,7 @@ export class CoreUserOfflineProvider { * @return Promise resolved when done. */ async setPreference(name: string, value: string, onlineValue?: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (typeof onlineValue == 'undefined') { const preference = await this.getPreference(name, site.id); @@ -78,4 +78,4 @@ export class CoreUserOfflineProvider { } -export class CoreUserOffline extends makeSingleton(CoreUserOfflineProvider) {} +export const CoreUserOffline = makeSingleton(CoreUserOfflineProvider); diff --git a/src/core/features/user/services/user-profile-field-delegate.ts b/src/core/features/user/services/user-profile-field-delegate.ts index 7743bf540..93f893b5b 100644 --- a/src/core/features/user/services/user-profile-field-delegate.ts +++ b/src/core/features/user/services/user-profile-field-delegate.ts @@ -205,4 +205,4 @@ export class CoreUserProfileFieldDelegateService extends CoreDelegate { * @param Promise resolved with warnings if sync is successful, rejected if sync fails. */ async syncSitePreferences(siteId: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const syncId = 'preferences'; @@ -76,21 +76,21 @@ export class CoreUserSyncProvider extends CoreSyncBaseProvider { protected async performSyncSitePreferences(siteId: string): Promise { const warnings: string[] = []; - const preferences = await CoreUserOffline.instance.getChangedPreferences(siteId); + const preferences = await CoreUserOffline.getChangedPreferences(siteId); - await CoreUtils.instance.allPromises(preferences.map(async (preference) => { - const onlineValue = await CoreUser.instance.getUserPreferenceOnline(preference.name, siteId); + await CoreUtils.allPromises(preferences.map(async (preference) => { + const onlineValue = await CoreUser.getUserPreferenceOnline(preference.name, siteId); if (onlineValue !== null && preference.onlinevalue != onlineValue) { // Preference was changed on web while the app was offline, do not sync. - return CoreUserOffline.instance.setPreference(preference.name, onlineValue, onlineValue, siteId); + return CoreUserOffline.setPreference(preference.name, onlineValue, onlineValue, siteId); } try { - await CoreUser.instance.setUserPreference(preference.name, preference.value, siteId); + await CoreUser.setUserPreference(preference.name, preference.value, siteId); } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { - warnings.push(CoreTextUtils.instance.getErrorMessageFromError(error)!); + if (CoreUtils.isWebServiceError(error)) { + warnings.push(CoreTextUtils.getErrorMessageFromError(error)!); } else { // Couldn't connect to server, reject. throw error; @@ -104,4 +104,4 @@ export class CoreUserSyncProvider extends CoreSyncBaseProvider { } -export class CoreUserSync extends makeSingleton(CoreUserSyncProvider) {} +export const CoreUserSync = makeSingleton(CoreUserSyncProvider, ['component', 'syncInterval']); diff --git a/src/core/features/user/services/user.ts b/src/core/features/user/services/user.ts index 0d34f14d2..19d8312b8 100644 --- a/src/core/features/user/services/user.ts +++ b/src/core/features/user/services/user.ts @@ -73,7 +73,7 @@ export class CoreUserProvider { * @since 3.8 */ async canSearchParticipants(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.canSearchParticipantsInSite(site); } @@ -86,7 +86,7 @@ export class CoreUserProvider { * @since 3.8 */ canSearchParticipantsInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.wsAvailable('core_enrol_search_users'); } @@ -99,7 +99,7 @@ export class CoreUserProvider { * @since 3.2 */ async canUpdatePicture(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.canUpdatePictureInSite(site); } @@ -112,7 +112,7 @@ export class CoreUserProvider { * @since 3.2 */ canUpdatePictureInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.wsAvailable('core_user_update_picture'); } @@ -126,7 +126,7 @@ export class CoreUserProvider { * @return Promise resolve with the new profileimageurl */ async changeProfilePicture(draftItemId: number, userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreUserUpdatePictureWSParams = { draftitemid: draftItemId, @@ -155,7 +155,7 @@ export class CoreUserProvider { throw new CoreError('Invalid user ID.'); } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await Promise.all([ this.invalidateUserCache(userId, site.getId()), @@ -181,7 +181,7 @@ export class CoreUserProvider { ignoreCache?: boolean, ): Promise<{participants: CoreUserParticipant[]; canLoadMore: boolean}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); this.logger.debug(`Get participants for course '${courseId}' starting at '${limitFrom}'`); @@ -245,7 +245,7 @@ export class CoreUserProvider { forceLocal: boolean = false, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (forceLocal) { try { @@ -284,7 +284,7 @@ export class CoreUserProvider { * @return Promise resolve when the user is retrieved. */ protected async getUserFromLocalDb(userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return site.getDb().getRecord(USERS_TABLE_NAME, { id: userId }); } @@ -302,7 +302,7 @@ export class CoreUserProvider { courseId?: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const preSets: CoreSiteWSPreSets = { cacheKey: this.getUserCacheKey(userId), @@ -342,7 +342,7 @@ export class CoreUserProvider { const user: CoreUserData | CoreUserCourseProfile = users[0]; if (user.country) { - user.country = CoreUtils.instance.getCountryName(user.country); + user.country = CoreUtils.getCountryName(user.country); } this.storeUser(user.id, user.fullname, user.profileimageurl); @@ -357,11 +357,11 @@ export class CoreUserProvider { * @return Preference value or null if preference not set. */ async getUserPreference(name: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const preference = await CoreUtils.instance.ignoreErrors(CoreUserOffline.instance.getPreference(name, siteId)); + const preference = await CoreUtils.ignoreErrors(CoreUserOffline.getPreference(name, siteId)); - if (preference && !CoreApp.instance.isOnline()) { + if (preference && !CoreApp.isOnline()) { // Offline, return stored value. return preference.value; } @@ -382,7 +382,7 @@ export class CoreUserProvider { return preference.value; } - await CoreUserOffline.instance.setPreference(name, wsValue, wsValue); + await CoreUserOffline.setPreference(name, wsValue, wsValue); return wsValue; } @@ -405,7 +405,7 @@ export class CoreUserProvider { * @return Preference value or null if preference not set. */ async getUserPreferenceOnline(name: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreUserGetUserPreferencesWSParams = { name, @@ -428,7 +428,7 @@ export class CoreUserProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserCache(userId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserCacheKey(userId)); } @@ -441,7 +441,7 @@ export class CoreUserProvider { * @return Promise resolved when the list is invalidated. */ async invalidateParticipantsList(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getParticipantsListCacheKey(courseId)); } @@ -454,7 +454,7 @@ export class CoreUserProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserPreference(name: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserPreferenceCacheKey(name)); } @@ -466,7 +466,7 @@ export class CoreUserProvider { * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async isParticipantsDisabled(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.isParticipantsDisabledInSite(site); } @@ -478,7 +478,7 @@ export class CoreUserProvider { * @return Whether it's disabled. */ isParticipantsDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('CoreCourseOptionsDelegate_CoreUserParticipants'); } @@ -496,7 +496,7 @@ export class CoreUserProvider { } // Retrieving one participant will fail if browsing users is disabled by capabilities. - return CoreUtils.instance.promiseWorks(this.getParticipants(courseId, 0, 1, siteId)); + return CoreUtils.promiseWorks(this.getParticipants(courseId, 0, 1, siteId)); } /** @@ -506,7 +506,7 @@ export class CoreUserProvider { * @return True if disabled, false otherwise. */ isUpdatePictureDisabledInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('CoreUserDelegate_picture'); } @@ -520,7 +520,7 @@ export class CoreUserProvider { * @return Promise resolved when done. */ async logView(userId: number, courseId?: number, name?: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreUserViewUserProfileWSParams = { userid: userId, @@ -531,7 +531,7 @@ export class CoreUserProvider { params.courseid = courseId; } - CorePushNotifications.instance.logViewEvent(userId, name, 'user', wsName, { courseid: courseId }); + CorePushNotifications.logViewEvent(userId, name, 'user', wsName, { courseid: courseId }); return site.write(wsName, params); } @@ -543,13 +543,13 @@ export class CoreUserProvider { * @return Promise resolved when done. */ async logParticipantsView(courseId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreUserViewUserListWSParams = { courseid: courseId, }; - CorePushNotifications.instance.logViewListEvent('user', 'core_user_view_user_list', params); + CorePushNotifications.logViewListEvent('user', 'core_user_view_user_list', params); return site.write('core_user_view_user_list', params); } @@ -563,7 +563,7 @@ export class CoreUserProvider { * @return Promise resolved when prefetched. */ async prefetchProfiles(userIds: number[], courseId?: number, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!siteId) { return; @@ -589,7 +589,7 @@ export class CoreUserProvider { const profile = await this.getProfile(userId, courseId, false, siteId); if (profile.profileimageurl) { - await CoreFilepool.instance.addToQueueByUrl(siteId!, profile.profileimageurl); + await CoreFilepool.addToQueueByUrl(siteId!, profile.profileimageurl); } } catch (error) { this.logger.warn(`Ignore error when prefetching user ${userId}`, error); @@ -606,7 +606,7 @@ export class CoreUserProvider { * @return Promise resolved when prefetched. */ async prefetchUserAvatars(entries: Record[], propertyName: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!siteId) { return; @@ -625,7 +625,7 @@ export class CoreUserProvider { treated[imageUrl] = true; try { - await CoreFilepool.instance.addToQueueByUrl(siteId!, imageUrl); + await CoreFilepool.addToQueueByUrl(siteId!, imageUrl); } catch (ex) { this.logger.warn(`Ignore error when prefetching user avatar ${imageUrl}`, entry, ex); } @@ -654,7 +654,7 @@ export class CoreUserProvider { perPage: number = CoreUserProvider.PARTICIPANTS_LIST_LIMIT, siteId?: string, ): Promise<{participants: CoreUserData[]; canLoadMore: boolean}> { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreEnrolSearchUsersWSParams = { courseid: courseId, @@ -685,7 +685,7 @@ export class CoreUserProvider { * @return Promise resolve when the user is stored. */ protected async storeUser(userId: number, fullname: string, avatar?: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const userRecord: CoreUserDBRecord = { id: userId, @@ -723,11 +723,11 @@ export class CoreUserProvider { * @return Promise resolved on success. */ async setUserPreference(name: string, value: string, siteId?: string): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // Offline, just update the preference. - return CoreUserOffline.instance.setPreference(name, value); + return CoreUserOffline.setPreference(name, value); } @@ -741,12 +741,12 @@ export class CoreUserProvider { // Update preference and invalidate data. await Promise.all([ - CoreUserOffline.instance.setPreference(name, value, value), - CoreUtils.instance.ignoreErrors(this.invalidateUserPreference(name)), + CoreUserOffline.setPreference(name, value, value), + CoreUtils.ignoreErrors(this.invalidateUserPreference(name)), ]); } catch (error) { // Preference not saved online. Update the offline one. - await CoreUserOffline.instance.setPreference(name, value); + await CoreUserOffline.setPreference(name, value); } } @@ -785,7 +785,7 @@ export class CoreUserProvider { userId?: number, siteId?: string, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -806,7 +806,7 @@ export class CoreUserProvider { } -export class CoreUser extends makeSingleton(CoreUserProvider) {} +export const CoreUser = makeSingleton(CoreUserProvider); /** * Data passed to PROFILE_REFRESHED event. diff --git a/src/core/features/user/user.module.ts b/src/core/features/user/user.module.ts index 0169c35ef..7eac3eea3 100644 --- a/src/core/features/user/user.module.ts +++ b/src/core/features/user/user.module.ts @@ -65,11 +65,11 @@ const courseIndexRoutes: Routes = [ multi: true, deps: [], useFactory: () => () => { - CoreUserDelegate.instance.registerHandler(CoreUserProfileMailHandler.instance); - CoreContentLinksDelegate.instance.registerHandler(CoreUserProfileLinkHandler.instance); - CoreCronDelegate.instance.register(CoreUserSyncCronHandler.instance); - CoreTagAreaDelegate.instance.registerHandler(CoreUserTagAreaHandler.instance); - CoreCourseOptionsDelegate.instance.registerHandler(CoreUserCourseOptionHandler.instance); + CoreUserDelegate.registerHandler(CoreUserProfileMailHandler.instance); + CoreContentLinksDelegate.registerHandler(CoreUserProfileLinkHandler.instance); + CoreCronDelegate.register(CoreUserSyncCronHandler.instance); + CoreTagAreaDelegate.registerHandler(CoreUserTagAreaHandler.instance); + CoreCourseOptionsDelegate.registerHandler(CoreUserCourseOptionHandler.instance); }, }, ], diff --git a/src/core/features/viewer/components/text/text.ts b/src/core/features/viewer/components/text/text.ts index 8baeaf033..2a88fdff1 100644 --- a/src/core/features/viewer/components/text/text.ts +++ b/src/core/features/viewer/components/text/text.ts @@ -43,14 +43,14 @@ export class CoreViewerTextComponent { * Close modal. */ closeModal(): void { - ModalController.instance.dismiss(); + ModalController.dismiss(); } /** * Copy the text to clipboard. */ copyText(): void { - CoreUtils.instance.copyToClipboard(this.content || ''); + CoreUtils.copyToClipboard(this.content || ''); } } diff --git a/src/core/features/xapi/services/offline.ts b/src/core/features/xapi/services/offline.ts index 32563902c..5114eed13 100644 --- a/src/core/features/xapi/services/offline.ts +++ b/src/core/features/xapi/services/offline.ts @@ -45,7 +45,7 @@ export class CoreXAPIOfflineProvider { * @return Promise resolved if stored, rejected if failure. */ async deleteStatements(id: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await db.deleteRecords(STATEMENTS_TABLE_NAME, { id }); } @@ -58,7 +58,7 @@ export class CoreXAPIOfflineProvider { * @return Promise resolved if stored, rejected if failure. */ async deleteStatementsForContext(contextId: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await db.deleteRecords(STATEMENTS_TABLE_NAME, { contextid: contextId }); } @@ -70,7 +70,7 @@ export class CoreXAPIOfflineProvider { * @return Promise resolved with all the data. */ async getAllStatements(siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); return db.getRecords(STATEMENTS_TABLE_NAME, undefined, 'timecreated ASC'); } @@ -83,7 +83,7 @@ export class CoreXAPIOfflineProvider { * @return Promise resolved with the data. */ async getContextStatements(contextId: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); return db.getRecords(STATEMENTS_TABLE_NAME, { contextid: contextId }, 'timecreated ASC'); } @@ -96,7 +96,7 @@ export class CoreXAPIOfflineProvider { * @return Promise resolved with the data. */ async getStatements(id: number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); return db.getRecord(STATEMENTS_TABLE_NAME, { id }); } @@ -116,7 +116,7 @@ export class CoreXAPIOfflineProvider { statements: string, options?: CoreXAPIOfflineSaveStatementsOptions, ): Promise { - const db = await CoreSites.instance.getSiteDb(options?.siteId); + const db = await CoreSites.getSiteDb(options?.siteId); const entry: Omit = { contextid: contextId, @@ -132,7 +132,7 @@ export class CoreXAPIOfflineProvider { } -export class CoreXAPIOffline extends makeSingleton(CoreXAPIOfflineProvider) {} +export const CoreXAPIOffline = makeSingleton(CoreXAPIOfflineProvider); /** * Options to pass to saveStatements function. diff --git a/src/core/features/xapi/services/xapi.ts b/src/core/features/xapi/services/xapi.ts index 7ea06df17..5e53fa214 100644 --- a/src/core/features/xapi/services/xapi.ts +++ b/src/core/features/xapi/services/xapi.ts @@ -36,7 +36,7 @@ export class CoreXAPIProvider { * @since 3.9 */ async canPostStatements(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); return this.canPostStatementsInSite(site); } @@ -49,7 +49,7 @@ export class CoreXAPIProvider { * @since 3.9 */ canPostStatementsInSite(site?: CoreSite): boolean { - site = site || CoreSites.instance.getCurrentSite(); + site = site || CoreSites.getCurrentSite(); return !!(site && site.wsAvailable('core_xapi_statement_post')); } @@ -63,9 +63,9 @@ export class CoreXAPIProvider { * @return Promise resolved when done. */ async getUrl(contextId: number, type: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); - return CoreTextUtils.instance.concatenatePaths(site.getURL(), `xapi/${type}/${contextId}`); + return CoreTextUtils.concatenatePaths(site.getURL(), `xapi/${type}/${contextId}`); } /** @@ -85,16 +85,16 @@ export class CoreXAPIProvider { ): Promise { options = options || {}; - options.siteId = options.siteId || CoreSites.instance.getCurrentSiteId(); + options.siteId = options.siteId || CoreSites.getCurrentSiteId(); // Convenience function to store a message to be synchronized later. const storeOffline = async (): Promise => { - await CoreXAPIOffline.instance.saveStatements(contextId, component, json, options); + await CoreXAPIOffline.saveStatements(contextId, component, json, options); return false; }; - if (!CoreApp.instance.isOnline() || options.offline) { + if (!CoreApp.isOnline() || options.offline) { // App is offline, store the action. return storeOffline(); } @@ -104,7 +104,7 @@ export class CoreXAPIProvider { return true; } catch (error) { - if (CoreUtils.instance.isWebServiceError(error)) { + if (CoreUtils.isWebServiceError(error)) { // The WebService has thrown an error, this means that responses cannot be submitted. throw error; } else { @@ -124,7 +124,7 @@ export class CoreXAPIProvider { */ async postStatementsOnline(component: string, json: string, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const data = { component: component, @@ -136,7 +136,7 @@ export class CoreXAPIProvider { } -export class CoreXAPI extends makeSingleton(CoreXAPIProvider) {} +export const CoreXAPI = makeSingleton(CoreXAPIProvider); /** * Options to pass to postStatements function. diff --git a/src/core/guards/can-leave.ts b/src/core/guards/can-leave.ts index 2f81f266c..17661660b 100644 --- a/src/core/guards/can-leave.ts +++ b/src/core/guards/can-leave.ts @@ -24,7 +24,7 @@ export class CanLeaveGuard implements CanDeactivate { return true; } - return CoreUtils.instance.ignoreErrors(component.canLeave(), false); + return CoreUtils.ignoreErrors(component.canLeave(), false); } isCanLeave(component: unknown | null): component is CanLeave { diff --git a/src/core/guards/redirect.ts b/src/core/guards/redirect.ts index fd01f1317..69129479d 100644 --- a/src/core/guards/redirect.ts +++ b/src/core/guards/redirect.ts @@ -41,7 +41,7 @@ export class CoreRedirectGuard implements CanLoad, CanActivate { * Check if there is a pending redirect and trigger it. */ private async guard(): Promise { - const redirect = CoreApp.instance.getRedirect(); + const redirect = CoreApp.getRedirect(); if (!redirect) { return true; @@ -55,12 +55,12 @@ export class CoreRedirectGuard implements CanLoad, CanActivate { // Redirect to site path. if (redirect.siteId && redirect.siteId !== CoreConstants.NO_SITE_ID) { - const loggedIn = await CoreSites.instance.loadSite( + const loggedIn = await CoreSites.loadSite( redirect.siteId, redirect.page, redirect.params, ); - const route = Router.instance.parseUrl('/main'); + const route = Router.parseUrl('/main'); route.queryParams = CoreObject.withoutEmpty({ redirectPath: redirect.page, @@ -76,7 +76,7 @@ export class CoreRedirectGuard implements CanLoad, CanActivate { } // Redirect to non-site path. - const route = Router.instance.parseUrl(redirect.page); + const route = Router.parseUrl(redirect.page); route.queryParams = CoreObject.withoutEmpty({ redirectPath: redirect.page, @@ -85,7 +85,7 @@ export class CoreRedirectGuard implements CanLoad, CanActivate { return route; } finally { - CoreApp.instance.forgetRedirect(); + CoreApp.forgetRedirect(); } } diff --git a/src/core/initializers/clear-tmp-folder.ts b/src/core/initializers/clear-tmp-folder.ts index 1d420c298..6249f79a4 100644 --- a/src/core/initializers/clear-tmp-folder.ts +++ b/src/core/initializers/clear-tmp-folder.ts @@ -15,5 +15,5 @@ import { CoreFile } from '@services/file'; export default async function(): Promise { - await CoreFile.instance.clearTmpFolder(); + await CoreFile.clearTmpFolder(); } diff --git a/src/core/initializers/consume-storage-redirect.ts b/src/core/initializers/consume-storage-redirect.ts index d44c3efa6..4a0f0efbc 100644 --- a/src/core/initializers/consume-storage-redirect.ts +++ b/src/core/initializers/consume-storage-redirect.ts @@ -15,5 +15,5 @@ import { CoreApp } from '@services/app'; export default function(): void { - CoreApp.instance.consumeStorageRedirect(); + CoreApp.consumeStorageRedirect(); } diff --git a/src/core/initializers/initialize-databases.ts b/src/core/initializers/initialize-databases.ts index 67b15aca9..4785c9455 100644 --- a/src/core/initializers/initialize-databases.ts +++ b/src/core/initializers/initialize-databases.ts @@ -21,11 +21,11 @@ import { CoreSites } from '@services/sites'; export default async function(): Promise { await Promise.all([ - CoreApp.instance.initializeDatabase(), - CoreConfig.instance.initializeDatabase(), - CoreCronDelegate.instance.initializeDatabase(), - CoreFilepool.instance.initializeDatabase(), - CoreLocalNotifications.instance.initializeDatabase(), - CoreSites.instance.initializeDatabase(), + CoreApp.initializeDatabase(), + CoreConfig.initializeDatabase(), + CoreCronDelegate.initializeDatabase(), + CoreFilepool.initializeDatabase(), + CoreLocalNotifications.initializeDatabase(), + CoreSites.initializeDatabase(), ]); } diff --git a/src/core/initializers/load-update-manager.ts b/src/core/initializers/load-update-manager.ts index d5a530d2b..fdfc913f9 100644 --- a/src/core/initializers/load-update-manager.ts +++ b/src/core/initializers/load-update-manager.ts @@ -15,5 +15,5 @@ import { CoreUpdateManager } from '@services/update-manager'; export default async function(): Promise { - await CoreUpdateManager.instance.load(); + await CoreUpdateManager.load(); } diff --git a/src/core/initializers/override-window-open.ts b/src/core/initializers/override-window-open.ts index 78e7c0bf5..af2eb11e9 100644 --- a/src/core/initializers/override-window-open.ts +++ b/src/core/initializers/override-window-open.ts @@ -15,7 +15,7 @@ import { Platform } from '@singletons'; export default async function(): Promise { - await Platform.instance.ready(); + await Platform.ready(); if (!window.cordova?.InAppBrowser) { return; diff --git a/src/core/initializers/restore-session.ts b/src/core/initializers/restore-session.ts index 55a6b1ad7..73296a92b 100644 --- a/src/core/initializers/restore-session.ts +++ b/src/core/initializers/restore-session.ts @@ -15,5 +15,5 @@ import { CoreSites } from '@services/sites'; export default async function(): Promise { - await CoreSites.instance.restoreSession(); + await CoreSites.restoreSession(); } diff --git a/src/core/initializers/wait-for-platform-ready.ts b/src/core/initializers/wait-for-platform-ready.ts index d0ad780c2..483289334 100644 --- a/src/core/initializers/wait-for-platform-ready.ts +++ b/src/core/initializers/wait-for-platform-ready.ts @@ -15,5 +15,5 @@ import { Platform } from '@singletons'; export default async function(): Promise { - await Platform.instance.ready(); + await Platform.ready(); } diff --git a/src/core/initializers/watch-screen-viewport.ts b/src/core/initializers/watch-screen-viewport.ts index e11d2d78b..23e1210b0 100644 --- a/src/core/initializers/watch-screen-viewport.ts +++ b/src/core/initializers/watch-screen-viewport.ts @@ -15,5 +15,5 @@ import { CoreScreen } from '@services/screen'; export default function(): void { - CoreScreen.instance.watchViewport(); + CoreScreen.watchViewport(); } diff --git a/src/core/pipes/bytes-to-size.ts b/src/core/pipes/bytes-to-size.ts index 97d18678b..36e78f737 100644 --- a/src/core/pipes/bytes-to-size.ts +++ b/src/core/pipes/bytes-to-size.ts @@ -49,7 +49,7 @@ export class CoreBytesToSizePipe implements PipeTransform { value = numberValue; } - return CoreTextUtils.instance.bytesToSize(value); + return CoreTextUtils.bytesToSize(value); } } diff --git a/src/core/pipes/date-day-or-time.ts b/src/core/pipes/date-day-or-time.ts index 6b8f68714..504ce72b6 100644 --- a/src/core/pipes/date-day-or-time.ts +++ b/src/core/pipes/date-day-or-time.ts @@ -62,10 +62,10 @@ export class CoreDateDayOrTimePipe implements PipeTransform { } return moment(timestamp * 1000).calendar(null, { - sameDay: CoreTimeUtils.instance.convertPHPToMoment(Translate.instance.instant('core.strftimetime')), - lastDay: Translate.instance.instant('core.dflastweekdate'), - lastWeek: Translate.instance.instant('core.dflastweekdate'), - sameElse: CoreTimeUtils.instance.convertPHPToMoment(Translate.instance.instant('core.strftimedatefullshort')), + sameDay: CoreTimeUtils.convertPHPToMoment(Translate.instant('core.strftimetime')), + lastDay: Translate.instant('core.dflastweekdate'), + lastWeek: Translate.instant('core.dflastweekdate'), + sameElse: CoreTimeUtils.convertPHPToMoment(Translate.instant('core.strftimedatefullshort')), }); } diff --git a/src/core/pipes/duration.ts b/src/core/pipes/duration.ts index 45d343f69..e1c666289 100644 --- a/src/core/pipes/duration.ts +++ b/src/core/pipes/duration.ts @@ -48,7 +48,7 @@ export class CoreDurationPipe implements PipeTransform { seconds = numberSeconds; } - return CoreTimeUtils.instance.formatTime(seconds); + return CoreTimeUtils.formatTime(seconds); } } diff --git a/src/core/pipes/format-date.ts b/src/core/pipes/format-date.ts index 7be53b6dc..960ec19c0 100644 --- a/src/core/pipes/format-date.ts +++ b/src/core/pipes/format-date.ts @@ -64,7 +64,7 @@ export class CoreFormatDatePipe implements PipeTransform { convert = format.indexOf('core.df') != 0; } - return CoreTimeUtils.instance.userDate(timestamp, format, convert); + return CoreTimeUtils.userDate(timestamp, format, convert); } } diff --git a/src/core/pipes/seconds-to-hms.ts b/src/core/pipes/seconds-to-hms.ts index 047b24ab4..9b3969cf3 100644 --- a/src/core/pipes/seconds-to-hms.ts +++ b/src/core/pipes/seconds-to-hms.ts @@ -62,8 +62,8 @@ export class CoreSecondsToHMSPipe implements PipeTransform { const minutes = Math.floor(seconds / CoreConstants.SECONDS_MINUTE); seconds -= minutes * CoreConstants.SECONDS_MINUTE; - return CoreTextUtils.instance.twoDigits(hours) + ':' + CoreTextUtils.instance.twoDigits(minutes) + ':' + - CoreTextUtils.instance.twoDigits(seconds); + return CoreTextUtils.twoDigits(hours) + ':' + CoreTextUtils.twoDigits(minutes) + ':' + + CoreTextUtils.twoDigits(seconds); } } diff --git a/src/core/pipes/time-ago.ts b/src/core/pipes/time-ago.ts index 4d63558cf..ea2657c53 100644 --- a/src/core/pipes/time-ago.ts +++ b/src/core/pipes/time-ago.ts @@ -49,7 +49,7 @@ export class CoreTimeAgoPipe implements PipeTransform { timestamp = numberTimestamp; } - return Translate.instance.instant('core.ago', { $a: moment(timestamp * 1000).fromNow(true) }); + return Translate.instant('core.ago', { $a: moment(timestamp * 1000).fromNow(true) }); } } diff --git a/src/core/services/app.ts b/src/core/services/app.ts index f00f28944..808976e5a 100644 --- a/src/core/services/app.ts +++ b/src/core/services/app.ts @@ -66,7 +66,7 @@ export class CoreAppProvider { constructor() { this.schemaVersionsManager = new Promise(resolve => this.resolveSchemaVersionsManager = resolve); - this.db = CoreDB.instance.getDB(DBNAME); + this.db = CoreDB.getDB(DBNAME); this.logger = CoreLogger.getInstance('CoreAppProvider'); // @todo @@ -131,7 +131,7 @@ export class CoreAppProvider { */ closeKeyboard(): void { if (this.isMobile()) { - Keyboard.instance.hide(); + Keyboard.hide(); } } @@ -214,7 +214,7 @@ export class CoreAppProvider { return 0; } - return Number(Device.instance.version?.split('.')[0]); + return Number(Device.version?.split('.')[0]); } /** @@ -233,7 +233,7 @@ export class CoreAppProvider { * @return Whether the app is running in an Android mobile or tablet device. */ isAndroid(): boolean { - return this.isMobile() && Platform.instance.is('android'); + return this.isMobile() && Platform.is('android'); } /** @@ -252,7 +252,7 @@ export class CoreAppProvider { * @return Whether the app is running in an iOS mobile or tablet device. */ isIOS(): boolean { - return this.isMobile() && !Platform.instance.is('android'); + return this.isMobile() && !Platform.is('android'); } /** @@ -318,7 +318,7 @@ export class CoreAppProvider { * @return Whether the app is running in a mobile or tablet device. */ isMobile(): boolean { - return Platform.instance.is('cordova'); + return Platform.is('cordova'); } /** @@ -327,7 +327,7 @@ export class CoreAppProvider { * @return Whether the app the current window is wider than a mobile. */ isWide(): boolean { - return Platform.instance.width() > 768; + return Platform.width() > 768; } /** @@ -340,8 +340,8 @@ export class CoreAppProvider { return false; } - let online = Network.instance.type !== null && Network.instance.type != Network.instance.Connection.NONE && - Network.instance.type != Network.instance.Connection.UNKNOWN; + let online = Network.type !== null && Network.type != Network.Connection.NONE && + Network.type != Network.Connection.UNKNOWN; // Double check we are not online because we cannot rely 100% in Cordova APIs. Also, check it in browser. if (!online && navigator.onLine) { @@ -357,17 +357,17 @@ export class CoreAppProvider { * @return Whether the device uses a limited connection. */ isNetworkAccessLimited(): boolean { - const type = Network.instance.type; + const type = Network.type; if (type === null) { // Plugin not defined, probably in browser. return false; } const limited = [ - Network.instance.Connection.CELL_2G, - Network.instance.Connection.CELL_3G, - Network.instance.Connection.CELL_4G, - Network.instance.Connection.CELL, + Network.Connection.CELL_2G, + Network.Connection.CELL_3G, + Network.Connection.CELL_4G, + Network.Connection.CELL, ]; return limited.indexOf(type) > -1; @@ -398,7 +398,7 @@ export class CoreAppProvider { openKeyboard(): void { // Open keyboard is not supported in desktop and in iOS. if (this.isAndroid()) { - Keyboard.instance.show(); + Keyboard.show(); } } @@ -457,7 +457,7 @@ export class CoreAppProvider { * NOT when the browser is opened. */ startSSOAuthentication(): void { - this.ssoAuthenticationDeferred = CoreUtils.instance.promiseDefer(); + this.ssoAuthenticationDeferred = CoreUtils.promiseDefer(); // Resolve it automatically after 10 seconds (it should never take that long). const cancelTimeout = setTimeout(() => this.finishSSOAuthentication(), 10000); @@ -503,7 +503,7 @@ export class CoreAppProvider { * @param timeout Maximum time to wait, use null to wait forever. */ async waitForResume(timeout: number | null = null): Promise { - let deferred: PromiseDefer | null = CoreUtils.instance.promiseDefer(); + let deferred: PromiseDefer | null = CoreUtils.promiseDefer(); const stopWaiting = () => { if (!deferred) { @@ -517,7 +517,7 @@ export class CoreAppProvider { deferred = null; }; - const resumeSubscription = Platform.instance.resume.subscribe(stopWaiting); + const resumeSubscription = Platform.resume.subscribe(stopWaiting); const timeoutId = timeout ? setTimeout(stopWaiting, timeout) : false; await deferred.promise; @@ -669,7 +669,7 @@ export class CoreAppProvider { } -export class CoreApp extends makeSingleton(CoreAppProvider) {} +export const CoreApp = makeSingleton(CoreAppProvider, ['isAndroid']); /** * Data stored for a redirect to another page/site. diff --git a/src/core/services/config.ts b/src/core/services/config.ts index edc5e22d1..37c65708e 100644 --- a/src/core/services/config.ts +++ b/src/core/services/config.ts @@ -38,12 +38,12 @@ export class CoreConfigProvider { */ async initializeDatabase(): Promise { try { - await CoreApp.instance.createTablesFromSchema(APP_SCHEMA); + await CoreApp.createTablesFromSchema(APP_SCHEMA); } catch (e) { // Ignore errors. } - this.resolveAppDB(CoreApp.instance.getDB()); + this.resolveAppDB(CoreApp.getDB()); } /** @@ -96,4 +96,4 @@ export class CoreConfigProvider { } -export class CoreConfig extends makeSingleton(CoreConfigProvider) {} +export const CoreConfig = makeSingleton(CoreConfigProvider); diff --git a/src/core/services/cron.ts b/src/core/services/cron.ts index b8eea95cb..4fabd91c0 100644 --- a/src/core/services/cron.ts +++ b/src/core/services/cron.ts @@ -49,7 +49,7 @@ export class CoreCronDelegateService { this.logger = CoreLogger.getInstance('CoreCronDelegate'); // When the app is re-connected, start network handlers that were stopped. - Network.instance.onConnect().subscribe(() => { + Network.onConnect().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. zone.run(() => { this.startNetworkHandlers(); @@ -62,12 +62,12 @@ export class CoreCronDelegateService { */ async initializeDatabase(): Promise { try { - await CoreApp.instance.createTablesFromSchema(APP_SCHEMA); + await CoreApp.createTablesFromSchema(APP_SCHEMA); } catch (e) { // Ignore errors. } - this.resolveAppDB(CoreApp.instance.getDB()); + this.resolveAppDB(CoreApp.getDB()); } /** @@ -91,7 +91,7 @@ export class CoreCronDelegateService { const usesNetwork = this.handlerUsesNetwork(name); const isSync = !force && this.isHandlerSync(name); - if (usesNetwork && !CoreApp.instance.isOnline()) { + if (usesNetwork && !CoreApp.isOnline()) { // Offline, stop executing. const message = `Cannot execute handler because device is offline: ${name}`; this.logger.debug(message); @@ -102,9 +102,9 @@ export class CoreCronDelegateService { if (isSync) { // Check network connection. - const syncOnlyOnWifi = await CoreConfig.instance.get(CoreConstants.SETTINGS_SYNC_ONLY_ON_WIFI, false); + const syncOnlyOnWifi = await CoreConfig.get(CoreConstants.SETTINGS_SYNC_ONLY_ON_WIFI, false); - if (syncOnlyOnWifi && !CoreApp.instance.isWifi()) { + if (syncOnlyOnWifi && !CoreApp.isWifi()) { // Cannot execute in this network connection, retry soon. const message = `Cannot execute handler because device is using limited connection: ${name}`; this.logger.debug(message); @@ -115,13 +115,13 @@ export class CoreCronDelegateService { } // Add the execution to the queue. - this.queuePromise = CoreUtils.instance.ignoreErrors(this.queuePromise).then(async () => { + this.queuePromise = CoreUtils.ignoreErrors(this.queuePromise).then(async () => { try { await this.executeHandler(name, force, siteId); this.logger.debug(`Execution of handler '${name}' was a success.`); - await CoreUtils.instance.ignoreErrors(this.setHandlerLastExecutionTime(name, Date.now())); + await CoreUtils.ignoreErrors(this.setHandlerLastExecutionTime(name, Date.now())); this.scheduleNextExecution(name); @@ -181,7 +181,7 @@ export class CoreCronDelegateService { } } - await CoreUtils.instance.allPromises(promises); + await CoreUtils.allPromises(promises); } /** @@ -393,7 +393,7 @@ export class CoreCronDelegateService { this.handlers[name].timeout = window.setTimeout(() => { delete this.handlers[name].timeout; - CoreUtils.instance.ignoreErrors(this.checkAndExecuteHandler(name)); + CoreUtils.ignoreErrors(this.checkAndExecuteHandler(name)); }, timeToNextExecution); } @@ -476,7 +476,7 @@ export class CoreCronDelegateService { } -export class CoreCronDelegate extends makeSingleton(CoreCronDelegateService) {} +export const CoreCronDelegate = makeSingleton(CoreCronDelegateService); /** diff --git a/src/core/services/db.ts b/src/core/services/db.ts index 5ebe04d74..1d1b2efea 100644 --- a/src/core/services/db.ts +++ b/src/core/services/db.ts @@ -37,7 +37,7 @@ export class CoreDbProvider { */ getDB(name: string, forceNew?: boolean): SQLiteDB { if (typeof this.dbInstances[name] === 'undefined' || forceNew) { - if (Platform.instance.is('cordova')) { + if (Platform.is('cordova')) { this.dbInstances[name] = new SQLiteDB(name); } else { this.dbInstances[name] = new SQLiteDBMock(name); @@ -65,13 +65,13 @@ export class CoreDbProvider { // In WebSQL we cannot delete the database, just empty it. return db.emptyDatabase(); } else { - return SQLite.instance.deleteDatabase({ + return SQLite.deleteDatabase({ name, location: 'default', }); } - } else if (Platform.instance.is('cordova')) { - return SQLite.instance.deleteDatabase({ + } else if (Platform.is('cordova')) { + return SQLite.deleteDatabase({ name, location: 'default', }); @@ -80,4 +80,4 @@ export class CoreDbProvider { } -export class CoreDB extends makeSingleton(CoreDbProvider) {} +export const CoreDB = makeSingleton(CoreDbProvider); diff --git a/src/core/services/file-helper.ts b/src/core/services/file-helper.ts index 11a29b0e1..426568b15 100644 --- a/src/core/services/file-helper.ts +++ b/src/core/services/file-helper.ts @@ -53,7 +53,7 @@ export class CoreFileHelperProvider { onProgress?: CoreFileHelperOnProgress, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const fileUrl = file.fileurl; const timemodified = this.getFileTimemodified(file); @@ -68,28 +68,28 @@ export class CoreFileHelperProvider { return; } - if (!CoreUrlUtils.instance.isLocalFileUrl(url)) { + if (!CoreUrlUtils.isLocalFileUrl(url)) { /* In iOS, if we use the same URL in embedded browser and background download then the download only downloads a few bytes (cached ones). Add a hash to the URL so both URLs are different. */ url = url + '#moodlemobile-embedded'; try { - await CoreUtils.instance.openOnlineFile(url); + await CoreUtils.openOnlineFile(url); return; } catch (error) { // Error opening the file, some apps don't allow opening online files. - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw error; } // Get the state. if (!state) { - state = await CoreFilepool.instance.getFileStateByUrl(siteId, fileUrl, timemodified); + state = await CoreFilepool.getFileStateByUrl(siteId, fileUrl, timemodified); } if (state == CoreConstants.DOWNLOADING) { - throw new CoreError(Translate.instance.instant('core.erroropenfiledownloading')); + throw new CoreError(Translate.instant('core.erroropenfiledownloading')); } if (state === CoreConstants.NOT_DOWNLOADED) { @@ -97,12 +97,12 @@ export class CoreFileHelperProvider { url = await this.downloadFile(fileUrl, component, componentId, timemodified, onProgress, file, siteId); } else { // File is outdated and can't be opened in online, return the local URL. - url = await CoreFilepool.instance.getInternalUrlByUrl(siteId, fileUrl); + url = await CoreFilepool.getInternalUrlByUrl(siteId, fileUrl); } } } - return CoreUtils.instance.openFile(url); + return CoreUtils.openFile(url); } /** @@ -128,28 +128,28 @@ export class CoreFileHelperProvider { onProgress?: CoreFileHelperOnProgress, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const fixedUrl = await site.checkAndFixPluginfileURL(fileUrl); - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { // Use the online URL. return fixedUrl; } if (!state) { // Calculate the state. - state = await CoreFilepool.instance.getFileStateByUrl(siteId, fileUrl, timemodified); + state = await CoreFilepool.getFileStateByUrl(siteId, fileUrl, timemodified); } // The file system is available. - const isWifi = CoreApp.instance.isWifi(); - const isOnline = CoreApp.instance.isOnline(); + const isWifi = CoreApp.isWifi(); + const isOnline = CoreApp.isOnline(); if (state == CoreConstants.DOWNLOADED) { // File is downloaded, get the local file URL. - return CoreFilepool.instance.getUrlByUrl(siteId, fileUrl, component, componentId, timemodified, false, false, file); + return CoreFilepool.getUrlByUrl(siteId, fileUrl, component, componentId, timemodified, false, false, file); } else { if (!isOnline && !this.isStateDownloaded(state)) { // Not downloaded and user is offline, reject. @@ -161,7 +161,7 @@ export class CoreFileHelperProvider { onProgress({ calculating: true }); } - const shouldDownloadFirst = await CoreFilepool.instance.shouldDownloadFileBeforeOpen(fixedUrl, file.filesize || 0); + const shouldDownloadFirst = await CoreFilepool.shouldDownloadFileBeforeOpen(fixedUrl, file.filesize || 0); if (shouldDownloadFirst) { // Download the file first. if (state == CoreConstants.DOWNLOADING) { @@ -183,7 +183,7 @@ export class CoreFileHelperProvider { return fixedUrl; } else { // Outdated but offline, so we return the local URL. - return CoreFilepool.instance.getUrlByUrl( + return CoreFilepool.getUrlByUrl( siteId, fileUrl, component, @@ -218,17 +218,17 @@ export class CoreFileHelperProvider { file?: CoreWSExternalFile, siteId?: string, ): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Get the site and check if it can download files. - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (!site.canDownloadFiles()) { - throw new CoreError(Translate.instance.instant('core.cannotdownloadfiles')); + throw new CoreError(Translate.instant('core.cannotdownloadfiles')); } try { - return await CoreFilepool.instance.downloadUrl( + return await CoreFilepool.downloadUrl( siteId, fileUrl, false, @@ -241,10 +241,10 @@ export class CoreFileHelperProvider { ); } catch (error) { // Download failed, check the state again to see if the file was downloaded before. - const state = await CoreFilepool.instance.getFileStateByUrl(siteId, fileUrl, timemodified); + const state = await CoreFilepool.getFileStateByUrl(siteId, fileUrl, timemodified); if (this.isStateDownloaded(state)) { - return CoreFilepool.instance.getInternalUrlByUrl(siteId, fileUrl); + return CoreFilepool.getInternalUrlByUrl(siteId, fileUrl); } else { throw error; } @@ -338,16 +338,16 @@ export class CoreFileHelperProvider { const fileUrl = file.fileurl; try { - const siteId = CoreSites.instance.getCurrentSiteId(); + const siteId = CoreSites.getCurrentSiteId(); - const path = await CoreFilepool.instance.getFilePathByUrl(siteId, fileUrl); - const fileEntry = await CoreFile.instance.getFile(path); - const fileObject = await CoreFile.instance.getFileObjectFromFileEntry(fileEntry); + const path = await CoreFilepool.getFilePathByUrl(siteId, fileUrl); + const fileEntry = await CoreFile.getFile(path); + const fileObject = await CoreFile.getFileObjectFromFileEntry(fileEntry); return fileObject.size; } catch (error) { // Error getting the file, maybe it's not downloaded. Get remote size. - const size = await CoreWS.instance.getRemoteFileSize(fileUrl); + const size = await CoreWS.getRemoteFileSize(fileUrl); if (size === -1) { throw new CoreError(`Couldn't determine file size: ${fileUrl}`); @@ -359,7 +359,7 @@ export class CoreFileHelperProvider { // If it's a local file, get its size. if ('name' in file) { - const fileObject = await CoreFile.instance.getFileObjectFromFileEntry(file); + const fileObject = await CoreFile.getFileObjectFromFileEntry(file); return fileObject.size; } @@ -392,10 +392,10 @@ export class CoreFileHelperProvider { * @return Promise resolved if confirmed, rejected otherwise. */ showConfirmOpenUnsupportedFile(onlyDownload?: boolean): Promise { - const message = Translate.instance.instant('core.cannotopeninapp' + (onlyDownload ? 'download' : '')); - const okButton = Translate.instance.instant(onlyDownload ? 'core.downloadfile' : 'core.openfile'); + const message = Translate.instant('core.cannotopeninapp' + (onlyDownload ? 'download' : '')); + const okButton = Translate.instant(onlyDownload ? 'core.downloadfile' : 'core.openfile'); - return CoreDomUtils.instance.showConfirm(message, undefined, okButton, undefined, { cssClass: 'core-modal-force-on-top' }); + return CoreDomUtils.showConfirm(message, undefined, okButton, undefined, { cssClass: 'core-modal-force-on-top' }); } /** @@ -405,7 +405,7 @@ export class CoreFileHelperProvider { * @return bool. */ isFileTypeExcludedInApp(fileType: string): boolean { - const currentSite = CoreSites.instance.getCurrentSite(); + const currentSite = CoreSites.getCurrentSite(); const fileTypeExcludeList = currentSite?.getStoredConfig('tool_mobile_filetypeexclusionlist'); if (!fileTypeExcludeList) { @@ -419,6 +419,6 @@ export class CoreFileHelperProvider { } -export class CoreFileHelper extends makeSingleton(CoreFileHelperProvider) {} +export const CoreFileHelper = makeSingleton(CoreFileHelperProvider); export type CoreFileHelperOnProgress = (event?: ProgressEvent | { calculating: true }) => void; diff --git a/src/core/services/file-session.ts b/src/core/services/file-session.ts index 5ca4dda27..6f9caeace 100644 --- a/src/core/services/file-session.ts +++ b/src/core/services/file-session.ts @@ -40,7 +40,7 @@ export class CoreFileSessionProvider { * @param siteId Site ID. If not defined, current site. */ addFile(component: string, id: string | number, file: CoreWSExternalFile | FileEntry, siteId?: string): void { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); this.initFileArea(component, id, siteId); @@ -55,7 +55,7 @@ export class CoreFileSessionProvider { * @param siteId Site ID. If not defined, current site. */ clearFiles(component: string, id: string | number, siteId?: string): void { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.files[siteId] && this.files[siteId][component] && this.files[siteId][component][id]) { this.files[siteId][component][id] = []; } @@ -70,7 +70,7 @@ export class CoreFileSessionProvider { * @return Array of files in session. */ getFiles(component: string, id: string | number, siteId?: string): (CoreWSExternalFile | FileEntry)[] { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.files[siteId] && this.files[siteId][component] && this.files[siteId][component][id]) { return this.files[siteId][component][id]; } @@ -108,7 +108,7 @@ export class CoreFileSessionProvider { * @param siteId Site ID. If not defined, current site. */ removeFile(component: string, id: string | number, file: CoreWSExternalFile | FileEntry, siteId?: string): void { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.files[siteId] && this.files[siteId][component] && this.files[siteId][component][id]) { const position = this.files[siteId][component][id].indexOf(file); if (position != -1) { @@ -126,7 +126,7 @@ export class CoreFileSessionProvider { * @param siteId Site ID. If not defined, current site. */ removeFileByIndex(component: string, id: string | number, index: number, siteId?: string): void { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (this.files[siteId] && this.files[siteId][component] && this.files[siteId][component][id] && index >= 0 && index < this.files[siteId][component][id].length) { this.files[siteId][component][id].splice(index, 1); @@ -142,7 +142,7 @@ export class CoreFileSessionProvider { * @param siteId Site ID. If not defined, current site. */ setFiles(component: string, id: string | number, newFiles: (CoreWSExternalFile | FileEntry)[], siteId?: string): void { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); this.initFileArea(component, id, siteId); @@ -151,4 +151,4 @@ export class CoreFileSessionProvider { } -export class CoreFileSession extends makeSingleton(CoreFileSessionProvider) {} +export const CoreFileSession = makeSingleton(CoreFileSessionProvider); diff --git a/src/core/services/file.ts b/src/core/services/file.ts index 529b96334..94b608103 100644 --- a/src/core/services/file.ts +++ b/src/core/services/file.ts @@ -137,12 +137,12 @@ export class CoreFileProvider { return; } - await Platform.instance.ready(); + await Platform.ready(); - if (CoreApp.instance.isAndroid()) { - this.basePath = File.instance.externalApplicationStorageDirectory || this.basePath; - } else if (CoreApp.instance.isIOS()) { - this.basePath = File.instance.documentsDirectory || this.basePath; + if (CoreApp.isAndroid()) { + this.basePath = File.externalApplicationStorageDirectory || this.basePath; + } else if (CoreApp.isIOS()) { + this.basePath = File.documentsDirectory || this.basePath; } else if (!this.isAvailable() || this.basePath === '') { this.logger.error('Error getting device OS.'); @@ -172,7 +172,7 @@ export class CoreFileProvider { return this.init().then(() => { this.logger.debug('Get file: ' + path); - return File.instance.resolveLocalFilesystemUrl(this.addBasePathIfNeeded(path)); + return File.resolveLocalFilesystemUrl(this.addBasePathIfNeeded(path)); }).then((entry) => entry); } @@ -186,7 +186,7 @@ export class CoreFileProvider { return this.init().then(() => { this.logger.debug('Get directory: ' + path); - return File.instance.resolveDirectoryUrl(this.addBasePathIfNeeded(path)); + return File.resolveDirectoryUrl(this.addBasePathIfNeeded(path)); }); } @@ -225,11 +225,11 @@ export class CoreFileProvider { if (isDirectory) { this.logger.debug('Create dir ' + path + ' in ' + base); - return File.instance.createDir(base, path, !failIfExists); + return File.createDir(base, path, !failIfExists); } else { this.logger.debug('Create file ' + path + ' in ' + base); - return File.instance.createFile(base, path, !failIfExists); + return File.createFile(base, path, !failIfExists); } } else { // The file plugin doesn't allow creating more than 1 level at a time (e.g. tmp/folder). @@ -239,7 +239,7 @@ export class CoreFileProvider { this.logger.debug('Create dir ' + firstDir + ' in ' + base); - const newDirEntry = await File.instance.createDir(base, firstDir, true); + const newDirEntry = await File.createDir(base, firstDir, true); return this.create(isDirectory, restOfPath, failIfExists, newDirEntry.toURL()); } @@ -284,7 +284,7 @@ export class CoreFileProvider { path = this.removeStartingSlash(path.replace(this.basePath, '')); this.logger.debug('Remove directory: ' + path); - await File.instance.removeRecursively(this.basePath, path); + await File.removeRecursively(this.basePath, path); } /** @@ -301,13 +301,13 @@ export class CoreFileProvider { this.logger.debug('Remove file: ' + path); try { - await File.instance.removeFile(this.basePath, path); + await File.removeFile(this.basePath, path); } catch (error) { // The delete can fail if the path has encoded characters. Try again if that's the case. const decodedPath = decodeURI(path); if (decodedPath != path) { - await File.instance.removeFile(this.basePath, decodedPath); + await File.removeFile(this.basePath, decodedPath); } else { throw error; } @@ -337,7 +337,7 @@ export class CoreFileProvider { path = this.removeStartingSlash(path.replace(this.basePath, '')); this.logger.debug('Get contents of dir: ' + path); - const result = await File.instance.listDir(this.basePath, path); + const result = await File.listDir(this.basePath, path); return <(FileEntry | DirectoryEntry)[]> result; } @@ -445,8 +445,8 @@ export class CoreFileProvider { * @return Promise resolved with the estimated free space in bytes. */ calculateFreeSpace(): Promise { - return File.instance.getFreeDiskSpace().then((size) => { - if (CoreApp.instance.isIOS()) { + return File.getFreeDiskSpace().then((size) => { + if (CoreApp.isIOS()) { // In iOS the size is in bytes. return Number(size); } @@ -463,7 +463,7 @@ export class CoreFileProvider { * @return The file name normalized. */ normalizeFileName(filename: string): string { - filename = CoreTextUtils.instance.decodeURIComponent(filename); + filename = CoreTextUtils.decodeURIComponent(filename); return filename; } @@ -488,14 +488,14 @@ export class CoreFileProvider { switch (format) { case CoreFileFormat.FORMATDATAURL: - return File.instance.readAsDataURL(this.basePath, path); + return File.readAsDataURL(this.basePath, path); case CoreFileFormat.FORMATBINARYSTRING: - return File.instance.readAsBinaryString(this.basePath, path); + return File.readAsBinaryString(this.basePath, path); case CoreFileFormat.FORMATARRAYBUFFER: - return File.instance.readAsArrayBuffer(this.basePath, path); + return File.readAsArrayBuffer(this.basePath, path); case CoreFileFormat.FORMATJSON: - return File.instance.readAsText(this.basePath, path).then((text) => { - const parsed = CoreTextUtils.instance.parseJSON(text, null); + return File.readAsText(this.basePath, path).then((text) => { + const parsed = CoreTextUtils.parseJSON(text, null); if (parsed == null && text != null) { throw new CoreError('Error parsing JSON file: ' + path); @@ -504,7 +504,7 @@ export class CoreFileProvider { return parsed; }); default: - return File.instance.readAsText(this.basePath, path); + return File.readAsText(this.basePath, path); } } @@ -526,7 +526,7 @@ export class CoreFileProvider { if (event.target?.result !== undefined && event.target.result !== null) { if (format == CoreFileFormat.FORMATJSON) { // Convert to object. - const parsed = CoreTextUtils.instance.parseJSON( event.target.result, null); + const parsed = CoreTextUtils.parseJSON( event.target.result, null); if (parsed == null) { reject('Error parsing JSON file.'); @@ -591,12 +591,12 @@ export class CoreFileProvider { if (this.isHTMLAPI && (typeof data == 'string' || data.toString() == '[object ArrayBuffer]')) { // We need to write Blobs. - const extension = CoreMimetypeUtils.instance.getFileExtension(path); - const type = extension ? CoreMimetypeUtils.instance.getMimeType(extension) : ''; + const extension = CoreMimetypeUtils.getFileExtension(path); + const type = extension ? CoreMimetypeUtils.getMimeType(extension) : ''; data = new Blob([data], { type: type || 'text/plain' }); } - await File.instance.writeFile(this.basePath, path, data, { replace: !append, append: !!append }); + await File.writeFile(this.basePath, path, data, { replace: !append, append: !!append }); return fileEntry; } @@ -660,7 +660,7 @@ export class CoreFileProvider { * @return Promise to be resolved when the file is retrieved. */ getExternalFile(fullPath: string): Promise { - return File.instance.resolveLocalFilesystemUrl(fullPath).then((entry) => entry); + return File.resolveLocalFilesystemUrl(fullPath).then((entry) => entry); } /** @@ -685,7 +685,7 @@ export class CoreFileProvider { const directory = fullPath.substring(0, fullPath.lastIndexOf('/')); const filename = fullPath.substr(fullPath.lastIndexOf('/') + 1); - await File.instance.removeFile(directory, filename); + await File.removeFile(directory, filename); } /** @@ -713,9 +713,9 @@ export class CoreFileProvider { async getBasePathToDownload(): Promise { await this.init(); - if (CoreApp.instance.isIOS()) { + if (CoreApp.isIOS()) { // In iOS we want the internal URL (cdvfile://localhost/persistent/...). - const dirEntry = await File.instance.resolveDirectoryUrl(this.basePath); + const dirEntry = await File.resolveDirectoryUrl(this.basePath); return dirEntry.toInternalURL(); } else { @@ -824,8 +824,8 @@ export class CoreFileProvider { } const moveCopyFn: MoveCopyFunction = copy ? - (isDir ? File.instance.copyDir.bind(File.instance) : File.instance.copyFile.bind(File.instance)) : - (isDir ? File.instance.moveDir.bind(File.instance) : File.instance.moveFile.bind(File.instance)); + (isDir ? File.copyDir.bind(File.instance) : File.copyFile.bind(File.instance)) : + (isDir ? File.moveDir.bind(File.instance) : File.moveFile.bind(File.instance)); await this.init(); @@ -907,7 +907,7 @@ export class CoreFileProvider { if (path.indexOf(this.basePath) > -1) { return path; } else { - return CoreTextUtils.instance.concatenatePaths(this.basePath, path); + return CoreTextUtils.concatenatePaths(this.basePath, path); } } @@ -946,16 +946,16 @@ export class CoreFileProvider { if (destFolder && recreateDir) { // Make sure the dest dir doesn't exist already. - await CoreUtils.instance.ignoreErrors(this.removeDir(destFolder)); + await CoreUtils.ignoreErrors(this.removeDir(destFolder)); // Now create the dir, otherwise if any of the ancestor dirs doesn't exist the unzip would fail. await this.createDir(destFolder); } // If destFolder is not set, use same location as ZIP file. We need to use absolute paths (including basePath). - destFolder = this.addBasePathIfNeeded(destFolder || CoreMimetypeUtils.instance.removeExtension(path)); + destFolder = this.addBasePathIfNeeded(destFolder || CoreMimetypeUtils.removeExtension(path)); - const result = await Zip.instance.unzip(fileEntry.toURL(), destFolder, onProgress); + const result = await Zip.unzip(fileEntry.toURL(), destFolder, onProgress); if (result == -1) { throw new CoreError('Unzip failed.'); @@ -1095,12 +1095,12 @@ export class CoreFileProvider { const entries = await this.getDirectoryContents(dirPath); const files = {}; - let fileNameWithoutExtension = CoreMimetypeUtils.instance.removeExtension(fileName); - let extension = CoreMimetypeUtils.instance.getFileExtension(fileName) || defaultExt; + let fileNameWithoutExtension = CoreMimetypeUtils.removeExtension(fileName); + let extension = CoreMimetypeUtils.getFileExtension(fileName) || defaultExt; // Clean the file name. - fileNameWithoutExtension = CoreTextUtils.instance.removeSpecialCharactersForFiles( - CoreTextUtils.instance.decodeURIComponent(fileNameWithoutExtension), + fileNameWithoutExtension = CoreTextUtils.removeSpecialCharactersForFiles( + CoreTextUtils.decodeURIComponent(fileNameWithoutExtension), ); // Index the files by name. @@ -1118,7 +1118,7 @@ export class CoreFileProvider { return this.calculateUniqueName(files, fileNameWithoutExtension + extension); } catch (error) { // Folder doesn't exist, name is unique. Clean it and return it. - return CoreTextUtils.instance.removeSpecialCharactersForFiles(CoreTextUtils.instance.decodeURIComponent(fileName)); + return CoreTextUtils.removeSpecialCharactersForFiles(CoreTextUtils.decodeURIComponent(fileName)); } } @@ -1136,8 +1136,8 @@ export class CoreFileProvider { } // Repeated name. Add a number until we find a free name. - const nameWithoutExtension = CoreMimetypeUtils.instance.removeExtension(name); - let extension = CoreMimetypeUtils.instance.getFileExtension(name); + const nameWithoutExtension = CoreMimetypeUtils.removeExtension(name); + let extension = CoreMimetypeUtils.getFileExtension(name); let num = 1; extension = extension ? '.' + extension : ''; @@ -1156,7 +1156,7 @@ export class CoreFileProvider { */ async clearTmpFolder(): Promise { // Ignore errors because the folder might not exist. - await CoreUtils.instance.ignoreErrors(this.removeDir(CoreFileProvider.TMPFOLDER)); + await CoreUtils.ignoreErrors(this.removeDir(CoreFileProvider.TMPFOLDER)); } /** @@ -1231,7 +1231,7 @@ export class CoreFileProvider { */ getWWWAbsolutePath(): string { if (cordova && cordova.file && cordova.file.applicationDirectory) { - return CoreTextUtils.instance.concatenatePaths(cordova.file.applicationDirectory, 'www'); + return CoreTextUtils.concatenatePaths(cordova.file.applicationDirectory, 'www'); } // Cannot use Cordova to get it, use the WebView URL. @@ -1246,7 +1246,7 @@ export class CoreFileProvider { * @return Converted src. */ convertFileSrc(src: string): string { - return CoreApp.instance.isMobile() ? WebView.instance.convertFileSrc(src) : src; + return CoreApp.isMobile() ? WebView.convertFileSrc(src) : src; } /** @@ -1256,11 +1256,11 @@ export class CoreFileProvider { * @return Unconverted src. */ unconvertFileSrc(src: string): string { - if (!CoreApp.instance.isMobile()) { + if (!CoreApp.isMobile()) { return src; } - const scheme = CoreApp.instance.isIOS() ? CoreConstants.CONFIG.ioswebviewscheme : 'http'; + const scheme = CoreApp.isIOS() ? CoreConstants.CONFIG.ioswebviewscheme : 'http'; return src.replace(scheme + '://localhost/_app_file_', 'file://'); } @@ -1282,11 +1282,11 @@ export class CoreFileProvider { * @return The file name. */ getFileName(file: CoreWSExternalFile | FileEntry): string | undefined { - return CoreUtils.instance.isFileEntry(file) ? file.name : file.filename; + return CoreUtils.isFileEntry(file) ? file.name : file.filename; } } -export class CoreFile extends makeSingleton(CoreFileProvider) {} +export const CoreFile = makeSingleton(CoreFileProvider); type MoveCopyFunction = (path: string, dirName: string, newPath: string, newDirName: string) => Promise; diff --git a/src/core/services/filepool.ts b/src/core/services/filepool.ts index b79075bd0..c81d56178 100644 --- a/src/core/services/filepool.ts +++ b/src/core/services/filepool.ts @@ -105,12 +105,12 @@ export class CoreFilepoolProvider { */ async initializeDatabase(): Promise { try { - await CoreApp.instance.createTablesFromSchema(APP_SCHEMA); + await CoreApp.createTablesFromSchema(APP_SCHEMA); } catch (e) { // Ignore errors. } - this.resolveAppDB(CoreApp.instance.getDB()); + this.resolveAppDB(CoreApp.getDB()); } /** @@ -118,14 +118,14 @@ export class CoreFilepoolProvider { */ protected async init(): Promise { // Waiting for the app to be ready to start processing the queue. - await ApplicationInit.instance.donePromise; + await ApplicationInit.donePromise; this.checkQueueProcessing(); // Start queue when device goes online. - Network.instance.onConnect().subscribe(() => { + Network.onConnect().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { + NgZone.run(() => { this.checkQueueProcessing(); }); }); @@ -147,7 +147,7 @@ export class CoreFilepoolProvider { componentId = this.fixComponentId(componentId); - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const newEntry: CoreFilepoolLinksRecord = { fileId, component, @@ -217,7 +217,7 @@ export class CoreFilepoolProvider { ...data, }; - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await db.insertRecord(FILES_TABLE_NAME, record); } @@ -329,11 +329,11 @@ export class CoreFilepoolProvider { revision?: number, alreadyFixed?: boolean, ): Promise { - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw new CoreError('File system cannot be used.'); } - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (!site.canDownloadFiles()) { throw new CoreError('Site doesn\'t allow downloading files.'); } @@ -471,16 +471,16 @@ export class CoreFilepoolProvider { if (typeof this.sizeCache[fileUrl] != 'undefined') { size = this.sizeCache[fileUrl]; } else { - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { // Cannot check size in offline, stop. - throw new CoreError(Translate.instance.instant('core.cannotconnect')); + throw new CoreError(Translate.instant('core.cannotconnect')); } - size = await CoreWS.instance.getRemoteFileSize(fileUrl); + size = await CoreWS.getRemoteFileSize(fileUrl); } // Calculate the size of the file. - const isWifi = CoreApp.instance.isWifi(); + const isWifi = CoreApp.isWifi(); const sizeUnknown = size <= 0; if (!sizeUnknown) { @@ -515,7 +515,7 @@ export class CoreFilepoolProvider { * is not accessible. Also, this will have no effect if the queue is already running. */ protected checkQueueProcessing(): void { - if (!CoreFile.instance.isAvailable() || !CoreApp.instance.isOnline()) { + if (!CoreFile.isAvailable() || !CoreApp.isOnline()) { this.queueState = CoreFilepoolProvider.QUEUE_PAUSED; return; @@ -536,7 +536,7 @@ export class CoreFilepoolProvider { async clearAllPackagesStatus(siteId: string): Promise { this.logger.debug('Clear all packages status for site ' + siteId); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); // Get all the packages to be able to "notify" the change in the status. const entries: CoreFilepoolPackageEntry[] = await site.getDb().getAllRecords(PACKAGES_TABLE_NAME); // Delete all the entries. @@ -555,7 +555,7 @@ export class CoreFilepoolProvider { * @return Promise resolved when the filepool is cleared. */ async clearFilepool(siteId: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await Promise.all([ db.deleteRecords(FILES_TABLE_NAME), @@ -572,7 +572,7 @@ export class CoreFilepoolProvider { * @return Resolved means yes, rejected means no. */ async componentHasFiles(siteId: string, component: string, componentId?: string | number): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const conditions = { component, componentId: this.fixComponentId(componentId), @@ -671,7 +671,7 @@ export class CoreFilepoolProvider { poolFileObject?: CoreFilepoolFileEntry, ): Promise { const fileId = this.getFileIdByUrl(fileUrl); - const extension = CoreMimetypeUtils.instance.guessExtensionFromUrl(fileUrl); + const extension = CoreMimetypeUtils.guessExtensionFromUrl(fileUrl); const addExtension = typeof filePath == 'undefined'; const path = filePath || (await this.getFilePath(siteId, fileId, extension)); @@ -690,14 +690,14 @@ export class CoreFilepoolProvider { this.filePromises[siteId] = {}; } - this.filePromises[siteId][downloadId] = CoreSites.instance.getSite(siteId).then(async (site) => { + this.filePromises[siteId][downloadId] = CoreSites.getSite(siteId).then(async (site) => { if (!site.canDownloadFiles()) { throw new CoreError('Site doesn\'t allow downloading files.'); } - const entry = await CoreWS.instance.downloadFile(fileUrl, path, addExtension, onProgress); + const entry = await CoreWS.downloadFile(fileUrl, path, addExtension, onProgress); const fileEntry = entry; - await CorePluginFileDelegate.instance.treatDownloadedFile(fileUrl, fileEntry, siteId, onProgress); + await CorePluginFileDelegate.treatDownloadedFile(fileUrl, fileEntry, siteId, onProgress); await this.addFileToPool(siteId, fileId, { downloadTime: Date.now(), @@ -760,7 +760,7 @@ export class CoreFilepoolProvider { if (file.filepath && file.filepath !== '/') { path = file.filepath.substr(1) + path; } - path = CoreTextUtils.instance.concatenatePaths(dirPath, path!); + path = CoreTextUtils.concatenatePaths(dirPath, path!); } if (prefetch) { @@ -780,7 +780,7 @@ export class CoreFilepoolProvider { } }); - return CoreUtils.instance.allPromises(promises); + return CoreUtils.allPromises(promises); } /** @@ -854,7 +854,7 @@ export class CoreFilepoolProvider { if (file.filepath && file.filepath !== '/') { path = file.filepath.substr(1) + path; } - path = CoreTextUtils.instance.concatenatePaths(dirPath, path!); + path = CoreTextUtils.concatenatePaths(dirPath, path!); } if (prefetch) { @@ -968,7 +968,7 @@ export class CoreFilepoolProvider { ): Promise { let alreadyDownloaded = true; - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw new CoreError('File system cannot be used.'); } @@ -985,7 +985,7 @@ export class CoreFilepoolProvider { const finishSuccessfulDownload = (url: string): string => { if (typeof component != 'undefined') { - CoreUtils.instance.ignoreErrors(this.addFileLink(siteId, fileId, component, componentId)); + CoreUtils.ignoreErrors(this.addFileLink(siteId, fileId, component, componentId)); } if (!alreadyDownloaded) { @@ -1001,7 +1001,7 @@ export class CoreFilepoolProvider { if (!fileObject || this.isFileOutdated(fileObject, options.revision, options.timemodified) && - CoreApp.instance.isOnline() && + CoreApp.isOnline() && !ignoreStale ) { throw new CoreError('Needs to be downloaded'); @@ -1041,28 +1041,28 @@ export class CoreFilepoolProvider { extractDownloadableFilesFromHtml(html: string): string[] { let urls: string[] = []; - const element = CoreDomUtils.instance.convertToElement(html); + const element = CoreDomUtils.convertToElement(html); const elements: AnchorOrMediaElement[] = Array.from(element.querySelectorAll('a, img, audio, video, source, track')); for (let i = 0; i < elements.length; i++) { const element = elements[i]; const url = 'href' in element ? element.href : element.src; - if (url && CoreUrlUtils.instance.isDownloadableUrl(url) && urls.indexOf(url) == -1) { + if (url && CoreUrlUtils.isDownloadableUrl(url) && urls.indexOf(url) == -1) { urls.push(url); } // Treat video poster. if (element.tagName == 'VIDEO' && element.getAttribute('poster')) { const poster = element.getAttribute('poster'); - if (poster && CoreUrlUtils.instance.isDownloadableUrl(poster) && urls.indexOf(poster) == -1) { + if (poster && CoreUrlUtils.isDownloadableUrl(poster) && urls.indexOf(poster) == -1) { urls.push(poster); } } } // Now get other files from plugin file handlers. - urls = urls.concat(CorePluginFileDelegate.instance.getDownloadableFilesFromHTML(element)); + urls = urls.concat(CorePluginFileDelegate.getDownloadableFilesFromHTML(element)); return urls; } @@ -1096,8 +1096,8 @@ export class CoreFilepoolProvider { return; } - const db = await CoreSites.instance.getSiteDb(siteId); - const extension = CoreMimetypeUtils.instance.getFileExtension(entry.path); + const db = await CoreSites.getSiteDb(siteId); + const extension = CoreMimetypeUtils.getFileExtension(entry.path); if (!extension) { // Files does not have extension. Invalidate file (stale = true). // Minor problem: file will remain in the filesystem once downloaded again. @@ -1110,7 +1110,7 @@ export class CoreFilepoolProvider { // File has extension. Save extension, and add extension to path. const fileId = entry.fileId; - entry.fileId = CoreMimetypeUtils.instance.removeExtension(fileId); + entry.fileId = CoreMimetypeUtils.removeExtension(fileId); entry.extension = extension; await db.updateRecords(FILES_TABLE_NAME, entry, { fileId }); @@ -1159,8 +1159,8 @@ export class CoreFilepoolProvider { * @return Promise resolved with the file data to use. */ protected async fixPluginfileURL(siteId: string, fileUrl: string, timemodified: number = 0): Promise { - const file = await CorePluginFileDelegate.instance.getDownloadableFile({ fileurl: fileUrl, timemodified }); - const site = await CoreSites.instance.getSite(siteId); + const file = await CorePluginFileDelegate.getDownloadableFile({ fileurl: fileUrl, timemodified }); + const site = await CoreSites.getSite(siteId); file.fileurl = await site.checkAndFixPluginfileURL(file.fileurl); @@ -1201,14 +1201,14 @@ export class CoreFilepoolProvider { * @return Resolved with the URL. Rejected otherwise. */ async getDirectoryUrlByUrl(siteId: string, fileUrl: string): Promise { - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw new CoreError('File system cannot be used.'); } const file = await this.fixPluginfileURL(siteId, fileUrl); const fileId = this.getFileIdByUrl(file.fileurl); const filePath = await this.getFilePath(siteId, fileId, ''); - const dirEntry = await CoreFile.instance.getDir(filePath); + const dirEntry = await CoreFile.getDir(filePath); return dirEntry.toURL(); } @@ -1270,7 +1270,7 @@ export class CoreFilepoolProvider { url = this.removeRevisionFromUrl(url); // Decode URL. - url = CoreTextUtils.instance.decodeHTML(CoreTextUtils.instance.decodeURIComponent(url)); + url = CoreTextUtils.decodeHTML(CoreTextUtils.decodeURIComponent(url)); if (url.indexOf('/webservice/pluginfile') !== -1) { // Remove attributes that do not matter. @@ -1294,7 +1294,7 @@ export class CoreFilepoolProvider { * @return Promise resolved with the links. */ protected async getFileLinks(siteId: string, fileId: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const items = await db.getRecords(LINKS_TABLE_NAME, { fileId }); items.forEach((item) => { @@ -1354,7 +1354,7 @@ export class CoreFilepoolProvider { * @return The root path to the filepool of the site. */ getFilepoolFolderPath(siteId: string): string { - return CoreFile.instance.getSiteFolder(siteId) + '/' + CoreFilepoolProvider.FOLDER; + return CoreFile.getSiteFolder(siteId) + '/' + CoreFilepoolProvider.FOLDER; } /** @@ -1366,7 +1366,7 @@ export class CoreFilepoolProvider { * @return Promise resolved with the files on success. */ async getFilesByComponent(siteId: string, component: string, componentId?: string | number): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const items = await this.getComponentFiles(db, component, componentId); const files: CoreFilepoolFileEntry[] = []; @@ -1405,7 +1405,7 @@ export class CoreFilepoolProvider { await Promise.all(files.map(async (file) => { try { - const fileSize = await CoreFile.instance.getFileSize(file.path); + const fileSize = await CoreFile.getFileSize(file.path); size += fileSize; } catch (error) { @@ -1453,7 +1453,7 @@ export class CoreFilepoolProvider { return CoreConstants.DOWNLOADING; } catch (e) { // Check if the file is being downloaded right now. - const extension = CoreMimetypeUtils.instance.guessExtensionFromUrl(fileUrl); + const extension = CoreMimetypeUtils.guessExtensionFromUrl(fileUrl); filePath = filePath || (await this.getFilePath(siteId, fileId, extension)); const downloadId = this.getFileDownloadId(fileUrl, filePath); @@ -1512,7 +1512,7 @@ export class CoreFilepoolProvider { ): Promise { const addToQueue = (fileUrl: string): void => { // Add the file to queue if needed and ignore errors. - CoreUtils.instance.ignoreErrors(this.addToQueueIfNeeded( + CoreUtils.ignoreErrors(this.addToQueueIfNeeded( siteId, fileUrl, component, @@ -1539,7 +1539,7 @@ export class CoreFilepoolProvider { throw new CoreError('File not downloaded.'); } - if (this.isFileOutdated(entry, revision, timemodified) && CoreApp.instance.isOnline()) { + if (this.isFileOutdated(entry, revision, timemodified) && CoreApp.isOnline()) { throw new CoreError('File is outdated'); } } catch (error) { @@ -1577,14 +1577,14 @@ export class CoreFilepoolProvider { * @return Resolved with the internal URL. Rejected otherwise. */ protected async getInternalSrcById(siteId: string, fileId: string): Promise { - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw new CoreError('File system cannot be used.'); } const path = await this.getFilePath(siteId, fileId); - const fileEntry = await CoreFile.instance.getFile(path); + const fileEntry = await CoreFile.getFile(path); - return CoreFile.instance.convertFileSrc(fileEntry.toURL()); + return CoreFile.convertFileSrc(fileEntry.toURL()); } /** @@ -1595,12 +1595,12 @@ export class CoreFilepoolProvider { * @return Resolved with the URL. Rejected otherwise. */ protected async getInternalUrlById(siteId: string, fileId: string): Promise { - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw new CoreError('File system cannot be used.'); } const path = await this.getFilePath(siteId, fileId); - const fileEntry = await CoreFile.instance.getFile(path); + const fileEntry = await CoreFile.getFile(path); // This URL is usually used to launch files or put them in HTML. return fileEntry.toURL(); @@ -1613,11 +1613,11 @@ export class CoreFilepoolProvider { * @return Resolved with the URL. */ protected async getInternalUrlByPath(filePath: string): Promise { - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw new CoreError('File system cannot be used.'); } - const fileEntry = await CoreFile.instance.getFile(filePath); + const fileEntry = await CoreFile.getFile(filePath); return fileEntry.toURL(); } @@ -1630,7 +1630,7 @@ export class CoreFilepoolProvider { * @return Resolved with the URL. Rejected otherwise. */ async getInternalUrlByUrl(siteId: string, fileUrl: string): Promise { - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw new CoreError('File system cannot be used.'); } @@ -1651,7 +1651,7 @@ export class CoreFilepoolProvider { async getPackageData(siteId: string, component: string, componentId?: string | number): Promise { componentId = this.fixComponentId(componentId); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const packageId = this.getPackageId(component, componentId); return site.getDb().getRecord(PACKAGES_TABLE_NAME, { id: packageId }); @@ -1675,7 +1675,7 @@ export class CoreFilepoolProvider { }); // Guess the extension of the URL. This is for backwards compatibility. - const candidate = CoreMimetypeUtils.instance.guessExtensionFromUrl(url); + const candidate = CoreMimetypeUtils.guessExtensionFromUrl(url); if (candidate && candidate !== 'php') { extension = '.' + candidate; } @@ -1707,14 +1707,14 @@ export class CoreFilepoolProvider { * @return Resolved with the URL. */ async getPackageDirUrlByUrl(siteId: string, url: string): Promise { - if (!CoreFile.instance.isAvailable()) { + if (!CoreFile.isAvailable()) { throw new CoreError('File system cannot be used.'); } const file = await this.fixPluginfileURL(siteId, url); const dirName = this.getPackageDirNameByUrl(file.fileurl); const dirPath = await this.getFilePath(siteId, dirName, ''); - const dirEntry = await CoreFile.instance.getDir(dirPath); + const dirEntry = await CoreFile.getDir(dirPath); return dirEntry.toURL(); } @@ -1800,7 +1800,7 @@ export class CoreFilepoolProvider { * @return The args found, undefined if not a pluginfile. */ protected getPluginFileArgs(url: string): string[] | undefined { - if (!CoreUrlUtils.instance.isPluginFileUrl(url)) { + if (!CoreUrlUtils.isPluginFileUrl(url)) { // Not pluginfile, return. return; } @@ -1841,7 +1841,7 @@ export class CoreFilepoolProvider { if (!create) { return; } - this.queueDeferreds[siteId][fileId] = CoreUtils.instance.promiseDefer(); + this.queueDeferreds[siteId][fileId] = CoreUtils.promiseDefer(); } if (onProgress) { @@ -1918,7 +1918,7 @@ export class CoreFilepoolProvider { return 0; } - const revisionRegex = CorePluginFileDelegate.instance.getComponentRevisionRegExp(args); + const revisionRegex = CorePluginFileDelegate.getComponentRevisionRegExp(args); if (!revisionRegex) { return 0; } @@ -2048,27 +2048,27 @@ export class CoreFilepoolProvider { if (fileUrl.indexOf('/webservice/pluginfile') !== -1) { // It's a pluginfile URL. Search for the 'file' param to extract the name. - const params = CoreUrlUtils.instance.extractUrlParams(fileUrl); + const params = CoreUrlUtils.extractUrlParams(fileUrl); if (params.file) { filename = params.file.substr(params.file.lastIndexOf('/') + 1); } else { // 'file' param not found. Extract what's after the last '/' without params. - filename = CoreUrlUtils.instance.getLastFileWithoutParams(fileUrl); + filename = CoreUrlUtils.getLastFileWithoutParams(fileUrl); } - } else if (CoreUrlUtils.instance.isGravatarUrl(fileUrl)) { + } else if (CoreUrlUtils.isGravatarUrl(fileUrl)) { // Extract gravatar ID. - filename = 'gravatar_' + CoreUrlUtils.instance.getLastFileWithoutParams(fileUrl); - } else if (CoreUrlUtils.instance.isThemeImageUrl(fileUrl)) { + filename = 'gravatar_' + CoreUrlUtils.getLastFileWithoutParams(fileUrl); + } else if (CoreUrlUtils.isThemeImageUrl(fileUrl)) { // Extract user ID. const matches = fileUrl.match(/\/core\/([^/]*)\//); if (matches && matches[1]) { filename = matches[1]; } // Attach a constant and the image type. - filename = 'default_' + filename + '_' + CoreUrlUtils.instance.getLastFileWithoutParams(fileUrl); + filename = 'default_' + filename + '_' + CoreUrlUtils.getLastFileWithoutParams(fileUrl); } else { // Another URL. Just get what's after the last /. - filename = CoreUrlUtils.instance.getLastFileWithoutParams(fileUrl); + filename = CoreUrlUtils.getLastFileWithoutParams(fileUrl); } // If there are hashes in the URL, extract them. @@ -2085,14 +2085,14 @@ export class CoreFilepoolProvider { } // Remove the extension from the filename. - filename = CoreMimetypeUtils.instance.removeExtension(filename); + filename = CoreMimetypeUtils.removeExtension(filename); if (hashes) { // Add hashes to the name. filename += '_' + hashes.join('_'); } - return CoreTextUtils.instance.removeSpecialCharactersForFiles(filename); + return CoreTextUtils.removeSpecialCharactersForFiles(filename); } /** @@ -2103,7 +2103,7 @@ export class CoreFilepoolProvider { * @return Resolved with file object from DB on success, rejected otherwise. */ protected async hasFileInPool(siteId: string, fileId: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const entry = await db.getRecord(FILES_TABLE_NAME, { fileId }); if (typeof entry === 'undefined') { @@ -2128,7 +2128,7 @@ export class CoreFilepoolProvider { throw new CoreError('File not found in queue.'); } // Convert the links to an object. - entry.linksUnserialized = CoreTextUtils.instance.parseJSON(entry.links || '[]', []); + entry.linksUnserialized = CoreTextUtils.parseJSON(entry.links || '[]', []); return entry; } @@ -2142,7 +2142,7 @@ export class CoreFilepoolProvider { * @return Resolved on success. */ async invalidateAllFiles(siteId: string, onlyUnknown: boolean = true): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const where = onlyUnknown ? CoreFilepoolProvider.FILE_UPDATE_UNKNOWN_WHERE_CLAUSE : undefined; @@ -2165,7 +2165,7 @@ export class CoreFilepoolProvider { const file = await this.fixPluginfileURL(siteId, fileUrl); const fileId = this.getFileIdByUrl(file.fileurl); - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); await db.updateRecords(FILES_TABLE_NAME, { stale: 1 }, { fileId }); } @@ -2186,7 +2186,7 @@ export class CoreFilepoolProvider { componentId?: string | number, onlyUnknown: boolean = true, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const items = await this.getComponentFiles(db, component, componentId); @@ -2425,7 +2425,7 @@ export class CoreFilepoolProvider { if (this.queueState !== CoreFilepoolProvider.QUEUE_RUNNING) { // Silently ignore, the queue is on pause. throw CoreFilepoolProvider.ERR_QUEUE_ON_PAUSE; - } else if (!CoreFile.instance.isAvailable() || !CoreApp.instance.isOnline()) { + } else if (!CoreFile.isAvailable() || !CoreApp.isOnline()) { throw CoreFilepoolProvider.ERR_FS_OR_NETWORK_UNAVAILABLE; } @@ -2476,7 +2476,7 @@ export class CoreFilepoolProvider { throw CoreFilepoolProvider.ERR_QUEUE_IS_EMPTY; } // Convert the links to an object. - item.linksUnserialized = CoreTextUtils.instance.parseJSON(item.links, []); + item.linksUnserialized = CoreTextUtils.parseJSON(item.links, []); return this.processQueueItem(item); } @@ -2534,14 +2534,14 @@ export class CoreFilepoolProvider { await this.downloadForPoolByUrl(siteId, fileUrl, options, filePath, onProgress, entry); // Success, we add links and remove from queue. - CoreUtils.instance.ignoreErrors(this.addFileLinks(siteId, fileId, links)); + CoreUtils.ignoreErrors(this.addFileLinks(siteId, fileId, links)); this.treatQueueDeferred(siteId, fileId, true); this.notifyFileDownloaded(siteId, fileId, links); // Wait for the item to be removed from queue before resolving the promise. // If the item could not be removed from queue we still resolve the promise. - await CoreUtils.instance.ignoreErrors(this.removeFromQueue(siteId, fileId)); + await CoreUtils.ignoreErrors(this.removeFromQueue(siteId, fileId)); } catch (errorObject) { // Whoops, we have an error... let dropFromQueue = false; @@ -2581,7 +2581,7 @@ export class CoreFilepoolProvider { if (dropFromQueue) { this.logger.debug('Item dropped from queue due to error: ' + fileUrl, errorObject); - await CoreUtils.instance.ignoreErrors(this.removeFromQueue(siteId, fileId)); + await CoreUtils.ignoreErrors(this.removeFromQueue(siteId, fileId)); this.treatQueueDeferred(siteId, fileId, false, errorMessage); this.notifyFileDownloadError(siteId, fileId, links); @@ -2616,7 +2616,7 @@ export class CoreFilepoolProvider { * @return Resolved on success. */ protected async removeFileById(siteId: string, fileId: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); // Get the path to the file first since it relies on the file object stored in the pool. // Don't use getFilePath to prevent performing 2 DB requests. let path = this.getFilepoolFolderPath(siteId) + '/' + fileId; @@ -2648,8 +2648,8 @@ export class CoreFilepoolProvider { promises.push(db.deleteRecords(LINKS_TABLE_NAME, conditions)); // Remove the file. - if (CoreFile.instance.isAvailable()) { - promises.push(CoreFile.instance.removeFile(path).catch((error) => { + if (CoreFile.isAvailable()) { + promises.push(CoreFile.removeFile(path).catch((error) => { if (error && error.code == 1) { // Not found, ignore error since maybe it was deleted already. } else { @@ -2663,7 +2663,7 @@ export class CoreFilepoolProvider { this.notifyFileDeleted(siteId, fileId, links); if (fileUrl) { - await CoreUtils.instance.ignoreErrors(CorePluginFileDelegate.instance.fileDeleted(fileUrl, path, siteId)); + await CoreUtils.ignoreErrors(CorePluginFileDelegate.fileDeleted(fileUrl, path, siteId)); } } @@ -2676,7 +2676,7 @@ export class CoreFilepoolProvider { * @return Resolved on success. */ async removeFilesByComponent(siteId: string, component: string, componentId?: string | number): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); const items = await this.getComponentFiles(db, component, componentId); await Promise.all(items.map((item) => this.removeFileById(siteId, item.fileId))); @@ -2711,7 +2711,7 @@ export class CoreFilepoolProvider { return url; } - return CorePluginFileDelegate.instance.removeRevisionFromUrl(url, args); + return CorePluginFileDelegate.removeRevisionFromUrl(url, args); } /** @@ -2726,7 +2726,7 @@ export class CoreFilepoolProvider { componentId = this.fixComponentId(componentId); this.logger.debug(`Set previous status for package ${component} ${componentId}`); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const packageId = this.getPackageId(component, componentId); // Get current stored data, we'll only update 'status' and 'updated' fields. @@ -2755,7 +2755,7 @@ export class CoreFilepoolProvider { */ shouldDownload(size: number): boolean { return size <= CoreFilepoolProvider.DOWNLOAD_THRESHOLD || - (CoreApp.instance.isWifi() && size <= CoreFilepoolProvider.WIFI_DOWNLOAD_THRESHOLD); + (CoreApp.isWifi() && size <= CoreFilepoolProvider.WIFI_DOWNLOAD_THRESHOLD); } /** @@ -2772,7 +2772,7 @@ export class CoreFilepoolProvider { return; } - const mimetype = await CoreUtils.instance.getMimeTypeFromUrl(url); + const mimetype = await CoreUtils.getMimeTypeFromUrl(url); // If the file is streaming (audio or video) we reject. if (mimetype.indexOf('video') != -1 || mimetype.indexOf('audio') != -1) { throw new CoreError('File is audio or video.'); @@ -2799,7 +2799,7 @@ export class CoreFilepoolProvider { return true; } - const mimetype = await CoreUtils.instance.getMimeTypeFromUrl(url); + const mimetype = await CoreUtils.getMimeTypeFromUrl(url); // If the file is streaming (audio or video), return false. return mimetype.indexOf('video') == -1 && mimetype.indexOf('audio') == -1; @@ -2825,14 +2825,14 @@ export class CoreFilepoolProvider { this.logger.debug(`Set status '${status}' for package ${component} ${componentId}`); componentId = this.fixComponentId(componentId); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const packageId = this.getPackageId(component, componentId); let downloadTime: number | undefined; let previousDownloadTime: number | undefined; if (status == CoreConstants.DOWNLOADING) { // Set download time if package is now downloading. - downloadTime = CoreTimeUtils.instance.timestamp(); + downloadTime = CoreTimeUtils.timestamp(); } let previousStatus: string | undefined; @@ -2898,7 +2898,7 @@ export class CoreFilepoolProvider { componentId?: string | number, revision?: number, ): Promise { - const urls = CoreDomUtils.instance.extractUrlsFromCSS(cssCode); + const urls = CoreDomUtils.extractUrlsFromCSS(cssCode); let updated = false; // Get the path of the CSS file. @@ -2907,7 +2907,7 @@ export class CoreFilepoolProvider { // Download all files in the CSS. await Promise.all(urls.map(async (url) => { // Download the file only if it's an online URL. - if (CoreUrlUtils.instance.isLocalFileUrl(url)) { + if (CoreUrlUtils.isLocalFileUrl(url)) { return; } @@ -2926,7 +2926,7 @@ export class CoreFilepoolProvider { ); if (fileUrl != url) { - cssCode = cssCode.replace(new RegExp(CoreTextUtils.instance.escapeForRegex(url), 'g'), fileUrl); + cssCode = cssCode.replace(new RegExp(CoreTextUtils.escapeForRegex(url), 'g'), fileUrl); updated = true; } } catch (error) { @@ -2936,7 +2936,7 @@ export class CoreFilepoolProvider { // All files downloaded. Store the result if it has changed. if (updated) { - await CoreFile.instance.writeFile(filePath, cssCode); + await CoreFile.writeFile(filePath, cssCode); } return cssCode; @@ -2992,19 +2992,19 @@ export class CoreFilepoolProvider { async updatePackageDownloadTime(siteId: string, component: string, componentId?: string | number): Promise { componentId = this.fixComponentId(componentId); - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const packageId = this.getPackageId(component, componentId); await site.getDb().updateRecords( PACKAGES_TABLE_NAME, - { downloadTime: CoreTimeUtils.instance.timestamp() }, + { downloadTime: CoreTimeUtils.timestamp() }, { id: packageId }, ); } } -export class CoreFilepool extends makeSingleton(CoreFilepoolProvider) {} +export const CoreFilepool = makeSingleton(CoreFilepoolProvider); /** * File actions. diff --git a/src/core/services/geolocation.ts b/src/core/services/geolocation.ts index c64378c2c..84e60f0ce 100644 --- a/src/core/services/geolocation.ts +++ b/src/core/services/geolocation.ts @@ -32,7 +32,7 @@ export class CoreGeolocationProvider { await this.authorizeLocation(); await this.enableLocation(); - const result = await Geolocation.instance.getCurrentPosition({ + const result = await Geolocation.getCurrentPosition({ enableHighAccuracy: true, timeout: 30000, }); @@ -62,18 +62,18 @@ export class CoreGeolocationProvider { * @throws {CoreGeolocationError} */ async enableLocation(): Promise { - let locationEnabled = await Diagnostic.instance.isLocationEnabled(); + let locationEnabled = await Diagnostic.isLocationEnabled(); if (locationEnabled) { // Location is enabled. return; } - if (!CoreApp.instance.isIOS()) { - Diagnostic.instance.switchToLocationSettings(); - await CoreApp.instance.waitForResume(30000); + if (!CoreApp.isIOS()) { + Diagnostic.switchToLocationSettings(); + await CoreApp.waitForResume(30000); - locationEnabled = await Diagnostic.instance.isLocationEnabled(); + locationEnabled = await Diagnostic.isLocationEnabled(); } if (!locationEnabled) { @@ -88,22 +88,22 @@ export class CoreGeolocationProvider { * @throws {CoreGeolocationError} */ protected async doAuthorizeLocation(failOnDeniedOnce: boolean = false): Promise { - const authorizationStatus = await Diagnostic.instance.getLocationAuthorizationStatus(); + const authorizationStatus = await Diagnostic.getLocationAuthorizationStatus(); switch (authorizationStatus) { - case Diagnostic.instance.permissionStatus.DENIED_ONCE: + case Diagnostic.permissionStatus.DENIED_ONCE: if (failOnDeniedOnce) { throw new CoreGeolocationError(CoreGeolocationErrorReason.PermissionDenied); } // Fall through. - case Diagnostic.instance.permissionStatus.NOT_REQUESTED: - await Diagnostic.instance.requestLocationAuthorization(); - await CoreApp.instance.waitForResume(500); + case Diagnostic.permissionStatus.NOT_REQUESTED: + await Diagnostic.requestLocationAuthorization(); + await CoreApp.waitForResume(500); await this.doAuthorizeLocation(true); return; - case Diagnostic.instance.permissionStatus.GRANTED: - case Diagnostic.instance.permissionStatus.GRANTED_WHEN_IN_USE: + case Diagnostic.permissionStatus.GRANTED: + case Diagnostic.permissionStatus.GRANTED_WHEN_IN_USE: // Location is authorized. return; default: @@ -123,7 +123,7 @@ export class CoreGeolocationProvider { } -export class CoreGeolocation extends makeSingleton(CoreGeolocationProvider) {} +export const CoreGeolocation = makeSingleton(CoreGeolocationProvider); export enum CoreGeolocationErrorReason { PermissionDenied = 'permission-denied', diff --git a/src/core/services/groups.ts b/src/core/services/groups.ts index 46465f044..e5b19bd01 100644 --- a/src/core/services/groups.ts +++ b/src/core/services/groups.ts @@ -66,7 +66,7 @@ export class CoreGroupsProvider { siteId?: string, ignoreCache?: boolean, ): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); @@ -116,7 +116,7 @@ export class CoreGroupsProvider { */ async getActivityAllowedGroupsIfEnabled(cmId: number, userId?: number, siteId?: string, ignoreCache?: boolean): Promise { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); // Get real groupmode, in case it's forced by the course. const hasGroups = await this.activityHasGroups(cmId, siteId, ignoreCache); @@ -173,7 +173,7 @@ export class CoreGroupsProvider { } else { // The "canaccessallgroups" field was added in 3.4. Add all participants for visible groups in previous versions. if (result.canaccessallgroups || (typeof result.canaccessallgroups == 'undefined' && groupInfo.visibleGroups)) { - groupInfo.groups!.push({ id: 0, name: Translate.instance.instant('core.allparticipants') }); + groupInfo.groups!.push({ id: 0, name: Translate.instant('core.allparticipants') }); groupInfo.defaultGroupId = 0; } else { groupInfo.defaultGroupId = result.groups[0].id; @@ -194,7 +194,7 @@ export class CoreGroupsProvider { * @return Promise resolved when the group mode is retrieved. */ async getActivityGroupMode(cmId: number, siteId?: string, ignoreCache?: boolean): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); const params: CoreGroupGetActivityGroupmodeWSParams = { cmid: cmId, }; @@ -235,7 +235,7 @@ export class CoreGroupsProvider { * @return Promise resolved when the groups are retrieved. */ async getAllUserGroups(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); siteId = siteId || site.getId(); if (site.isVersionGreaterEqualThan('3.6')) { @@ -272,7 +272,7 @@ export class CoreGroupsProvider { * @return Promise resolved when the groups are retrieved. */ async getUserGroupsInCourse(courseId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const data: CoreGroupGetCourseUserGroupsWSParams = { userid: userId, @@ -322,7 +322,7 @@ export class CoreGroupsProvider { * @return Promise resolved when the data is invalidated. */ async invalidateActivityAllowedGroups(cmId: number, userId?: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.invalidateWsCacheForKey(this.getActivityAllowedGroupsCacheKey(cmId, userId)); @@ -336,7 +336,7 @@ export class CoreGroupsProvider { * @return Promise resolved when the data is invalidated. */ async invalidateActivityGroupMode(cmId: number, siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getActivityGroupModeCacheKey(cmId)); } @@ -364,7 +364,7 @@ export class CoreGroupsProvider { * @return Promise resolved when the data is invalidated. */ async invalidateAllUserGroups(siteId?: string): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); if (site.isVersionGreaterEqualThan('3.6')) { return this.invalidateUserGroupsInCourse(0, siteId); @@ -382,7 +382,7 @@ export class CoreGroupsProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserGroups(courses: CoreCourseBase[] | number[], siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const promises = this.getCourseIds(courses).map((courseId) => this.invalidateUserGroupsInCourse(courseId, site.id, userId)); @@ -399,7 +399,7 @@ export class CoreGroupsProvider { * @return Promise resolved when the data is invalidated. */ async invalidateUserGroupsInCourse(courseId: number, siteId?: string, userId?: number): Promise { - const site = await CoreSites.instance.getSite(siteId); + const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.invalidateWsCacheForKey(this.getUserGroupsInCourseCacheKey(courseId, userId)); @@ -431,7 +431,7 @@ export class CoreGroupsProvider { } -export class CoreGroups extends makeSingleton(CoreGroupsProvider) {} +export const CoreGroups = makeSingleton(CoreGroupsProvider); /** * Specific group info. diff --git a/src/core/services/handlers/site-info-cron.ts b/src/core/services/handlers/site-info-cron.ts index 1cb3063e3..6a066f30c 100644 --- a/src/core/services/handlers/site-info-cron.ts +++ b/src/core/services/handlers/site-info-cron.ts @@ -33,11 +33,11 @@ export class CoreSiteInfoCronHandler implements CoreCronHandler { */ async execute(siteId?: string): Promise { if (!siteId) { - const siteIds = await CoreSites.instance.getSitesIds(); + const siteIds = await CoreSites.getSitesIds(); - await Promise.all(siteIds.map((siteId) => CoreSites.instance.updateSiteInfo(siteId))); + await Promise.all(siteIds.map((siteId) => CoreSites.updateSiteInfo(siteId))); } else { - await CoreSites.instance.updateSiteInfo(siteId); + await CoreSites.updateSiteInfo(siteId); } } diff --git a/src/core/services/lang.ts b/src/core/services/lang.ts index 569ace06d..81fdcd15a 100644 --- a/src/core/services/lang.ts +++ b/src/core/services/lang.ts @@ -39,15 +39,15 @@ export class CoreLangProvider { constructor() { // Set fallback language and language to use until the app determines the right language to use. - Translate.instance.setDefaultLang(this.fallbackLanguage); - Translate.instance.use(this.defaultLanguage); + Translate.setDefaultLang(this.fallbackLanguage); + Translate.use(this.defaultLanguage); this.initLanguage(); - Translate.instance.onLangChange.subscribe((event: LangChangeEvent) => { + Translate.onLangChange.subscribe((event: LangChangeEvent) => { document.documentElement.setAttribute('lang', event.lang); - let dir = Translate.instance.instant('core.thisdirection'); + let dir = Translate.instant('core.thisdirection'); dir = dir.indexOf('rtl') != -1 ? 'rtl' : 'ltr'; document.documentElement.setAttribute('dir', dir); }); @@ -57,7 +57,7 @@ export class CoreLangProvider { * Init language. */ protected async initLanguage(): Promise { - await Platform.instance.ready(); + await Platform.ready(); let language: string; @@ -129,13 +129,13 @@ export class CoreLangProvider { // Change the language, resolving the promise when we receive the first value. promises.push(new Promise((resolve, reject) => { - CoreSubscriptions.once(Translate.instance.use(language), data => { + CoreSubscriptions.once(Translate.use(language), data => { // It's a language override, load the original one first. - const fallbackLang = Translate.instance.instant('core.parentlanguage'); + const fallbackLang = Translate.instant('core.parentlanguage'); if (fallbackLang != '' && fallbackLang != 'core.parentlanguage' && fallbackLang != language) { CoreSubscriptions.once( - Translate.instance.use(fallbackLang), + Translate.use(fallbackLang), fallbackData => { data = Object.assign(fallbackData, data); @@ -151,7 +151,7 @@ export class CoreLangProvider { })); // Change the config. - promises.push(CoreConfig.instance.set('current_language', language)); + promises.push(CoreConfig.set('current_language', language)); // Use british english when parent english is loaded. moment.locale(language == 'en' ? 'en-gb' : language); @@ -166,7 +166,7 @@ export class CoreLangProvider { // Load the custom and site plugins strings for the language. if (this.loadLangStrings(this.customStrings, language) || this.loadLangStrings(this.sitePluginsStrings, language)) { // Some lang strings have changed, emit an event to update the pipes. - Translate.instance.onLangChange.emit({ lang: language, translations: Translate.instance.translations[language] }); + Translate.onLangChange.emit({ lang: language, translations: Translate.translations[language] }); } } } @@ -229,7 +229,7 @@ export class CoreLangProvider { protected async detectLanguage(): Promise { // Get current language from config (user might have changed it). try { - return await CoreConfig.instance.get('current_language'); + return await CoreConfig.get('current_language'); } catch (e) { // Try will return, ignore errors here to avoid nesting. } @@ -284,7 +284,7 @@ export class CoreLangProvider { getTranslationTable(lang: string): Promise> { // Create a promise to convert the observable into a promise. return new Promise((resolve, reject): void => { - const observer = Translate.instance.getTranslation(lang).subscribe((table) => { + const observer = Translate.getTranslation(lang).subscribe((table) => { resolve(table); observer.unsubscribe(); }, (err) => { @@ -358,9 +358,9 @@ export class CoreLangProvider { if (currentLangChanged) { // Some lang strings have changed, emit an event to update the pipes. - Translate.instance.onLangChange.emit({ + Translate.onLangChange.emit({ lang: this.currentLanguage!, - translations: Translate.instance.translations[this.currentLanguage!], + translations: Translate.translations[this.currentLanguage!], }); } } @@ -381,10 +381,10 @@ export class CoreLangProvider { if (!entry.applied) { // Store the original value of the string. - entry.original = Translate.instance.translations[lang][key]; + entry.original = Translate.translations[lang][key]; // Store the string in the translations table. - Translate.instance.translations[lang][key] = entry.value; + Translate.translations[lang][key] = entry.value; entry.applied = true; langApplied = true; @@ -406,17 +406,17 @@ export class CoreLangProvider { loadString(langObject: CoreLanguageObject, lang: string, key: string, value: string): void { lang = lang.replace(/_/g, '-'); // Use the app format instead of Moodle format. - if (Translate.instance.translations[lang]) { + if (Translate.translations[lang]) { // The language is loaded. // Store the original value of the string. langObject[lang][key] = { - original: Translate.instance.translations[lang][key], + original: Translate.translations[lang][key], value, applied: true, }; // Store the string in the translations table. - Translate.instance.translations[lang][key] = value; + Translate.translations[lang][key] = value; } else { // The language isn't loaded. // Save it in our object but not in the translations table, it will be loaded when the lang is loaded. @@ -435,7 +435,7 @@ export class CoreLangProvider { protected unloadStrings(strings: CoreLanguageObject): void { // Iterate over all languages and strings. for (const lang in strings) { - if (!Translate.instance.translations[lang]) { + if (!Translate.translations[lang]) { // Language isn't loaded, nothing to unload. continue; } @@ -445,10 +445,10 @@ export class CoreLangProvider { const entry = langStrings[key]; if (entry.original) { // The string had a value, restore it. - Translate.instance.translations[lang][key] = entry.original; + Translate.translations[lang][key] = entry.original; } else { // The string didn't exist, delete it. - delete Translate.instance.translations[lang][key]; + delete Translate.translations[lang][key]; } } } @@ -456,7 +456,7 @@ export class CoreLangProvider { } -export class CoreLang extends makeSingleton(CoreLangProvider) {} +export const CoreLang = makeSingleton(CoreLangProvider); /** * Language object has two leves, first per language and second per string key. diff --git a/src/core/services/local-notifications.ts b/src/core/services/local-notifications.ts index 23caf809b..2e18fc047 100644 --- a/src/core/services/local-notifications.ts +++ b/src/core/services/local-notifications.ts @@ -72,55 +72,55 @@ export class CoreLocalNotificationsProvider { */ async initializeDatabase(): Promise { try { - await CoreApp.instance.createTablesFromSchema(APP_SCHEMA); + await CoreApp.createTablesFromSchema(APP_SCHEMA); } catch (e) { // Ignore errors. } - this.resolveAppDB(CoreApp.instance.getDB()); + this.resolveAppDB(CoreApp.getDB()); } /** * Init some properties. */ protected async init(): Promise { - await Platform.instance.ready(); + await Platform.ready(); if (!this.isAvailable()) { return; } // Listen to events. - this.triggerSubscription = LocalNotifications.instance.on('trigger').subscribe((notification: ILocalNotification) => { + this.triggerSubscription = LocalNotifications.on('trigger').subscribe((notification: ILocalNotification) => { this.trigger(notification); this.handleEvent('trigger', notification); }); - this.clickSubscription = LocalNotifications.instance.on('click').subscribe((notification: ILocalNotification) => { + this.clickSubscription = LocalNotifications.on('click').subscribe((notification: ILocalNotification) => { this.handleEvent('click', notification); }); - this.clearSubscription = LocalNotifications.instance.on('clear').subscribe((notification: ILocalNotification) => { + this.clearSubscription = LocalNotifications.on('clear').subscribe((notification: ILocalNotification) => { this.handleEvent('clear', notification); }); - this.cancelSubscription = LocalNotifications.instance.on('cancel').subscribe((notification: ILocalNotification) => { + this.cancelSubscription = LocalNotifications.on('cancel').subscribe((notification: ILocalNotification) => { this.handleEvent('cancel', notification); }); - this.addSubscription = LocalNotifications.instance.on('schedule').subscribe((notification: ILocalNotification) => { + this.addSubscription = LocalNotifications.on('schedule').subscribe((notification: ILocalNotification) => { this.handleEvent('schedule', notification); }); - this.updateSubscription = LocalNotifications.instance.on('update').subscribe((notification: ILocalNotification) => { + this.updateSubscription = LocalNotifications.on('update').subscribe((notification: ILocalNotification) => { this.handleEvent('update', notification); }); // Create the default channel for local notifications. this.createDefaultChannel(); - Translate.instance.onLangChange.subscribe(() => { + Translate.onLangChange.subscribe(() => { // Update the channel name. this.createDefaultChannel(); }); @@ -145,7 +145,7 @@ export class CoreLocalNotificationsProvider { const queueId = 'cancel-' + uniqueId; - await this.queueRunner.run(queueId, () => LocalNotifications.instance.cancel(uniqueId), { + await this.queueRunner.run(queueId, () => LocalNotifications.cancel(uniqueId), { allowRepeated: true, }); } @@ -176,7 +176,7 @@ export class CoreLocalNotificationsProvider { } }); - await this.queueRunner.run(queueId, () => LocalNotifications.instance.cancel(ids), { + await this.queueRunner.run(queueId, () => LocalNotifications.cancel(ids), { allowRepeated: true, }); } @@ -188,7 +188,7 @@ export class CoreLocalNotificationsProvider { */ canDisableSound(): boolean { // Only allow disabling sound in Android 7 or lower. In iOS and Android 8+ it can easily be done with system settings. - return this.isAvailable() && CoreApp.instance.isAndroid() && CoreApp.instance.getPlatformMajorVersion() < 8; + return this.isAvailable() && CoreApp.isAndroid() && CoreApp.getPlatformMajorVersion() < 8; } /** @@ -197,13 +197,13 @@ export class CoreLocalNotificationsProvider { * @return Promise resolved when done. */ protected async createDefaultChannel(): Promise { - if (!CoreApp.instance.isAndroid()) { + if (!CoreApp.isAndroid()) { return; } - await Push.instance.createChannel({ + await Push.createChannel({ id: 'default-channel-id', - description: Translate.instance.instant('addon.calendar.calendarreminders'), + description: Translate.instant('addon.calendar.calendarreminders'), importance: 4, }).catch((error) => { this.logger.error('Error changing channel name', error); @@ -216,7 +216,7 @@ export class CoreLocalNotificationsProvider { * @return Promise resolved with the notifications. */ protected getAllScheduled(): Promise { - return this.queueRunner.run('allScheduled', () => LocalNotifications.instance.getAllScheduled()); + return this.queueRunner.run('allScheduled', () => LocalNotifications.getAllScheduled()); } /** @@ -358,11 +358,11 @@ export class CoreLocalNotificationsProvider { if (useQueue) { const queueId = 'isTriggered-' + notification.id; - return this.queueRunner.run(queueId, () => LocalNotifications.instance.isTriggered(notification.id!), { + return this.queueRunner.run(queueId, () => LocalNotifications.isTriggered(notification.id!), { allowRepeated: true, }); } else { - return LocalNotifications.instance.isTriggered(notification.id || 0); + return LocalNotifications.isTriggered(notification.id || 0); } } } @@ -384,7 +384,7 @@ export class CoreLocalNotificationsProvider { */ notifyEvent(eventName: string, data: Record): void { // Execute the code in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { + NgZone.run(() => { const component = data.component; if (component) { if (this.observables[eventName] && this.observables[eventName][component]) { @@ -404,7 +404,7 @@ export class CoreLocalNotificationsProvider { if (!data) { return {}; } else if (typeof data == 'string') { - return CoreTextUtils.instance.parseJSON(data, {}); + return CoreTextUtils.parseJSON(data, {}); } else { return data; } @@ -510,7 +510,7 @@ export class CoreLocalNotificationsProvider { * @return Promise resolved when the code is retrieved. */ protected requestCode(table: string, id: string): Promise { - const deferred = CoreUtils.instance.promiseDefer(); + const deferred = CoreUtils.promiseDefer(); const key = table + '#' + id; const isQueueEmpty = Object.keys(this.codeRequestsQueue).length == 0; @@ -573,7 +573,7 @@ export class CoreLocalNotificationsProvider { notification.data.component = component; notification.data.siteId = siteId; - if (CoreApp.instance.isAndroid()) { + if (CoreApp.isAndroid()) { notification.icon = notification.icon || 'res://icon'; notification.smallIcon = notification.smallIcon || 'res://smallicon'; notification.color = notification.color || CoreConstants.CONFIG.notificoncolor; @@ -621,7 +621,7 @@ export class CoreLocalNotificationsProvider { const triggered = await this.isTriggered(notification, false); // Cancel the current notification in case it gets scheduled twice. - LocalNotifications.instance.cancel(notification.id).finally(async () => { + LocalNotifications.cancel(notification.id).finally(async () => { if (!triggered) { let soundEnabled: boolean; @@ -629,7 +629,7 @@ export class CoreLocalNotificationsProvider { if (!this.canDisableSound()) { soundEnabled = true; } else { - soundEnabled = await CoreConfig.instance.get(CoreConstants.SETTINGS_NOTIFICATION_SOUND, true); + soundEnabled = await CoreConfig.get(CoreConstants.SETTINGS_NOTIFICATION_SOUND, true); } if (!soundEnabled) { @@ -642,7 +642,7 @@ export class CoreLocalNotificationsProvider { // Remove from triggered, since the notification could be in there with a different time. this.removeTriggered(notification.id || 0); - LocalNotifications.instance.schedule(notification); + LocalNotifications.schedule(notification); } }); } @@ -682,6 +682,6 @@ export class CoreLocalNotificationsProvider { } -export class CoreLocalNotifications extends makeSingleton(CoreLocalNotificationsProvider) {} +export const CoreLocalNotifications = makeSingleton(CoreLocalNotificationsProvider); export type CoreLocalNotificationsClickCallback = (value: T) => void; diff --git a/src/core/services/navigator.ts b/src/core/services/navigator.ts index 67a6291f3..5f830d1d1 100644 --- a/src/core/services/navigator.ts +++ b/src/core/services/navigator.ts @@ -86,7 +86,7 @@ export class CoreNavigatorService { * @return Whether the active route is using the given path. */ isCurrent(path: string): boolean { - return CoreTextUtils.instance.matchesGlob(this.getCurrentPath(), path); + return CoreTextUtils.matchesGlob(this.getCurrentPath(), path); } /** @@ -108,7 +108,7 @@ export class CoreNavigatorService { * @return Whether the active route is using the given path. */ isCurrentPathInTablet(path: string): boolean { - if (CoreScreen.instance.isMobile) { + if (CoreScreen.isMobile) { // Split view is off. return false; } @@ -135,8 +135,8 @@ export class CoreNavigatorService { this.replaceObjectParams(navigationOptions.queryParams); const navigationResult = (options.reset ?? false) - ? await NavController.instance.navigateRoot(url, navigationOptions) - : await NavController.instance.navigateForward(url, navigationOptions); + ? await NavController.navigateRoot(url, navigationOptions) + : await NavController.navigateForward(url, navigationOptions); return navigationResult !== false; } @@ -150,7 +150,7 @@ export class CoreNavigatorService { async navigateToLoginCredentials(params: Params = {}): Promise { // If necessary, open the previous path to keep the navigation history. if (!this.isCurrent('/login/site') && !this.isCurrent('/login/sites')) { - const hasSites = await CoreSites.instance.hasSites(); + const hasSites = await CoreSites.hasSites(); await this.navigate(hasSites ? '/login/sites' : '/login/site', { reset: true }); } @@ -180,7 +180,7 @@ export class CoreNavigatorService { path: string, options: Omit & { siteId?: string } = {}, ): Promise { - const siteId = options.siteId ?? CoreSites.instance.getCurrentSiteId(); + const siteId = options.siteId ?? CoreSites.getCurrentSiteId(); const navigationOptions: CoreNavigationOptions = CoreObject.without(options, ['siteId']); // @todo: When this function was in ContentLinksHelper, this code was inside NgZone. Check if it's needed. @@ -194,18 +194,18 @@ export class CoreNavigatorService { } // If we are logged into a different site, log out first. - if (CoreSites.instance.isLoggedIn() && CoreSites.instance.getCurrentSiteId() !== siteId) { + if (CoreSites.isLoggedIn() && CoreSites.getCurrentSiteId() !== siteId) { // @todo: Check site plugins and store redirect. - await CoreSites.instance.logout(); + await CoreSites.logout(); } // If we are not logged into the site, load the site. - if (!CoreSites.instance.isLoggedIn()) { - const modal = await CoreDomUtils.instance.showModalLoading(); + if (!CoreSites.isLoggedIn()) { + const modal = await CoreDomUtils.showModalLoading(); try { - const loggedIn = await CoreSites.instance.loadSite(siteId, path, options.params); + const loggedIn = await CoreSites.loadSite(siteId, path, options.params); if (!loggedIn) { // User has been redirected to the login page and will be redirected to the site path after login. @@ -229,7 +229,7 @@ export class CoreNavigatorService { * @return Current path. */ getCurrentPath(): string { - return CoreUrlUtils.instance.removeUrlParams(Router.instance.url); + return CoreUrlUtils.removeUrlParams(Router.url); } /** @@ -240,7 +240,7 @@ export class CoreNavigatorService { getPreviousPath(): string { // @todo: Remove this method and the used attributes. // This is a quick workarround to avoid loops. Ie, in messages we can navigate to user profile and there to messages. - return CoreUrlUtils.instance.removeUrlParams(this.previousPath || ''); + return CoreUrlUtils.removeUrlParams(this.previousPath || ''); } /** @@ -293,11 +293,11 @@ export class CoreNavigatorService { // Remove the parameter from our map if it's in there. delete this.storedParams[value]; - if (!CoreApp.instance.isMobile() && !storedParam) { + if (!CoreApp.isMobile() && !storedParam) { // Try to retrieve the param from local storage in browser. const storageParam = localStorage.getItem(value); if (storageParam) { - storedParam = CoreTextUtils.instance.parseJSON(storageParam); + storedParam = CoreTextUtils.parseJSON(storageParam); } } @@ -338,7 +338,7 @@ export class CoreNavigatorService { * @return Promise resolved when done. */ back(): Promise { - return NavController.instance.pop(); + return NavController.pop(); } /** @@ -353,7 +353,7 @@ export class CoreNavigatorService { getCurrentRoute(): ActivatedRoute; getCurrentRoute(options: GetCurrentRouteOptions): ActivatedRoute | null; getCurrentRoute({ parentRoute, pageComponent }: GetCurrentRouteOptions = {}): ActivatedRoute | null { - parentRoute = parentRoute ?? Router.instance.routerState.root; + parentRoute = parentRoute ?? Router.routerState.root; if (pageComponent && parentRoute.component === pageComponent) { return parentRoute; @@ -389,8 +389,8 @@ export class CoreNavigatorService { const pathRoot = /^[^/]+/.exec(path)?.[0] ?? ''; const currentMainMenuTab = this.getCurrentMainMenuTab(); - const isMainMenuTab = await CoreUtils.instance.ignoreErrors( - CoreMainMenu.instance.isMainMenuTab(pathRoot), + const isMainMenuTab = await CoreUtils.ignoreErrors( + CoreMainMenu.isMainMenuTab(pathRoot), false, ); @@ -435,7 +435,7 @@ export class CoreNavigatorService { this.storedParams[id] = value; queryParams[name] = id; - if (!CoreApp.instance.isMobile()) { + if (!CoreApp.isMobile()) { // In browser, save the param in local storage to be able to retrieve it if the app is refreshed. localStorage.setItem(id, JSON.stringify(value)); } @@ -451,4 +451,4 @@ export class CoreNavigatorService { } -export class CoreNavigator extends makeSingleton(CoreNavigatorService) {} +export const CoreNavigator = makeSingleton(CoreNavigatorService); diff --git a/src/core/services/plugin-file-delegate.ts b/src/core/services/plugin-file-delegate.ts index e7417e778..425c67e6e 100644 --- a/src/core/services/plugin-file-delegate.ts +++ b/src/core/services/plugin-file-delegate.ts @@ -135,12 +135,12 @@ export class CorePluginFileDelegateService extends CoreDelegate { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const filteredFiles = []; await Promise.all(files.map(async (file) => { - const state = await CoreFilepool.instance.getFileStateByUrl(siteId!, file.fileurl, file.timemodified); + const state = await CoreFilepool.getFileStateByUrl(siteId!, file.fileurl, file.timemodified); if (state != CoreConstants.DOWNLOADED && state != CoreConstants.NOT_DOWNLOADABLE) { filteredFiles.push(file); @@ -291,7 +291,7 @@ export class CorePluginFileDelegateService extends CoreDelegate { try { - await CoreApp.instance.createTablesFromSchema(APP_SCHEMA); + await CoreApp.createTablesFromSchema(APP_SCHEMA); } catch (e) { // Ignore errors. } - this.resolveAppDB(CoreApp.instance.getDB()); + this.resolveAppDB(CoreApp.getDB()); } /** @@ -132,11 +132,11 @@ export class CoreSitesProvider { */ async checkSite(siteUrl: string, protocol: string = 'https://'): Promise { // The formatURL function adds the protocol if is missing. - siteUrl = CoreUrlUtils.instance.formatURL(siteUrl); + siteUrl = CoreUrlUtils.formatURL(siteUrl); - if (!CoreUrlUtils.instance.isHttpURL(siteUrl)) { - throw new CoreError(Translate.instance.instant('core.login.invalidsite')); - } else if (!CoreApp.instance.isOnline()) { + if (!CoreUrlUtils.isHttpURL(siteUrl)) { + throw new CoreError(Translate.instant('core.login.invalidsite')); + } else if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } @@ -159,12 +159,12 @@ export class CoreSitesProvider { } // Site doesn't exist. Return the error message. - if (CoreTextUtils.instance.getErrorMessageFromError(error)) { + if (CoreTextUtils.getErrorMessageFromError(error)) { throw error; - } else if (CoreTextUtils.instance.getErrorMessageFromError(secondError)) { + } else if (CoreTextUtils.getErrorMessageFromError(secondError)) { throw secondError; } else { - throw new CoreError(Translate.instance.instant('core.cannotconnecttrouble')); + throw new CoreError(Translate.instant('core.cannotconnecttrouble')); } } } @@ -194,7 +194,7 @@ export class CoreSitesProvider { } // Site doesn't exist. Try to add or remove 'www'. - const treatedUrl = CoreUrlUtils.instance.addOrRemoveWWW(siteUrl); + const treatedUrl = CoreUrlUtils.addOrRemoveWWW(siteUrl); try { await this.siteExists(treatedUrl); @@ -210,7 +210,7 @@ export class CoreSitesProvider { } // Return the error. - if (CoreTextUtils.instance.getErrorMessageFromError(error)) { + if (CoreTextUtils.getErrorMessageFromError(error)) { throw error; } else { throw secondError; @@ -245,14 +245,14 @@ export class CoreSitesProvider { // Check that the user can authenticate. if (!config.enablewebservices) { throw new CoreSiteError({ - message: Translate.instance.instant('core.login.webservicesnotenabled'), + message: Translate.instant('core.login.webservicesnotenabled'), }); } else if (!config.enablemobilewebservice) { throw new CoreSiteError({ - message: Translate.instance.instant('core.login.mobileservicesnotenabled'), + message: Translate.instant('core.login.mobileservicesnotenabled'), }); } else if (config.maintenanceenabled) { - let message = Translate.instance.instant('core.sitemaintenance'); + let message = Translate.instant('core.sitemaintenance'); if (config.maintenancemessage) { message += config.maintenancemessage; } @@ -272,13 +272,13 @@ export class CoreSitesProvider { // Service supported but an error happened. Return error. if (error.errorcode == 'codingerror') { // This could be caused by a redirect. Check if it's the case. - const redirect = await CoreUtils.instance.checkRedirect(siteUrl); + const redirect = await CoreUtils.checkRedirect(siteUrl); if (redirect) { - error.error = Translate.instance.instant('core.login.sitehasredirect'); + error.error = Translate.instant('core.login.sitehasredirect'); } else { // We can't be sure if there is a redirect or not. Display cannot connect error. - error.error = Translate.instance.instant('core.cannotconnecttrouble'); + error.error = Translate.instant('core.cannotconnecttrouble'); } } @@ -306,22 +306,22 @@ export class CoreSitesProvider { let data: CoreSitesLoginTokenResponse; // Use a valid path first. - siteUrl = CoreUrlUtils.instance.removeUrlParams(siteUrl); + siteUrl = CoreUrlUtils.removeUrlParams(siteUrl); try { - data = await Http.instance.post(siteUrl + '/login/token.php', {}).pipe(timeout(CoreWS.instance.getRequestTimeout())) + data = await Http.post(siteUrl + '/login/token.php', {}).pipe(timeout(CoreWS.getRequestTimeout())) .toPromise(); } catch (error) { // Default error messages are kinda bad, return our own message. throw new CoreSiteError({ - message: Translate.instance.instant('core.cannotconnecttrouble'), + message: Translate.instant('core.cannotconnecttrouble'), }); } if (data === null) { // Cannot connect. throw new CoreSiteError({ - message: Translate.instance.instant('core.cannotconnect', { $a: CoreSite.MINIMUM_MOODLE_VERSION }), + message: Translate.instant('core.cannotconnect', { $a: CoreSite.MINIMUM_MOODLE_VERSION }), }); } @@ -359,7 +359,7 @@ export class CoreSitesProvider { service?: string, retry?: boolean, ): Promise { - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } @@ -376,13 +376,13 @@ export class CoreSitesProvider { let data: CoreSitesLoginTokenResponse; try { - data = await Http.instance.post(loginUrl, params).pipe(timeout(CoreWS.instance.getRequestTimeout())).toPromise(); + data = await Http.post(loginUrl, params).pipe(timeout(CoreWS.getRequestTimeout())).toPromise(); } catch (error) { - throw new CoreError(Translate.instance.instant('core.cannotconnecttrouble')); + throw new CoreError(Translate.instant('core.cannotconnecttrouble')); } if (typeof data == 'undefined') { - throw new CoreError(Translate.instance.instant('core.cannotconnecttrouble')); + throw new CoreError(Translate.instant('core.cannotconnecttrouble')); } else { if (typeof data.token != 'undefined') { return { token: data.token, siteUrl, privateToken: data.privatetoken }; @@ -390,16 +390,16 @@ export class CoreSitesProvider { if (typeof data.error != 'undefined') { // We only allow one retry (to avoid loops). if (!retry && data.errorcode == 'requirecorrectaccess') { - siteUrl = CoreUrlUtils.instance.addOrRemoveWWW(siteUrl); + siteUrl = CoreUrlUtils.addOrRemoveWWW(siteUrl); return this.getUserToken(siteUrl, username, password, service, true); } else if (data.errorcode == 'missingparam') { // It seems the server didn't receive all required params, it could be due to a redirect. - const redirect = await CoreUtils.instance.checkRedirect(loginUrl); + const redirect = await CoreUtils.checkRedirect(loginUrl); if (redirect) { throw new CoreSiteError({ - message: Translate.instance.instant('core.login.sitehasredirect'), + message: Translate.instant('core.login.sitehasredirect'), }); } } @@ -410,7 +410,7 @@ export class CoreSitesProvider { }); } - throw new CoreError(Translate.instance.instant('core.login.invalidaccount')); + throw new CoreError(Translate.instant('core.login.invalidaccount')); } } } @@ -451,7 +451,7 @@ export class CoreSitesProvider { const siteId = this.createSiteID(info.siteurl, info.username); // Check if the site already exists. - const site = await CoreUtils.instance.ignoreErrors(this.getSite(siteId)); + const site = await CoreUtils.ignoreErrors(this.getSite(siteId)); if (site) { // Site already exists, update its data and use it. @@ -546,7 +546,7 @@ export class CoreSitesProvider { } throw new CoreSiteError({ - message: Translate.instance.instant(errorKey, translateParams), + message: Translate.instant(errorKey, translateParams), errorcode: errorCode, loggedOut: true, }); @@ -733,22 +733,22 @@ export class CoreSitesProvider { siteId = siteId || this.getCurrentSiteId(); - const downloadUrl = CoreApp.instance.getAppStoreUrl(storesConfig); + const downloadUrl = CoreApp.getAppStoreUrl(storesConfig); if (downloadUrl != null) { // Do not block interface. - CoreDomUtils.instance.showConfirm( - Translate.instance.instant('core.updaterequireddesc', { $a: config.tool_mobile_minimumversion }), - Translate.instance.instant('core.updaterequired'), - Translate.instance.instant('core.download'), - Translate.instance.instant(siteId ? 'core.mainmenu.logout' : 'core.cancel'), - ).then(() => CoreUtils.instance.openInBrowser(downloadUrl)).catch(() => { + CoreDomUtils.showConfirm( + Translate.instant('core.updaterequireddesc', { $a: config.tool_mobile_minimumversion }), + Translate.instant('core.updaterequired'), + Translate.instant('core.download'), + Translate.instant(siteId ? 'core.mainmenu.logout' : 'core.cancel'), + ).then(() => CoreUtils.openInBrowser(downloadUrl)).catch(() => { // Do nothing. }); } else { - CoreDomUtils.instance.showAlert( - Translate.instance.instant('core.updaterequired'), - Translate.instance.instant('core.updaterequireddesc', { $a: config.tool_mobile_minimumversion }), + CoreDomUtils.showAlert( + Translate.instant('core.updaterequired'), + Translate.instant('core.updaterequireddesc', { $a: config.tool_mobile_minimumversion }), ); } @@ -997,8 +997,8 @@ export class CoreSitesProvider { */ makeSiteFromSiteListEntry(entry: SiteDBEntry): Promise { // Parse info and config. - const info = entry.info ? CoreTextUtils.instance.parseJSON(entry.info) : undefined; - const config = entry.config ? CoreTextUtils.instance.parseJSON(entry.config) : undefined; + const info = entry.info ? CoreTextUtils.parseJSON(entry.info) : undefined; + const config = entry.config ? CoreTextUtils.parseJSON(entry.config) : undefined; const site = new CoreSite(entry.id, entry.siteUrl, entry.token, info, entry.privateToken, config, entry.loggedOut == 1); site.setOAuthId(entry.oauthId); @@ -1061,7 +1061,7 @@ export class CoreSitesProvider { sites.forEach((site) => { if (!ids || ids.indexOf(site.id) > -1) { // Parse info. - const siteInfo = site.info ? CoreTextUtils.instance.parseJSON(site.info) : undefined; + const siteInfo = site.info ? CoreTextUtils.parseJSON(site.info) : undefined; const basicInfo: CoreSiteBasicInfo = { id: site.id, siteUrl: site.siteUrl, @@ -1360,7 +1360,7 @@ export class CoreSitesProvider { // Check if URL has http(s) protocol. if (!url.match(/^https?:\/\//i)) { // URL doesn't have http(s) protocol. Check if it has any protocol. - if (CoreUrlUtils.instance.isAbsoluteURL(url)) { + if (CoreUrlUtils.isAbsoluteURL(url)) { // It has some protocol. Return empty array. return []; } else { @@ -1602,10 +1602,10 @@ export class CoreSitesProvider { // If more than one site is returned it usually means there are different users stored. Use any of them. const site = await this.getSite(siteIds[0]); - const siteUrl = CoreTextUtils.instance.removeEndingSlash( - CoreUrlUtils.instance.removeProtocolAndWWW(site.getURL()), + const siteUrl = CoreTextUtils.removeEndingSlash( + CoreUrlUtils.removeProtocolAndWWW(site.getURL()), ); - const treatedUrl = CoreTextUtils.instance.removeEndingSlash(CoreUrlUtils.instance.removeProtocolAndWWW(url)); + const treatedUrl = CoreTextUtils.removeEndingSlash(CoreUrlUtils.removeProtocolAndWWW(url)); if (siteUrl == treatedUrl) { result.site = site; @@ -1677,7 +1677,7 @@ export class CoreSitesProvider { } -export class CoreSites extends makeSingleton(CoreSitesProvider) {} +export const CoreSites = makeSingleton(CoreSitesProvider); /** * Response of checking if a site exists and its configuration. diff --git a/src/core/services/sync.ts b/src/core/services/sync.ts index 24a1314e9..c48c3a055 100644 --- a/src/core/services/sync.ts +++ b/src/core/services/sync.ts @@ -43,7 +43,7 @@ export class CoreSyncProvider { * @param siteId Site ID. If not defined, current site. */ blockOperation(component: string, id: string | number, operation?: string, siteId?: string): void { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const uniqueId = this.getUniqueSyncBlockId(component, id); @@ -81,7 +81,7 @@ export class CoreSyncProvider { * @param siteId Site ID. If not defined, current site. */ clearBlocks(component: string, id: string | number, siteId?: string): void { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const uniqueId = this.getUniqueSyncBlockId(component, id); if (this.blockedItems[siteId]) { @@ -98,7 +98,7 @@ export class CoreSyncProvider { * @return Record if found or reject. */ async getSyncRecord(component: string, id: string | number, siteId?: string): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); return await db.getRecord(SYNC_TABLE_NAME, { component: component, id: String(id) }); } @@ -118,7 +118,7 @@ export class CoreSyncProvider { data: Partial, siteId?: string, ): Promise { - const db = await CoreSites.instance.getSiteDb(siteId); + const db = await CoreSites.getSiteDb(siteId); data.component = component; data.id = String(id); @@ -147,7 +147,7 @@ export class CoreSyncProvider { * @return Whether it's blocked. */ isBlocked(component: string, id: string | number, siteId?: string): boolean { - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); if (!this.blockedItems[siteId]) { return false; @@ -171,7 +171,7 @@ export class CoreSyncProvider { */ unblockOperation(component: string, id: string | number, operation?: string, siteId?: string): void { operation = operation || '-'; - siteId = siteId || CoreSites.instance.getCurrentSiteId(); + siteId = siteId || CoreSites.getCurrentSiteId(); const uniqueId = this.getUniqueSyncBlockId(component, id); @@ -182,4 +182,4 @@ export class CoreSyncProvider { } -export class CoreSync extends makeSingleton(CoreSyncProvider) {} +export const CoreSync = makeSingleton(CoreSyncProvider); diff --git a/src/core/services/tests/utils/text.test.ts b/src/core/services/tests/utils/text.test.ts index 5d4ab6da3..6fbc20848 100644 --- a/src/core/services/tests/utils/text.test.ts +++ b/src/core/services/tests/utils/text.test.ts @@ -59,7 +59,7 @@ describe('CoreTextUtilsProvider', () => { expect(url).toEqual('geo:0,0?q=Moodle%20Spain%20HQ'); expect(sanitizer.bypassSecurityTrustUrl).toHaveBeenCalled(); - expect(CoreApp.instance.isAndroid).toHaveBeenCalled(); + expect(CoreApp.isAndroid).toHaveBeenCalled(); }); it('builds address URL for non-Android platforms', () => { @@ -75,7 +75,7 @@ describe('CoreTextUtilsProvider', () => { expect(url).toEqual('http://maps.google.com?q=Moodle%20Spain%20HQ'); expect(sanitizer.bypassSecurityTrustUrl).toHaveBeenCalled(); - expect(CoreApp.instance.isAndroid).toHaveBeenCalled(); + expect(CoreApp.isAndroid).toHaveBeenCalled(); }); it('matches glob patterns', () => { diff --git a/src/core/services/update-manager.ts b/src/core/services/update-manager.ts index 3963db5d4..5d11fd4fc 100644 --- a/src/core/services/update-manager.ts +++ b/src/core/services/update-manager.ts @@ -45,7 +45,7 @@ export class CoreUpdateManagerProvider { const promises = []; const versionCode = CoreConstants.CONFIG.versioncode; - const versionApplied = await CoreConfig.instance.get(VERSION_APPLIED, 0); + const versionApplied = await CoreConfig.get(VERSION_APPLIED, 0); if (versionCode >= 3900 && versionApplied < 3900 && versionApplied > 0) { // @todo: H5P update. @@ -54,7 +54,7 @@ export class CoreUpdateManagerProvider { try { await Promise.all(promises); - await CoreConfig.instance.set(VERSION_APPLIED, versionCode); + await CoreConfig.set(VERSION_APPLIED, versionCode); } catch (error) { this.logger.error(`Error applying update from ${versionApplied} to ${versionCode}`, error); } @@ -62,4 +62,4 @@ export class CoreUpdateManagerProvider { } -export class CoreUpdateManager extends makeSingleton(CoreUpdateManagerProvider) {} +export const CoreUpdateManager = makeSingleton(CoreUpdateManagerProvider); diff --git a/src/core/services/utils/dom.ts b/src/core/services/utils/dom.ts index f26315593..6212a6678 100644 --- a/src/core/services/utils/dom.ts +++ b/src/core/services/utils/dom.ts @@ -70,7 +70,7 @@ export class CoreDomUtilsProvider { */ protected async init(): Promise { // Check if debug messages should be displayed. - const debugDisplay = await CoreConfig.instance.get(CoreConstants.SETTINGS_DEBUG_DISPLAY, 0); + const debugDisplay = await CoreConfig.get(CoreConstants.SETTINGS_DEBUG_DISPLAY, 0); this.debugDisplay = debugDisplay != 0; } @@ -143,12 +143,12 @@ export class CoreDomUtilsProvider { limitedThreshold?: number, alwaysConfirm?: boolean, ): Promise { - const readableSize = CoreTextUtils.instance.bytesToSize(size.size, 2); + const readableSize = CoreTextUtils.bytesToSize(size.size, 2); const getAvailableBytes = async (): Promise => { - const availableBytes = await CoreFile.instance.calculateFreeSpace(); + const availableBytes = await CoreFile.calculateFreeSpace(); - if (CoreApp.instance.isAndroid()) { + if (CoreApp.isAndroid()) { return availableBytes; } else { // Space calculation is not accurate on iOS, but it gets more accurate when space is lower. @@ -165,18 +165,18 @@ export class CoreDomUtilsProvider { if (availableBytes === null) { return ''; } else { - const availableSize = CoreTextUtils.instance.bytesToSize(availableBytes, 2); + const availableSize = CoreTextUtils.bytesToSize(availableBytes, 2); - if (CoreApp.instance.isAndroid() && size.size > availableBytes - CoreConstants.MINIMUM_FREE_SPACE) { + if (CoreApp.isAndroid() && size.size > availableBytes - CoreConstants.MINIMUM_FREE_SPACE) { throw new CoreError( - Translate.instance.instant( + Translate.instant( 'core.course.insufficientavailablespace', { size: readableSize }, ), ); } - return Translate.instance.instant('core.course.availablespace', { available: availableSize }); + return Translate.instant('core.course.availablespace', { available: availableSize }); } }; @@ -188,8 +188,8 @@ export class CoreDomUtilsProvider { limitedThreshold = typeof limitedThreshold == 'undefined' ? CoreConstants.DOWNLOAD_THRESHOLD : limitedThreshold; let wifiPrefix = ''; - if (CoreApp.instance.isNetworkAccessLimited()) { - wifiPrefix = Translate.instance.instant('core.course.confirmlimiteddownload'); + if (CoreApp.isNetworkAccessLimited()) { + wifiPrefix = Translate.instant('core.course.confirmlimiteddownload'); } if (size.size < 0 || (size.size == 0 && !size.total)) { @@ -197,7 +197,7 @@ export class CoreDomUtilsProvider { unknownMessage = unknownMessage || 'core.course.confirmdownloadunknownsize'; return this.showConfirm( - wifiPrefix + Translate.instance.instant( + wifiPrefix + Translate.instant( unknownMessage, { availableSpace: availableSpace }, ), @@ -206,17 +206,17 @@ export class CoreDomUtilsProvider { // Filesize is only partial. return this.showConfirm( - wifiPrefix + Translate.instance.instant( + wifiPrefix + Translate.instant( 'core.course.confirmpartialdownloadsize', { size: readableSize, availableSpace: availableSpace }, ), ); } else if (alwaysConfirm || size.size >= wifiThreshold || - (CoreApp.instance.isNetworkAccessLimited() && size.size >= limitedThreshold)) { + (CoreApp.isNetworkAccessLimited() && size.size >= limitedThreshold)) { message = message || (size.size === 0 ? 'core.course.confirmdownloadzerosize' : 'core.course.confirmdownload'); return this.showConfirm( - wifiPrefix + Translate.instance.instant( + wifiPrefix + Translate.instant( message, { size: readableSize, availableSpace: availableSpace }, ), @@ -293,14 +293,14 @@ export class CoreDomUtilsProvider { const element = elements[i]; let url = 'href' in element ? element.href : element.src; - if (url && CoreUrlUtils.instance.isDownloadableUrl(url) && urls.indexOf(url) == -1) { + if (url && CoreUrlUtils.isDownloadableUrl(url) && urls.indexOf(url) == -1) { urls.push(url); } // Treat video poster. if (element.tagName == 'VIDEO' && element.getAttribute('poster')) { url = element.getAttribute('poster') || ''; - if (url && CoreUrlUtils.instance.isDownloadableUrl(url) && urls.indexOf(url) == -1) { + if (url && CoreUrlUtils.isDownloadableUrl(url) && urls.indexOf(url) == -1) { urls.push(url); } } @@ -386,9 +386,9 @@ export class CoreDomUtilsProvider { focusElement(el: HTMLElement): void { if (el?.focus) { el.focus(); - if (CoreApp.instance.isAndroid() && this.supportsInputKeyboard(el)) { + if (CoreApp.isAndroid() && this.supportsInputKeyboard(el)) { // On some Android versions the keyboard doesn't open automatically. - CoreApp.instance.openKeyboard(); + CoreApp.openKeyboard(); } } } @@ -649,8 +649,8 @@ export class CoreDomUtilsProvider { * @return True if the message error is a network error, false otherwise. */ protected isNetworkError(message: string, error?: CoreError | CoreTextErrorObject | string): boolean { - return message == Translate.instance.instant('core.networkerrormsg') || - message == Translate.instance.instant('core.fileuploader.errormustbeonlinetoupload') || + return message == Translate.instant('core.networkerrormsg') || + message == Translate.instant('core.fileuploader.errormustbeonlinetoupload') || error instanceof CoreNetworkError; } @@ -673,11 +673,11 @@ export class CoreDomUtilsProvider { if (this.debugDisplay) { // Get the debug info. Escape the HTML so it is displayed as it is in the view. if ('debuginfo' in error && error.debuginfo) { - extraInfo = '

' + CoreTextUtils.instance.escapeHTML(error.debuginfo, false); + extraInfo = '

' + CoreTextUtils.escapeHTML(error.debuginfo, false); } if ('backtrace' in error && error.backtrace) { - extraInfo += '

' + CoreTextUtils.instance.replaceNewLines( - CoreTextUtils.instance.escapeHTML(error.backtrace, false), + extraInfo += '

' + CoreTextUtils.replaceNewLines( + CoreTextUtils.escapeHTML(error.backtrace, false), '
', ); } @@ -692,7 +692,7 @@ export class CoreDomUtilsProvider { } // We received an object instead of a string. Search for common properties. - errorMessage = CoreTextUtils.instance.getErrorMessageFromError(error); + errorMessage = CoreTextUtils.getErrorMessageFromError(error); if (!errorMessage) { // No common properties found, just stringify it. errorMessage = JSON.stringify(error); @@ -713,7 +713,7 @@ export class CoreDomUtilsProvider { return null; } - let message = CoreTextUtils.instance.decodeHTML(needsTranslate ? Translate.instance.instant(errorMessage) : errorMessage); + let message = CoreTextUtils.decodeHTML(needsTranslate ? Translate.instant(errorMessage) : errorMessage); if (extraInfo) { message += extraInfo; @@ -764,7 +764,7 @@ export class CoreDomUtilsProvider { * @return Resolved if found, rejected if too many tries. */ waitElementToExist(findFunction: () => HTMLElement | null): Promise { - const promiseInterval = CoreUtils.instance.promiseDefer(); + const promiseInterval = CoreUtils.promiseDefer(); let tries = 100; const clear = setInterval(() => { @@ -844,7 +844,7 @@ export class CoreDomUtilsProvider { * @return Promise resolved with boolean: true if enabled, false otherwise. */ isRichTextEditorEnabled(): Promise { - return CoreConfig.instance.get(CoreConstants.SETTINGS_RICH_TEXT_EDITOR, true).then((enabled) => !!enabled); + return CoreConfig.get(CoreConstants.SETTINGS_RICH_TEXT_EDITOR, true).then((enabled) => !!enabled); } /** @@ -976,7 +976,7 @@ export class CoreDomUtilsProvider { const media = Array.from(element.querySelectorAll('img, video, audio, source, track')); media.forEach((media: HTMLElement) => { const currentSrc = media.getAttribute('src'); - const newSrc = currentSrc ? paths[CoreTextUtils.instance.decodeURIComponent(currentSrc)] : undefined; + const newSrc = currentSrc ? paths[CoreTextUtils.decodeURIComponent(currentSrc)] : undefined; if (typeof newSrc != 'undefined') { media.setAttribute('src', newSrc); @@ -985,7 +985,7 @@ export class CoreDomUtilsProvider { // Treat video posters. if (media.tagName == 'VIDEO' && media.getAttribute('poster')) { const currentPoster = media.getAttribute('poster'); - const newPoster = paths[CoreTextUtils.instance.decodeURIComponent(currentPoster!)]; + const newPoster = paths[CoreTextUtils.decodeURIComponent(currentPoster!)]; if (typeof newPoster !== 'undefined') { media.setAttribute('poster', newPoster); } @@ -996,7 +996,7 @@ export class CoreDomUtilsProvider { const anchors = Array.from(element.querySelectorAll('a')); anchors.forEach((anchor: HTMLElement) => { const currentHref = anchor.getAttribute('href'); - const newHref = currentHref ? paths[CoreTextUtils.instance.decodeURIComponent(currentHref)] : undefined; + const newHref = currentHref ? paths[CoreTextUtils.decodeURIComponent(currentHref)] : undefined; if (typeof newHref != 'undefined') { anchor.setAttribute('href', newHref); @@ -1190,7 +1190,7 @@ export class CoreDomUtilsProvider { return this.showAlertWithOptions({ header, message, - buttons: [buttonText || Translate.instance.instant('core.ok')], + buttons: [buttonText || Translate.instant('core.ok')], }, autocloseTime); } @@ -1202,11 +1202,11 @@ export class CoreDomUtilsProvider { * @return Promise resolved with the alert modal. */ async showAlertWithOptions(options: AlertOptions = {}, autocloseTime?: number): Promise { - const hasHTMLTags = CoreTextUtils.instance.hasHTMLTags( options.message || ''); + const hasHTMLTags = CoreTextUtils.hasHTMLTags( options.message || ''); if (hasHTMLTags) { // Format the text. - options.message = await CoreTextUtils.instance.formatText( options.message); + options.message = await CoreTextUtils.formatText( options.message); } const alertId = Md5.hashAsciiStr((options.header || '') + '#' + (options.message || '')); @@ -1216,7 +1216,7 @@ export class CoreDomUtilsProvider { return this.displayedAlerts[alertId]; } - const alert = await AlertController.instance.create(options); + const alert = await AlertController.create(options); // eslint-disable-next-line promise/catch-or-return alert.present().then(() => { @@ -1270,9 +1270,9 @@ export class CoreDomUtilsProvider { buttonText?: string, autocloseTime?: number, ): Promise { - header = header ? Translate.instance.instant(header) : header; - message = message ? Translate.instance.instant(message) : message; - buttonText = buttonText ? Translate.instance.instant(buttonText) : buttonText; + header = header ? Translate.instant(header) : header; + message = message ? Translate.instant(message) : message; + buttonText = buttonText ? Translate.instant(buttonText) : buttonText; return this.showAlert(header, message, buttonText, autocloseTime); } @@ -1291,9 +1291,9 @@ export class CoreDomUtilsProvider { options?: AlertOptions, ): Promise { return this.showConfirm( - Translate.instance.instant(translateMessage, translateArgs), + Translate.instant(translateMessage, translateArgs), undefined, - Translate.instance.instant('core.delete'), + Translate.instant('core.delete'), undefined, options, ); @@ -1322,14 +1322,14 @@ export class CoreDomUtilsProvider { options.buttons = [ { - text: cancelText || Translate.instance.instant('core.cancel'), + text: cancelText || Translate.instant('core.cancel'), role: 'cancel', handler: () => { reject(new CoreCanceledError('')); }, }, { - text: okText || Translate.instance.instant('core.ok'), + text: okText || Translate.instant('core.ok'), handler: (data: T) => { resolve(data); }, @@ -1371,13 +1371,13 @@ export class CoreDomUtilsProvider { const alertOptions: AlertOptions = { message: message, - buttons: [Translate.instance.instant('core.ok')], + buttons: [Translate.instant('core.ok')], }; if (this.isNetworkError(message, error)) { alertOptions.cssClass = 'core-alert-network-error'; } else { - alertOptions.header = Translate.instance.instant('core.error'); + alertOptions.header = Translate.instant('core.error'); } return this.showAlertWithOptions(alertOptions, autocloseTime); @@ -1406,7 +1406,7 @@ export class CoreDomUtilsProvider { let errorMessage = error || undefined; if (error && typeof error != 'string') { - errorMessage = CoreTextUtils.instance.getErrorMessageFromError(error); + errorMessage = CoreTextUtils.getErrorMessageFromError(error); } return this.showErrorModal(typeof errorMessage == 'string' ? error! : defaultError, needsTranslate, autocloseTime); @@ -1444,12 +1444,12 @@ export class CoreDomUtilsProvider { */ async showModalLoading(text?: string, needsTranslate?: boolean): Promise { if (!text) { - text = Translate.instance.instant('core.loading'); + text = Translate.instant('core.loading'); } else if (needsTranslate) { - text = Translate.instance.instant(text); + text = Translate.instant(text); } - const loadingElement = await LoadingController.instance.create({ + const loadingElement = await LoadingController.create({ message: text, }); @@ -1469,27 +1469,27 @@ export class CoreDomUtilsProvider { */ async showDownloadAppNoticeModal(message: string, link?: string): Promise { const buttons: AlertButton[] = [{ - text: Translate.instance.instant('core.ok'), + text: Translate.instant('core.ok'), role: 'cancel', }]; if (link) { buttons.push({ - text: Translate.instance.instant('core.download'), + text: Translate.instant('core.download'), handler: (): void => { - CoreUtils.instance.openInBrowser(link); + CoreUtils.openInBrowser(link); }, }); } - const alert = await AlertController.instance.create({ + const alert = await AlertController.create({ message: message, buttons: buttons, }); await alert.present(); - const isDevice = CoreApp.instance.isAndroid() || CoreApp.instance.isIOS(); + const isDevice = CoreApp.isAndroid() || CoreApp.isIOS(); if (!isDevice) { // Treat all anchors so they don't override the app. const alertMessageEl: HTMLElement | null = alert.querySelector('.alert-message'); @@ -1514,7 +1514,7 @@ export class CoreDomUtilsProvider { type: TextFieldTypes | 'checkbox' | 'radio' | 'textarea' = 'password', ): Promise { // eslint-disable-line @typescript-eslint/no-explicit-any return new Promise((resolve, reject) => { - placeholder = placeholder ?? Translate.instance.instant('core.login.password'); + placeholder = placeholder ?? Translate.instant('core.login.password'); const options: AlertOptions = { header, @@ -1528,14 +1528,14 @@ export class CoreDomUtilsProvider { ], buttons: [ { - text: Translate.instance.instant('core.cancel'), + text: Translate.instant('core.cancel'), role: 'cancel', handler: () => { reject(); }, }, { - text: Translate.instance.instant('core.ok'), + text: Translate.instant('core.ok'), handler: (data) => { resolve(data.promptinput); }, @@ -1579,10 +1579,10 @@ export class CoreDomUtilsProvider { cssClass: string = '', ): Promise { if (needsTranslate) { - text = Translate.instance.instant(text); + text = Translate.instant(text); } - const loader = await ToastController.instance.create({ + const loader = await ToastController.create({ message: text, duration: duration, position: 'bottom', @@ -1656,7 +1656,7 @@ export class CoreDomUtilsProvider { event.preventDefault(); event.stopPropagation(); - CoreUtils.instance.openInBrowser(href); + CoreUtils.openInBrowser(href); } }); }); @@ -1759,7 +1759,7 @@ export class CoreDomUtilsProvider { } -export class CoreDomUtils extends makeSingleton(CoreDomUtilsProvider) {} +export const CoreDomUtils = makeSingleton(CoreDomUtilsProvider); type AnchorOrMediaElement = HTMLAnchorElement | HTMLImageElement | HTMLAudioElement | HTMLVideoElement | HTMLSourceElement | HTMLTrackElement; diff --git a/src/core/services/utils/iframe.ts b/src/core/services/utils/iframe.ts index 85dc4cbb9..587759265 100644 --- a/src/core/services/utils/iframe.ts +++ b/src/core/services/utils/iframe.ts @@ -51,9 +51,9 @@ export class CoreIframeUtilsProvider { constructor() { this.logger = CoreLogger.getInstance('CoreUtilsProvider'); - if (CoreApp.instance.isIOS() && 'WKUserScript' in window) { + if (CoreApp.isIOS() && 'WKUserScript' in window) { // eslint-disable-next-line promise/catch-or-return - Platform.instance.ready().then(() => this.injectiOSScripts(window)); + Platform.ready().then(() => this.injectiOSScripts(window)); } } @@ -67,7 +67,7 @@ export class CoreIframeUtilsProvider { checkOnlineFrameInOffline(element: CoreFrameElement, isSubframe?: boolean): boolean { const src = 'src' in element ? element.src : element.data; - if (src && src != 'about:blank' && !CoreUrlUtils.instance.isLocalFileUrl(src) && !CoreApp.instance.isOnline()) { + if (src && src != 'about:blank' && !CoreUrlUtils.isLocalFileUrl(src) && !CoreApp.isOnline()) { if (element.classList.contains('core-iframe-offline-disabled')) { // Iframe already hidden, stop. return true; @@ -91,9 +91,9 @@ export class CoreIframeUtilsProvider { } // If the network changes, check it again. - const subscription = Network.instance.onConnect().subscribe(() => { + const subscription = Network.onConnect().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. - NgZone.instance.run(() => { + NgZone.run(() => { if (!this.checkOnlineFrameInOffline(element, isSubframe)) { // Now the app is online, no need to check connection again. subscription.unsubscribe(); @@ -113,7 +113,7 @@ export class CoreIframeUtilsProvider { } // Remove the warning and show the iframe - CoreDomUtils.instance.removeElement(element.parentElement!, 'div.core-iframe-offline-warning'); + CoreDomUtils.removeElement(element.parentElement!, 'div.core-iframe-offline-warning'); element.classList.remove('core-iframe-offline-disabled'); if (isSubframe) { @@ -308,16 +308,16 @@ export class CoreIframeUtilsProvider { * @return Promise resolved when done. */ protected async windowOpen(url: string, name: string, element?: CoreFrameElement): Promise { - const scheme = CoreUrlUtils.instance.getUrlScheme(url); + const scheme = CoreUrlUtils.getUrlScheme(url); if (!scheme) { // It's a relative URL, use the frame src to create the full URL. const src = element ? ('src' in element ? element.src : element.data) : null; if (src) { - const dirAndFile = CoreFile.instance.getFileAndDirectoryFromPath(src); + const dirAndFile = CoreFile.getFileAndDirectoryFromPath(src); if (dirAndFile.directory) { - url = CoreTextUtils.instance.concatenatePaths(dirAndFile.directory, url); + url = CoreTextUtils.concatenatePaths(dirAndFile.directory, url); } else { this.logger.warn('Cannot get iframe dir path to open relative url', url, element); @@ -343,22 +343,22 @@ export class CoreIframeUtilsProvider { } else { element.setAttribute('src', url); } - } else if (CoreUrlUtils.instance.isLocalFileUrl(url)) { + } else if (CoreUrlUtils.isLocalFileUrl(url)) { // It's a local file. const filename = url.substr(url.lastIndexOf('/') + 1); - if (!CoreFileHelper.instance.isOpenableInApp({ filename })) { + if (!CoreFileHelper.isOpenableInApp({ filename })) { try { - await CoreFileHelper.instance.showConfirmOpenUnsupportedFile(); + await CoreFileHelper.showConfirmOpenUnsupportedFile(); } catch (error) { return; // Cancelled, stop. } } try { - await CoreUtils.instance.openFile(url); + await CoreUtils.openFile(url); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } } else { // It's an external link, check if it can be opened in the app. @@ -390,7 +390,7 @@ export class CoreIframeUtilsProvider { return; } - if (urlParts.protocol && !CoreUrlUtils.instance.isLocalFileUrlScheme(urlParts.protocol, urlParts.domain || '')) { + if (urlParts.protocol && !CoreUrlUtils.isLocalFileUrlScheme(urlParts.protocol, urlParts.domain || '')) { // Scheme suggests it's an external resource. event && event.preventDefault(); @@ -400,7 +400,7 @@ export class CoreIframeUtilsProvider { if ( element && frameSrc && - !CoreUrlUtils.instance.isLocalFileUrl(frameSrc) && + !CoreUrlUtils.isLocalFileUrl(frameSrc) && (!link.target || link.target == '_self') ) { // Load the link inside the frame itself. @@ -414,10 +414,10 @@ export class CoreIframeUtilsProvider { } // The frame is local or the link needs to be opened in a new window. Open in browser. - if (!CoreSites.instance.isLoggedIn()) { - CoreUtils.instance.openInBrowser(link.href); + if (!CoreSites.isLoggedIn()) { + CoreUtils.openInBrowser(link.href); } else { - await CoreSites.instance.getCurrentSite()!.openInBrowserWithAutoLoginIfSameSite(link.href); + await CoreSites.getCurrentSite()!.openInBrowserWithAutoLoginIfSameSite(link.href); } } else if (link.target == '_parent' || link.target == '_top' || link.target == '_blank') { // Opening links with _parent, _top or _blank can break the app. We'll open it in InAppBrowser. @@ -425,20 +425,20 @@ export class CoreIframeUtilsProvider { const filename = link.href.substr(link.href.lastIndexOf('/') + 1); - if (!CoreFileHelper.instance.isOpenableInApp({ filename })) { + if (!CoreFileHelper.isOpenableInApp({ filename })) { try { - await CoreFileHelper.instance.showConfirmOpenUnsupportedFile(); + await CoreFileHelper.showConfirmOpenUnsupportedFile(); } catch (error) { return; // Cancelled, stop. } } try { - await CoreUtils.instance.openFile(link.href); + await CoreUtils.openFile(link.href); } catch (error) { - CoreDomUtils.instance.showErrorModal(error); + CoreDomUtils.showErrorModal(error); } - } else if (CoreApp.instance.isIOS() && (!link.target || link.target == '_self') && element) { + } else if (CoreApp.isIOS() && (!link.target || link.target == '_self') && element) { // In cordova ios 4.1.0 links inside iframes stopped working. We'll manually treat them. event && event.preventDefault(); if (element.tagName.toLowerCase() == 'object') { @@ -455,9 +455,9 @@ export class CoreIframeUtilsProvider { * @param userScriptWindow Window. */ private injectiOSScripts(userScriptWindow: WKUserScriptWindow) { - const wwwPath = CoreFile.instance.getWWWAbsolutePath(); - const linksPath = CoreTextUtils.instance.concatenatePaths(wwwPath, 'assets/js/iframe-treat-links.js'); - const recaptchaPath = CoreTextUtils.instance.concatenatePaths(wwwPath, 'assets/js/iframe-recaptcha.js'); + const wwwPath = CoreFile.getWWWAbsolutePath(); + const linksPath = CoreTextUtils.concatenatePaths(wwwPath, 'assets/js/iframe-treat-links.js'); + const recaptchaPath = CoreTextUtils.concatenatePaths(wwwPath, 'assets/js/iframe-recaptcha.js'); userScriptWindow.WKUserScript?.addScript({ id: 'CoreIframeUtilsLinksScript', file: linksPath }); userScriptWindow.WKUserScript?.addScript({ @@ -477,7 +477,7 @@ export class CoreIframeUtilsProvider { * @return Promise resolved when done. */ async fixIframeCookies(url: string): Promise { - if (!CoreApp.instance.isIOS() || !url || CoreUrlUtils.instance.isLocalFileUrl(url)) { + if (!CoreApp.isIOS() || !url || CoreUrlUtils.isLocalFileUrl(url)) { // No need to fix cookies. return; } @@ -502,7 +502,7 @@ export class CoreIframeUtilsProvider { } -export class CoreIframeUtils extends makeSingleton(CoreIframeUtilsProvider) {} +export const CoreIframeUtils = makeSingleton(CoreIframeUtilsProvider); /** * Subtype of HTMLAnchorElement, with some calculated data. diff --git a/src/core/services/utils/mimetype.ts b/src/core/services/utils/mimetype.ts index b4257d084..7c57a147d 100644 --- a/src/core/services/utils/mimetype.ts +++ b/src/core/services/utils/mimetype.ts @@ -164,11 +164,11 @@ export class CoreMimetypeUtilsProvider { * @param path Alternative path that will override fileurl from file object. */ getEmbeddedHtml(file: CoreWSExternalFile | FileEntry, path?: string): string { - const filename = CoreUtils.instance.isFileEntry(file) ? (file as FileEntry).name : file.filename; - const extension = !CoreUtils.instance.isFileEntry(file) && file.mimetype + const filename = CoreUtils.isFileEntry(file) ? (file as FileEntry).name : file.filename; + const extension = !CoreUtils.isFileEntry(file) && file.mimetype ? this.getExtension(file.mimetype) : (filename && this.getFileExtension(filename)); - const mimeType = !CoreUtils.instance.isFileEntry(file) && file.mimetype + const mimeType = !CoreUtils.isFileEntry(file) && file.mimetype ? file.mimetype : (extension && this.getMimeType(extension)); @@ -181,8 +181,8 @@ export class CoreMimetypeUtilsProvider { // @todo linting: See if this can be removed (file as { embedType?: string }).embedType = embedType; - path = path ?? (CoreUtils.instance.isFileEntry(file) ? file.toURL() : file.fileurl); - path = path && CoreFile.instance.convertFileSrc(path); + path = path ?? (CoreUtils.isFileEntry(file) ? file.toURL() : file.fileurl); + path = path && CoreFile.convertFileSrc(path); switch (embedType) { case 'image': @@ -407,7 +407,7 @@ export class CoreMimetypeUtilsProvider { let mimetype: string | undefined = ''; let extension: string | undefined = ''; - if (typeof obj == 'object' && CoreUtils.instance.isFileEntry(obj)) { + if (typeof obj == 'object' && CoreUtils.isFileEntry(obj)) { // It's a FileEntry. Don't use the file function because it's asynchronous and the type isn't reliable. filename = obj.name; } else if (typeof obj == 'object') { @@ -449,15 +449,15 @@ export class CoreMimetypeUtilsProvider { const value = attr[key]; translateParams[key] = value; translateParams[key.toUpperCase()] = value.toUpperCase(); - translateParams[CoreTextUtils.instance.ucFirst(key)] = CoreTextUtils.instance.ucFirst(value); + translateParams[CoreTextUtils.ucFirst(key)] = CoreTextUtils.ucFirst(value); } // MIME types may include + symbol but this is not permitted in string ids. const safeMimetype = mimetype.replace(/\+/g, '_'); const safeMimetypeStr = mimetypeStr.replace(/\+/g, '_'); - const safeMimetypeTrns = Translate.instance.instant(langPrefix + safeMimetype, { $a: translateParams }); - const safeMimetypeStrTrns = Translate.instance.instant(langPrefix + safeMimetypeStr, { $a: translateParams }); - const defaultTrns = Translate.instance.instant(langPrefix + 'default', { $a: translateParams }); + const safeMimetypeTrns = Translate.instant(langPrefix + safeMimetype, { $a: translateParams }); + const safeMimetypeStrTrns = Translate.instant(langPrefix + safeMimetypeStr, { $a: translateParams }); + const defaultTrns = Translate.instant(langPrefix + 'default', { $a: translateParams }); let result = mimetype; if (safeMimetypeTrns != langPrefix + safeMimetype) { @@ -469,7 +469,7 @@ export class CoreMimetypeUtilsProvider { } if (capitalise) { - result = CoreTextUtils.instance.ucFirst(result); + result = CoreTextUtils.ucFirst(result); } return result; @@ -529,7 +529,7 @@ export class CoreMimetypeUtilsProvider { */ getTranslatedGroupName(name: string): string { const key = 'assets.mimetypes.group:' + name; - const translated = Translate.instance.instant(key); + const translated = Translate.instant(key); return translated != key ? translated : name; } @@ -580,4 +580,4 @@ export class CoreMimetypeUtilsProvider { } -export class CoreMimetypeUtils extends makeSingleton(CoreMimetypeUtilsProvider) {} +export const CoreMimetypeUtils = makeSingleton(CoreMimetypeUtilsProvider); diff --git a/src/core/services/utils/text.ts b/src/core/services/utils/text.ts index 7063dec43..70d30bb15 100644 --- a/src/core/services/utils/text.ts +++ b/src/core/services/utils/text.ts @@ -145,7 +145,7 @@ export class CoreTextUtilsProvider { * @return URL to view the address. */ buildAddressURL(address: string): SafeUrl { - return this.sanitizer.bypassSecurityTrustUrl((CoreApp.instance.isAndroid() ? 'geo:0,0?q=' : 'http://maps.google.com?q=') + + return this.sanitizer.bypassSecurityTrustUrl((CoreApp.isAndroid() ? 'geo:0,0?q=' : 'http://maps.google.com?q=') + encodeURIComponent(address)); } @@ -193,7 +193,7 @@ export class CoreTextUtilsProvider { let builtMessage = messages[0]; for (let i = 1; i < messages.length; i++) { - builtMessage = Translate.instance.instant('core.twoparagraphs', { p1: builtMessage, p2: messages[i] }); + builtMessage = Translate.instant('core.twoparagraphs', { p1: builtMessage, p2: messages[i] }); } return builtMessage; @@ -208,7 +208,7 @@ export class CoreTextUtilsProvider { */ bytesToSize(bytes: number, precision: number = 2): string { if (typeof bytes == 'undefined' || bytes === null || bytes < 0) { - return Translate.instance.instant('core.notapplicable'); + return Translate.instant('core.notapplicable'); } if (precision < 0) { @@ -216,7 +216,7 @@ export class CoreTextUtilsProvider { } const keys = ['core.sizeb', 'core.sizekb', 'core.sizemb', 'core.sizegb', 'core.sizetb']; - const units = Translate.instance.instant(keys); + const units = Translate.instant(keys); let pos = 0; if (bytes >= 1024) { @@ -228,7 +228,7 @@ export class CoreTextUtilsProvider { bytes = Number(Math.round(parseFloat(bytes + 'e+' + precision)) + 'e-' + precision); } - return Translate.instance.instant('core.humanreadablesize', { size: bytes, unit: units[keys[pos]] }); + return Translate.instant('core.humanreadablesize', { size: bytes, unit: units[keys[pos]] }); } /** @@ -983,7 +983,7 @@ export class CoreTextUtilsProvider { return Promise.resolve(''); } - return CoreLang.instance.getCurrentLanguage().then((language) => { + return CoreLang.getCurrentLanguage().then((language) => { // Match the current language. const anyLangRegEx = /<(?:lang|span)[^>]+lang="[a-zA-Z0-9_-]+"[^>]*>(.*?)<\/(?:lang|span)>/g; let currentLangRegEx = new RegExp('<(?:lang|span)[^>]+lang="' + language + '"[^>]*>(.*?)', 'g'); @@ -1082,7 +1082,7 @@ export class CoreTextUtilsProvider { ...options, }; - const modal = await ModalController.instance.create(modalOptions); + const modal = await ModalController.create(modalOptions); await modal.present(); } @@ -1104,4 +1104,4 @@ export type CoreTextUtilsViewTextOptions = { modalOptions?: Partial; // Modal options. }; -export class CoreTextUtils extends makeSingleton(CoreTextUtilsProvider) {} +export const CoreTextUtils = makeSingleton(CoreTextUtilsProvider); diff --git a/src/core/services/utils/time.ts b/src/core/services/utils/time.ts index ea9d9128c..7439be193 100644 --- a/src/core/services/utils/time.ts +++ b/src/core/services/utils/time.ts @@ -161,11 +161,11 @@ export class CoreTimeUtilsProvider { const mins = Math.floor(remainder / CoreConstants.SECONDS_MINUTE); const secs = remainder - (mins * CoreConstants.SECONDS_MINUTE); - const ss = Translate.instance.instant('core.' + (secs == 1 ? 'sec' : 'secs')); - const sm = Translate.instance.instant('core.' + (mins == 1 ? 'min' : 'mins')); - const sh = Translate.instance.instant('core.' + (hours == 1 ? 'hour' : 'hours')); - const sd = Translate.instance.instant('core.' + (days == 1 ? 'day' : 'days')); - const sy = Translate.instance.instant('core.' + (years == 1 ? 'year' : 'years')); + const ss = Translate.instant('core.' + (secs == 1 ? 'sec' : 'secs')); + const sm = Translate.instant('core.' + (mins == 1 ? 'min' : 'mins')); + const sh = Translate.instant('core.' + (hours == 1 ? 'hour' : 'hours')); + const sd = Translate.instant('core.' + (days == 1 ? 'day' : 'days')); + const sy = Translate.instant('core.' + (years == 1 ? 'year' : 'years')); let oyears = ''; let odays = ''; let ohours = ''; @@ -204,7 +204,7 @@ export class CoreTimeUtilsProvider { return osecs; } - return Translate.instance.instant('core.now'); + return Translate.instant('core.now'); } /** @@ -295,7 +295,7 @@ export class CoreTimeUtilsProvider { * @return Readable date. */ userDate(timestamp: number, format?: string, convert: boolean = true, fixDay: boolean = true, fixHour: boolean = true): string { - format = Translate.instance.instant(format ? format : 'core.strftimedaydatetime'); + format = Translate.instant(format ? format : 'core.strftimedaydatetime'); if (fixDay) { format = format!.replace(/%d/g, '%e'); @@ -369,4 +369,4 @@ export class CoreTimeUtilsProvider { } -export class CoreTimeUtils extends makeSingleton(CoreTimeUtilsProvider) {} +export const CoreTimeUtils = makeSingleton(CoreTimeUtilsProvider); diff --git a/src/core/services/utils/url.ts b/src/core/services/utils/url.ts index c773dd3fb..bff2c6d1f 100644 --- a/src/core/services/utils/url.ts +++ b/src/core/services/utils/url.ts @@ -103,8 +103,8 @@ export class CoreUrlUtilsProvider { // Do not use tokenpluginfile if site doesn't use slash params, the URL doesn't work. // Also, only use it for "core" pluginfile endpoints. Some plugins can implement their own endpoint (like customcert). return !!accessKey && !url.match(/[&?]file=/) && ( - url.indexOf(CoreTextUtils.instance.concatenatePaths(siteUrl, 'pluginfile.php')) === 0 || - url.indexOf(CoreTextUtils.instance.concatenatePaths(siteUrl, 'webservice/pluginfile.php')) === 0); + url.indexOf(CoreTextUtils.concatenatePaths(siteUrl, 'pluginfile.php')) === 0 || + url.indexOf(CoreTextUtils.concatenatePaths(siteUrl, 'webservice/pluginfile.php')) === 0); } /** @@ -131,7 +131,7 @@ export class CoreUrlUtilsProvider { } urlAndHash[0].replace(regex, (match: string, key: string, value: string): string => { - params[key] = typeof value != 'undefined' ? CoreTextUtils.instance.decodeURIComponent(value) : ''; + params[key] = typeof value != 'undefined' ? CoreTextUtils.decodeURIComponent(value) : ''; if (subParams) { params[key] = params[key].replace(subParamsPlaceholder, subParams); @@ -177,7 +177,7 @@ export class CoreUrlUtilsProvider { } // Check if is a valid URL (contains the pluginfile endpoint) and belongs to the site. - if (!this.isPluginFileUrl(url) || url.indexOf(CoreTextUtils.instance.addEndingSlash(siteUrl)) !== 0) { + if (!this.isPluginFileUrl(url) || url.indexOf(CoreTextUtils.addEndingSlash(siteUrl)) !== 0) { return url; } @@ -186,7 +186,7 @@ export class CoreUrlUtilsProvider { url = url.replace(/(\/webservice)?\/pluginfile\.php/, '/tokenpluginfile.php/' + accessKey); } else { // Use pluginfile.php. Some webservices returns directly the correct download url, others not. - if (url.indexOf(CoreTextUtils.instance.concatenatePaths(siteUrl, 'pluginfile.php')) === 0) { + if (url.indexOf(CoreTextUtils.concatenatePaths(siteUrl, 'pluginfile.php')) === 0) { url = url.replace('/pluginfile', '/webservice/pluginfile'); } @@ -241,7 +241,7 @@ export class CoreUrlUtilsProvider { } try { - const lang = await CoreLang.instance.getCurrentLanguage(); + const lang = await CoreLang.getCurrentLanguage(); return docsUrl.replace('/en/', '/' + lang + '/'); } catch (error) { @@ -263,7 +263,7 @@ export class CoreUrlUtilsProvider { let videoId = ''; const params: CoreUrlParams = {}; - url = CoreTextUtils.instance.decodeHTML(url); + url = CoreTextUtils.decodeHTML(url); // Get the video ID. let match = url.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/); @@ -508,7 +508,7 @@ export class CoreUrlUtilsProvider { url = url.replace(/&/g, '&'); // It site URL is supplied, check if the URL belongs to the site. - if (siteUrl && url.indexOf(CoreTextUtils.instance.addEndingSlash(siteUrl)) !== 0) { + if (siteUrl && url.indexOf(CoreTextUtils.addEndingSlash(siteUrl)) !== 0) { return url; } @@ -523,6 +523,6 @@ export class CoreUrlUtilsProvider { } -export class CoreUrlUtils extends makeSingleton(CoreUrlUtilsProvider) {} +export const CoreUrlUtils = makeSingleton(CoreUrlUtilsProvider); export type CoreUrlParams = {[key: string]: string}; diff --git a/src/core/services/utils/utils.ts b/src/core/services/utils/utils.ts index dc5c66b65..b5b23f0bf 100644 --- a/src/core/services/utils/utils.ts +++ b/src/core/services/utils/utils.ts @@ -57,14 +57,14 @@ export class CoreUtilsProvider { * @return New error message. */ addDataNotDownloadedError(error: Error | string, defaultError?: string): string { - const errorMessage = CoreTextUtils.instance.getErrorMessageFromError(error) || defaultError || ''; + const errorMessage = CoreTextUtils.getErrorMessageFromError(error) || defaultError || ''; if (this.isWebServiceError(error)) { return errorMessage; } // Local error. Add an extra warning. - return errorMessage + '

' + Translate.instance.instant('core.errorsomedatanotdownloaded'); + return errorMessage + '

' + Translate.instant('core.errorsomedatanotdownloaded'); } /** @@ -101,7 +101,7 @@ export class CoreUtilsProvider { * @return Promise resolved if all promises are resolved and rejected if at least 1 promise fails. */ async allPromisesIgnoringErrors(promises: Promise[]): Promise { - await CoreUtils.instance.ignoreErrors(this.allPromises(promises)); + await CoreUtils.ignoreErrors(this.allPromises(promises)); } /** @@ -217,7 +217,7 @@ export class CoreUtilsProvider { } try { - const response = await this.timeoutPromise(window.fetch(url, initOptions), CoreWS.instance.getRequestTimeout()); + const response = await this.timeoutPromise(window.fetch(url, initOptions), CoreWS.getRequestTimeout()); return !!response && response.redirected; } catch (error) { @@ -308,7 +308,7 @@ export class CoreUtilsProvider { */ async copyToClipboard(text: string): Promise { try { - await Clipboard.instance.copy(text); + await Clipboard.copy(text); } catch { // Use HTML Copy command. const virtualInput = document.createElement('textarea'); @@ -319,7 +319,7 @@ export class CoreUtilsProvider { } // Show toast using ionicLoading. - CoreDomUtils.instance.showToast('core.copiedtoclipboard', true); + CoreDomUtils.showToast('core.copiedtoclipboard', true); } /** @@ -331,7 +331,7 @@ export class CoreUtilsProvider { * @deprecated since 3.9.5. Just create the error directly. */ createFakeWSError(message: string, needsTranslate?: boolean): CoreWSError { - return CoreWS.instance.createFakeWSError(message, needsTranslate); + return CoreWS.createFakeWSError(message, needsTranslate); } /** @@ -506,7 +506,7 @@ export class CoreUtilsProvider { return ''; } - const localeSeparator = Translate.instance.instant('core.decsep'); + const localeSeparator = Translate.instant('core.decsep'); // Convert float to string. const floatString = float + ''; @@ -592,7 +592,7 @@ export class CoreUtilsProvider { */ getCountryName(code: string): string { const countryKey = 'assets.countries.' + code; - const countryName = Translate.instance.instant(countryKey); + const countryName = Translate.instant(countryKey); return countryName !== countryKey ? countryName : code; } @@ -611,7 +611,7 @@ export class CoreUtilsProvider { keys.forEach((key) => { if (key.indexOf('assets.countries.') === 0) { const code = key.replace('assets.countries.', ''); - countries[code] = Translate.instance.instant(key); + countries[code] = Translate.instant(key); } }); @@ -645,11 +645,11 @@ export class CoreUtilsProvider { */ protected getCountryKeysList(): Promise { // It's possible that the current language isn't translated, so try with default language first. - const defaultLang = CoreLang.instance.getDefaultLanguage(); + const defaultLang = CoreLang.getDefaultLanguage(); return this.getCountryKeysListForLanguage(defaultLang).catch(() => { // Not translated, try to use the fallback language. - const fallbackLang = CoreLang.instance.getFallbackLanguage(); + const fallbackLang = CoreLang.getFallbackLanguage(); if (fallbackLang === defaultLang) { // Same language, just reject. @@ -668,7 +668,7 @@ export class CoreUtilsProvider { */ protected async getCountryKeysListForLanguage(lang: string): Promise { // Get the translation table for the language. - const table = await CoreLang.instance.getTranslationTable(lang); + const table = await CoreLang.getTranslationTable(lang); // Gather all the keys for countries, const keys: string[] = []; @@ -697,15 +697,15 @@ export class CoreUtilsProvider { */ getMimeTypeFromUrl(url: string): Promise { // First check if it can be guessed from the URL. - const extension = CoreMimetypeUtils.instance.guessExtensionFromUrl(url); - const mimetype = extension && CoreMimetypeUtils.instance.getMimeType(extension); + const extension = CoreMimetypeUtils.guessExtensionFromUrl(url); + const mimetype = extension && CoreMimetypeUtils.getMimeType(extension); if (mimetype) { return Promise.resolve(mimetype); } // Can't be guessed, get the remote mimetype. - return CoreWS.instance.getRemoteFileMimeType(url).then(mimetype => mimetype || ''); + return CoreWS.getRemoteFileMimeType(url).then(mimetype => mimetype || ''); } /** @@ -761,7 +761,7 @@ export class CoreUtilsProvider { const name = (this.isFileEntry(file) ? file.name : file.filename) || ''; if (names.indexOf(name) > -1) { - return Translate.instance.instant('core.filenameexist', { $a: name }); + return Translate.instant('core.filenameexist', { $a: name }); } names.push(name); @@ -894,12 +894,12 @@ export class CoreUtilsProvider { */ async openFile(path: string): Promise { // Convert the path to a native path if needed. - path = CoreFile.instance.unconvertFileSrc(path); + path = CoreFile.unconvertFileSrc(path); - const extension = CoreMimetypeUtils.instance.getFileExtension(path); - const mimetype = extension && CoreMimetypeUtils.instance.getMimeType(extension); + const extension = CoreMimetypeUtils.getFileExtension(path); + const mimetype = extension && CoreMimetypeUtils.getMimeType(extension); - if (mimetype == 'text/html' && CoreApp.instance.isAndroid()) { + if (mimetype == 'text/html' && CoreApp.isAndroid()) { // Open HTML local files in InAppBrowser, in system browser some embedded files aren't loaded. this.openInApp(path); @@ -914,17 +914,17 @@ export class CoreUtilsProvider { } try { - await FileOpener.instance.open(path, mimetype || ''); + await FileOpener.open(path, mimetype || ''); } catch (error) { this.logger.error('Error opening file ' + path + ' with mimetype ' + mimetype); this.logger.error('Error: ', JSON.stringify(error)); if (!extension || extension.indexOf('/') > -1 || extension.indexOf('\\') > -1) { // Extension not found. - throw new Error(Translate.instance.instant('core.erroropenfilenoextension')); + throw new Error(Translate.instant('core.erroropenfilenoextension')); } - throw new Error(Translate.instance.instant('core.erroropenfilenoapp')); + throw new Error(Translate.instant('core.erroropenfilenoapp')); } } @@ -952,15 +952,15 @@ export class CoreUtilsProvider { options.allowInlineMediaPlayback = 'yes'; // Allow playing inline videos in iOS. } - if (!options.location && CoreApp.instance.isIOS() && url.indexOf('file://') === 0) { + if (!options.location && CoreApp.isIOS() && url.indexOf('file://') === 0) { // The URL uses file protocol, don't show it on iOS. // In Android we keep it because otherwise we lose the whole toolbar. options.location = 'no'; } - this.iabInstance = InAppBrowser.instance.create(url, '_blank', options); + this.iabInstance = InAppBrowser.create(url, '_blank', options); - if (CoreApp.instance.isMobile()) { + if (CoreApp.isMobile()) { let loadStopSubscription; const loadStartUrls: string[] = []; @@ -978,7 +978,7 @@ export class CoreUtilsProvider { }); }); - if (CoreApp.instance.isAndroid()) { + if (CoreApp.isAndroid()) { // Load stop is needed with InAppBrowser v3. Custom URL schemes no longer trigger load start, simulate it. loadStopSubscription = this.iabInstance.on('loadstop').subscribe((event) => { // Execute the callback in the Angular zone, so change detection doesn't stop working. @@ -1023,26 +1023,26 @@ export class CoreUtilsProvider { * @return Promise resolved when opened. */ async openOnlineFile(url: string): Promise { - if (CoreApp.instance.isAndroid()) { + if (CoreApp.isAndroid()) { // In Android we need the mimetype to open it. const mimetype = await this.ignoreErrors(this.getMimeTypeFromUrl(url)); if (!mimetype) { // Couldn't retrieve mimetype. Return error. - throw new Error(Translate.instance.instant('core.erroropenfilenoextension')); + throw new Error(Translate.instant('core.erroropenfilenoextension')); } const options = { - action: WebIntent.instance.ACTION_VIEW, + action: WebIntent.ACTION_VIEW, url, type: mimetype, }; - return WebIntent.instance.startActivity(options).catch((error) => { + return WebIntent.startActivity(options).catch((error) => { this.logger.error('Error opening online file ' + url + ' with mimetype ' + mimetype); this.logger.error('Error: ', JSON.stringify(error)); - throw new Error(Translate.instance.instant('core.erroropenfilenoapp')); + throw new Error(Translate.instant('core.erroropenfilenoapp')); }); } @@ -1428,7 +1428,7 @@ export class CoreUtilsProvider { } localeFloat = localeFloat.replace(' ', ''); // No spaces - those might be used as thousand separators. - localeFloat = localeFloat.replace(Translate.instance.instant('core.decsep'), '.'); + localeFloat = localeFloat.replace(Translate.instant('core.decsep'), '.'); const parsedFloat = parseFloat(localeFloat); @@ -1489,7 +1489,7 @@ export class CoreUtilsProvider { * @return Whether the app can scan QR codes. */ canScanQR(): boolean { - return CoreApp.instance.isMobile(); + return CoreApp.isMobile(); } /** @@ -1519,14 +1519,14 @@ export class CoreUtilsProvider { } - if (!CoreApp.instance.isMobile()) { + if (!CoreApp.isMobile()) { return Promise.reject('QRScanner isn\'t available in browser.'); } // Ask the user for permission to use the camera. // The scan method also does this, but since it returns an Observable we wouldn't be able to detect if the user denied. try { - const status = await QRScanner.instance.prepare(); + const status = await QRScanner.prepare(); if (!status.authorized) { // No access to the camera, reject. In android this shouldn't happen, denying access passes through catch. @@ -1543,12 +1543,12 @@ export class CoreUtilsProvider { deferred: this.promiseDefer(), // When text is received, stop scanning and return the text. - observable: QRScanner.instance.scan().subscribe(text => this.stopScanQR(text, false)), + observable: QRScanner.scan().subscribe(text => this.stopScanQR(text, false)), }; // Show the camera. try { - await QRScanner.instance.show(); + await QRScanner.show(); document.body.classList.add('core-scanning-qr'); @@ -1580,8 +1580,8 @@ export class CoreUtilsProvider { // Hide camera preview. document.body.classList.remove('core-scanning-qr'); - QRScanner.instance.hide(); - QRScanner.instance.destroy(); + QRScanner.hide(); + QRScanner.destroy(); this.qrScanData.observable.unsubscribe(); // Stop scanning. @@ -1590,7 +1590,7 @@ export class CoreUtilsProvider { } else if (typeof data != 'undefined') { this.qrScanData.deferred.resolve(data as string); } else { - this.qrScanData.deferred.reject(CoreDomUtils.instance.createCanceledError()); + this.qrScanData.deferred.reject(CoreDomUtils.createCanceledError()); } delete this.qrScanData; @@ -1635,7 +1635,7 @@ export class CoreUtilsProvider { } -export class CoreUtils extends makeSingleton(CoreUtilsProvider) {} +export const CoreUtils = makeSingleton(CoreUtilsProvider); /** * Deferred promise. It's similar to the result of $q.defer() in AngularJS. diff --git a/src/core/services/ws.ts b/src/core/services/ws.ts index 66420bbf9..72ea027b5 100644 --- a/src/core/services/ws.ts +++ b/src/core/services/ws.ts @@ -61,10 +61,10 @@ export class CoreWSProvider { * Initialize some data. */ protected async init(): Promise { - await Platform.instance.ready(); + await Platform.ready(); - if (CoreApp.instance.isIOS()) { - NativeHttp.instance.setHeader('*', 'User-Agent', navigator.userAgent); + if (CoreApp.isIOS()) { + NativeHttp.setHeader('*', 'User-Agent', navigator.userAgent); } } @@ -88,7 +88,7 @@ export class CoreWSProvider { siteUrl, data, preSets, - deferred: CoreUtils.instance.promiseDefer(), + deferred: CoreUtils.promiseDefer(), }; this.retryCalls.push(call); @@ -106,8 +106,8 @@ export class CoreWSProvider { */ call(method: string, data: Record, preSets: CoreWSPreSets): Promise { if (!preSets) { - throw new CoreError(Translate.instance.instant('core.unexpectederror')); - } else if (!CoreApp.instance.isOnline()) { + throw new CoreError(Translate.instant('core.unexpectederror')); + } else if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } @@ -183,7 +183,7 @@ export class CoreWSProvider { } } else if (typeof value == 'string') { if (stripUnicode) { - const stripped = CoreTextUtils.instance.stripUnicode(value); + const stripped = CoreTextUtils.stripUnicode(value); if (stripped != value && stripped.trim().length == 0) { return null; } @@ -226,7 +226,7 @@ export class CoreWSProvider { */ createFakeWSError(message: string, needsTranslate?: boolean, translateParams?: {[name: string]: string}): CoreError { if (needsTranslate) { - message = Translate.instance.instant(message, translateParams); + message = Translate.instant(message, translateParams); } return new CoreError(message); @@ -249,7 +249,7 @@ export class CoreWSProvider { ): Promise { this.logger.debug('Downloading file', url, path, addExtension); - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } @@ -259,9 +259,9 @@ export class CoreWSProvider { try { // Create the tmp file as an empty file. - const fileEntry = await CoreFile.instance.createFile(tmpPath); + const fileEntry = await CoreFile.createFile(tmpPath); - const transfer = FileTransfer.instance.create(); + const transfer = FileTransfer.create(); onProgress && transfer.onProgress(onProgress); // Download the file in the tmp file. @@ -270,7 +270,7 @@ export class CoreWSProvider { let extension = ''; if (addExtension) { - extension = CoreMimetypeUtils.instance.getFileExtension(path) || ''; + extension = CoreMimetypeUtils.getFileExtension(path) || ''; // Google Drive extensions will be considered invalid since Moodle usually converts them. if (!extension || CoreArray.contains(['gdoc', 'gsheet', 'gslides', 'gdraw', 'php'], extension)) { @@ -278,12 +278,12 @@ export class CoreWSProvider { const mimetype = await this.getRemoteFileMimeType(url); if (mimetype) { - const remoteExtension = CoreMimetypeUtils.instance.getExtension(mimetype, url); + const remoteExtension = CoreMimetypeUtils.getExtension(mimetype, url); // If the file is from Google Drive, ignore mimetype application/json. if (remoteExtension && (!extension || mimetype != 'application/json')) { if (extension) { // Remove existing extension since we will use another one. - path = CoreMimetypeUtils.instance.removeExtension(path); + path = CoreMimetypeUtils.removeExtension(path); } path += '.' + remoteExtension; @@ -294,7 +294,7 @@ export class CoreWSProvider { } // Move the file to the final location. - const movedEntry = await CoreFile.instance.moveFile(tmpPath, path); + const movedEntry = await CoreFile.moveFile(tmpPath, path); this.logger.debug(`Success downloading file ${url} to ${path} with extension ${extension}`); @@ -378,7 +378,7 @@ export class CoreWSProvider { * @return Timeout in ms. */ getRequestTimeout(): number { - return CoreApp.instance.isNetworkAccessLimited() ? CoreConstants.WS_TIMEOUT : CoreConstants.WS_TIMEOUT_WIFI; + return CoreApp.isNetworkAccessLimited() ? CoreConstants.WS_TIMEOUT : CoreConstants.WS_TIMEOUT_WIFI; } /** @@ -410,9 +410,9 @@ export class CoreWSProvider { let promise: Promise>; if (typeof preSets.siteUrl == 'undefined') { - throw new CoreAjaxError(Translate.instance.instant('core.unexpectederror')); - } else if (!CoreApp.instance.isOnline()) { - throw new CoreAjaxError(Translate.instance.instant('core.networkerrormsg')); + throw new CoreAjaxError(Translate.instant('core.unexpectederror')); + } else if (!CoreApp.isOnline()) { + throw new CoreAjaxError(Translate.instant('core.networkerrormsg')); } if (typeof preSets.responseExpected == 'undefined') { @@ -457,7 +457,7 @@ export class CoreWSProvider { // Check if error. Ajax layer should always return an object (if error) or an array (if success). if (!data || typeof data != 'object') { - throw new CoreAjaxError(Translate.instance.instant('core.serverconnection')); + throw new CoreAjaxError(Translate.instant('core.serverconnection')); } else if (data.error) { throw new CoreAjaxWSError(data); } @@ -473,7 +473,7 @@ export class CoreWSProvider { }, (data) => { const available = data.status == 404 ? -1 : 0; - throw new CoreAjaxError(Translate.instance.instant('core.serverconnection'), available); + throw new CoreAjaxError(Translate.instant('core.serverconnection'), available); }); } @@ -592,7 +592,7 @@ export class CoreWSProvider { const requestUrl = siteUrl + '&wsfunction=' + method; // Perform the post request. - const promise = Http.instance.post(requestUrl, ajaxData, options).pipe(timeout(this.getRequestTimeout())).toPromise(); + const promise = Http.post(requestUrl, ajaxData, options).pipe(timeout(this.getRequestTimeout())).toPromise(); // eslint-disable-next-line @typescript-eslint/no-explicit-any return promise.then((data: any) => { @@ -603,7 +603,7 @@ export class CoreWSProvider { } if (!data) { - throw new CoreError(Translate.instance.instant('core.serverconnection')); + throw new CoreError(Translate.instant('core.serverconnection')); } else if (typeof data != preSets.typeExpected) { // If responseType is text an string will be returned, parse before returning. if (typeof data == 'string') { @@ -612,7 +612,7 @@ export class CoreWSProvider { if (isNaN(data)) { this.logger.warn(`Response expected type "${preSets.typeExpected}" cannot be parsed to number`); - throw new CoreError(Translate.instance.instant('core.errorinvalidresponse')); + throw new CoreError(Translate.instant('core.errorinvalidresponse')); } } else if (preSets.typeExpected == 'boolean') { if (data === 'true') { @@ -622,17 +622,17 @@ export class CoreWSProvider { } else { this.logger.warn(`Response expected type "${preSets.typeExpected}" is not true or false`); - throw new CoreError(Translate.instance.instant('core.errorinvalidresponse')); + throw new CoreError(Translate.instant('core.errorinvalidresponse')); } } else { this.logger.warn('Response of type "' + typeof data + `" received, expecting "${preSets.typeExpected}"`); - throw new CoreError(Translate.instance.instant('core.errorinvalidresponse')); + throw new CoreError(Translate.instant('core.errorinvalidresponse')); } } else { this.logger.warn('Response of type "' + typeof data + `" received, expecting "${preSets.typeExpected}"`); - throw new CoreError(Translate.instance.instant('core.errorinvalidresponse')); + throw new CoreError(Translate.instant('core.errorinvalidresponse')); } } @@ -674,7 +674,7 @@ export class CoreWSProvider { return retryPromise; } - throw new CoreError(Translate.instance.instant('core.serverconnection')); + throw new CoreError(Translate.instant('core.serverconnection')); }); } @@ -740,8 +740,8 @@ export class CoreWSProvider { // eslint-disable-next-line @typescript-eslint/no-explicit-any syncCall(method: string, data: any, preSets: CoreWSPreSets): T { if (!preSets) { - throw new CoreError(Translate.instance.instant('core.unexpectederror')); - } else if (!CoreApp.instance.isOnline()) { + throw new CoreError(Translate.instant('core.unexpectederror')); + } else if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } @@ -753,7 +753,7 @@ export class CoreWSProvider { data = this.convertValuesToString(data || {}, preSets.cleanUnicode); if (data == null) { // Empty cleaned text found. - throw new CoreError(Translate.instance.instant('core.unicodenotsupportedcleanerror')); + throw new CoreError(Translate.instant('core.unicodenotsupportedcleanerror')); } data.wsfunction = method; @@ -782,7 +782,7 @@ export class CoreWSProvider { } // Treat response. - data = CoreTextUtils.instance.parseJSON(data); + data = CoreTextUtils.parseJSON(data); // Some moodle web services return null. // If the responseExpected value is set then so long as no data is returned, we create a blank object. @@ -791,10 +791,10 @@ export class CoreWSProvider { } if (!data) { - throw new CoreError(Translate.instance.instant('core.serverconnection')); + throw new CoreError(Translate.instant('core.serverconnection')); } else if (typeof data != preSets.typeExpected) { this.logger.warn('Response of type "' + typeof data + '" received, expecting "' + preSets.typeExpected + '"'); - throw new CoreError(Translate.instance.instant('core.errorinvalidresponse')); + throw new CoreError(Translate.instant('core.errorinvalidresponse')); } if (typeof data.exception != 'undefined' || typeof data.debuginfo != 'undefined') { @@ -825,12 +825,12 @@ export class CoreWSProvider { throw new CoreError('Invalid options passed to upload file.'); } - if (!CoreApp.instance.isOnline()) { + if (!CoreApp.isOnline()) { throw new CoreNetworkError(); } const uploadUrl = preSets.siteUrl + '/webservice/upload.php'; - const transfer = FileTransfer.instance.create(); + const transfer = FileTransfer.create(); onProgress && transfer.onProgress(onProgress); @@ -848,22 +848,22 @@ export class CoreWSProvider { const success = await transfer.upload(filePath, uploadUrl, options, true); // eslint-disable-next-line @typescript-eslint/no-explicit-any - const data = CoreTextUtils.instance.parseJSON( + const data = CoreTextUtils.parseJSON( success.response, null, this.logger.error.bind(this.logger, 'Error parsing response from upload', success.response), ); if (data === null) { - throw new CoreError(Translate.instance.instant('core.errorinvalidresponse')); + throw new CoreError(Translate.instant('core.errorinvalidresponse')); } if (!data) { - throw new CoreError(Translate.instance.instant('core.serverconnection')); + throw new CoreError(Translate.instant('core.serverconnection')); } else if (typeof data != 'object') { this.logger.warn('Upload file: Response of type "' + typeof data + '" received, expecting "object"'); - throw new CoreError(Translate.instance.instant('core.errorinvalidresponse')); + throw new CoreError(Translate.instant('core.errorinvalidresponse')); } if (typeof data.exception !== 'undefined') { @@ -887,7 +887,7 @@ export class CoreWSProvider { } catch (error) { this.logger.error('Error while uploading file', filePath, error); - throw new CoreError(Translate.instance.instant('core.errorinvalidresponse')); + throw new CoreError(Translate.instant('core.errorinvalidresponse')); } } @@ -927,13 +927,13 @@ export class CoreWSProvider { options.responseType = options.responseType || 'json'; options.timeout = typeof options.timeout == 'undefined' ? this.getRequestTimeout() : options.timeout; - if (CoreApp.instance.isMobile()) { + if (CoreApp.isMobile()) { // Use the cordova plugin. if (url.indexOf('file://') === 0) { // We cannot load local files using the http native plugin. Use file provider instead. const content = options.responseType == 'json' ? - await CoreFile.instance.readFile(url, CoreFileFormat.FORMATJSON) : - await CoreFile.instance.readFile(url, CoreFileFormat.FORMATTEXT); + await CoreFile.readFile(url, CoreFileFormat.FORMATJSON) : + await CoreFile.readFile(url, CoreFileFormat.FORMATTEXT); return new HttpResponse({ body: content, @@ -944,7 +944,7 @@ export class CoreWSProvider { }); } - return NativeHttp.instance.sendRequest(url, options).then((response) => new CoreNativeToAngularHttpResponse(response)); + return NativeHttp.sendRequest(url, options).then((response) => new CoreNativeToAngularHttpResponse(response)); } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any let observable: Observable>; @@ -953,7 +953,7 @@ export class CoreWSProvider { // Use Angular's library. switch (angularOptions.method) { case 'get': - observable = Http.instance.get(url, { + observable = Http.get(url, { headers: angularOptions.headers, params: angularOptions.params, observe: 'response', @@ -967,7 +967,7 @@ export class CoreWSProvider { angularOptions.data = JSON.stringify(angularOptions.data); } - observable = Http.instance.post(url, angularOptions.data, { + observable = Http.post(url, angularOptions.data, { headers: angularOptions.headers, observe: 'response', // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -976,7 +976,7 @@ export class CoreWSProvider { break; case 'head': - observable = Http.instance.head(url, { + observable = Http.head(url, { headers: angularOptions.headers, observe: 'response', // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -1014,7 +1014,7 @@ export class CoreWSProvider { } -export class CoreWS extends makeSingleton(CoreWSProvider) {} +export const CoreWS = makeSingleton(CoreWSProvider); /** * File upload options. diff --git a/src/core/singletons/index.ts b/src/core/singletons/index.ts index 616ff6296..7cf4d1e73 100644 --- a/src/core/singletons/index.ts +++ b/src/core/singletons/index.ts @@ -56,23 +56,32 @@ import { Zip as ZipService } from '@ionic-native/zip/ngx'; import { TranslateService } from '@ngx-translate/core'; +const OBJECT_PROTOTYPE = Object.getPrototypeOf(Object); + /** * Injector instance used to resolve singletons. */ let singletonsInjector: Injector | null = null; /** - * Stub class used to type anonymous classes created in the makeSingleton method. + * Helper to get service class methods. */ -class CoreSingleton {} +type GetMethods = { + [K in keyof T]: T[K] extends (...args: unknown[]) => unknown ? K : never; +}[keyof T]; /** - * Singleton class created using the factory. + * Singleton proxy created using the factory method. + * + * @see makeSingleton */ -export type CoreSingletonClass = typeof CoreSingleton & { - instance: Service; - setInstance(instance: Service): void; -}; +export type CoreSingletonProxy = + Pick> & + Pick & + { + instance: Service; + setInstance(instance: Service): void; + }; /** * Set the injector that will be used to resolve instances in the singletons of this module. @@ -84,84 +93,163 @@ export function setSingletonsInjector(injector: Injector): void { } /** - * Make a singleton for the given injection token. + * Make a singleton proxy for the given injection token. * - * @param injectionToken Injection token used to resolve the singleton instance. This is usually the service class if the - * provider was defined using a class or the string used in the `provide` key if it was defined using an object. + * This method will return an object that will proxy method calls to an underlying service instance. Getters will also be proxied, + * but these need to be configured manually using the `getters` argument. Most of the time, this proxy can be used directly like + * you would use a service instance. If you need to get the real service instance, it can be accessed through the `instance` + * property and it can be set with the `setInstance` method. + * + * @param injectionToken Injection token used to resolve the service. This is usually the service class if the provider was + * defined using a class or the string used in the `provide` key if it was defined using an object. + * @param getters Getter names to proxy. + * @return Singleton proxy. */ -export function makeSingleton(injectionToken: Type | Type | string): CoreSingletonClass { - return class { +export function makeSingleton(injectionToken: Type | Type | string): CoreSingletonProxy; +export function makeSingleton( + injectionToken: Type | Type | string, + getters: Getters[], +): CoreSingletonProxy; +export function makeSingleton( + injectionToken: Type | Type | string, + getters: Getters[] = [], +): CoreSingletonProxy { + // Define instance manipulation affordances. + const proxy = { + setInstance(instance: Service) { + Object.defineProperty(proxy, 'instance', { + value: instance, + configurable: true, + }); + }, + } as CoreSingletonProxy; - private static serviceInstance: Service; - - static get instance(): Service { - // Initialize instances lazily. - if (!this.serviceInstance) { - if (!singletonsInjector) { - throw new Error('Can\'t resolve a singleton instance without an injector'); - } - - this.serviceInstance = singletonsInjector.get(injectionToken); + Object.defineProperty(proxy, 'instance', { + get: () => { + if (!singletonsInjector) { + throw new Error('Can\'t resolve a singleton instance without an injector'); } - return this.serviceInstance; + const instance = singletonsInjector.get(injectionToken); + + proxy.setInstance(instance); + + return instance; + }, + configurable: true, + }); + + // Define method and getter proxies. + if (isServiceClass(injectionToken)) { + // Get property descriptors, going all the way up the prototype chain (for services extending other classes). + let parentPrototype = injectionToken; + let descriptors: Record = {}; + + do { + descriptors = { + ...Object.getOwnPropertyDescriptors(parentPrototype.prototype), + ...descriptors, + }; + + parentPrototype = Object.getPrototypeOf(parentPrototype); + } while (parentPrototype !== OBJECT_PROTOTYPE); + + // Don't proxy constructor calls. + delete descriptors['constructor']; + + // Define method proxies. + for (const [property, descriptor] of Object.entries(descriptors)) { + // Skip getters and setters. + if (descriptor.get || descriptor.set) { + continue; + } + + // Define method proxy. + Object.defineProperty(proxy, property, { + value: (...args) => proxy.instance[property].call(proxy.instance, ...args), + configurable: true, + }); } - static setInstance(instance: Service): void { - this.serviceInstance = instance; + // Define getter proxies. + for (const getter of getters) { + Object.defineProperty(proxy, getter, { get: () => proxy.instance[getter] }); } + } - }; + return proxy; +} + +/** + * Type guard to check if an injection token is a service class. + * + * @param injectionToken Injection token. + * @return Whether the token is a class. + */ +function isServiceClass(injectionToken: Type | string): injectionToken is Type { + return typeof injectionToken !== 'string'; } // Convert ionic-native services to singleton. -export class Badge extends makeSingleton(BadgeService) {} -export class Camera extends makeSingleton(CameraService) {} -export class Chooser extends makeSingleton(ChooserService) {} -export class Clipboard extends makeSingleton(ClipboardService) {} -export class Device extends makeSingleton(DeviceService) {} -export class Diagnostic extends makeSingleton(DiagnosticService) {} -export class File extends makeSingleton(FileService) {} -export class FileOpener extends makeSingleton(FileOpenerService) {} -export class FileTransfer extends makeSingleton(FileTransferService) {} -export class Geolocation extends makeSingleton(GeolocationService) {} -export class InAppBrowser extends makeSingleton(InAppBrowserService) {} -export class Keyboard extends makeSingleton(KeyboardService) {} -export class LocalNotifications extends makeSingleton(LocalNotificationsService) {} -export class Media extends makeSingleton(MediaService) {} -export class MediaCapture extends makeSingleton(MediaCaptureService) {} -export class NativeHttp extends makeSingleton(HTTP) {} -export class Network extends makeSingleton(NetworkService) {} -export class Push extends makeSingleton(PushService) {} -export class QRScanner extends makeSingleton(QRScannerService) {} -export class StatusBar extends makeSingleton(StatusBarService) {} -export class SplashScreen extends makeSingleton(SplashScreenService) {} -export class SQLite extends makeSingleton(SQLiteService) {} -export class WebIntent extends makeSingleton(WebIntentService) {} -export class WebView extends makeSingleton(WebViewService) {} -export class Zip extends makeSingleton(ZipService) {} +export const Badge = makeSingleton(BadgeService); +export const Chooser = makeSingleton(ChooserService); +export const Clipboard = makeSingleton(ClipboardService); +export const Diagnostic = makeSingleton(DiagnosticService, ['permissionStatus']); +export const File = makeSingleton(FileService, ['documentsDirectory', 'externalApplicationStorageDirectory']); +export const FileOpener = makeSingleton(FileOpenerService); +export const FileTransfer = makeSingleton(FileTransferService); +export const Geolocation = makeSingleton(GeolocationService); +export const InAppBrowser = makeSingleton(InAppBrowserService); +export const Keyboard = makeSingleton(KeyboardService); +export const LocalNotifications = makeSingleton(LocalNotificationsService); +export const Media = makeSingleton(MediaService); +export const MediaCapture = makeSingleton(MediaCaptureService); +export const NativeHttp = makeSingleton(HTTP); +export const Network = makeSingleton(NetworkService, ['Connection', 'type']); +export const Push = makeSingleton(PushService); +export const QRScanner = makeSingleton(QRScannerService); +export const StatusBar = makeSingleton(StatusBarService); +export const SplashScreen = makeSingleton(SplashScreenService); +export const SQLite = makeSingleton(SQLiteService); +export const WebIntent = makeSingleton(WebIntentService, ['ACTION_VIEW']); +export const WebView = makeSingleton(WebViewService); +export const Zip = makeSingleton(ZipService); + +export const Camera = makeSingleton(CameraService, [ + 'DestinationType', + 'Direction', + 'EncodingType', + 'MediaType', + 'PictureSourceType', + 'PopoverArrowDirection', +]); + +export const Device = makeSingleton(DeviceService, [ + 'cordova', + 'isVirtual', + 'manufacturer', + 'model', + 'platform', + 'serial', + 'uuid', + 'version', +]); // Convert some Angular and Ionic injectables to singletons. -export class NgZone extends makeSingleton(NgZoneService) {} -export class Http extends makeSingleton(HttpClient) {} -export class Platform extends makeSingleton(PlatformService) {} -export class ActionSheetController extends makeSingleton(ActionSheetControllerService) {} -export class AlertController extends makeSingleton(AlertControllerService) {} -export class LoadingController extends makeSingleton(LoadingControllerService) {} -export class ModalController extends makeSingleton(ModalControllerService) {} -export class PopoverController extends makeSingleton(PopoverControllerService) {} -export class ToastController extends makeSingleton(ToastControllerService) {} -export class GestureController extends makeSingleton(GestureControllerService) {} -export class ApplicationInit extends makeSingleton(ApplicationInitStatus) {} -export class Application extends makeSingleton(ApplicationRef) {} -export class NavController extends makeSingleton(NavControllerService) {} -export class Router extends makeSingleton(RouterService) {} +export const NgZone = makeSingleton(NgZoneService); +export const Http = makeSingleton(HttpClient); +export const Platform = makeSingleton(PlatformService, ['isRTL', 'resume']); +export const ActionSheetController = makeSingleton(ActionSheetControllerService); +export const AlertController = makeSingleton(AlertControllerService); +export const LoadingController = makeSingleton(LoadingControllerService); +export const ModalController = makeSingleton(ModalControllerService); +export const PopoverController = makeSingleton(PopoverControllerService); +export const ToastController = makeSingleton(ToastControllerService); +export const GestureController = makeSingleton(GestureControllerService); +export const ApplicationInit = makeSingleton(ApplicationInitStatus, ['donePromise']); +export const Application = makeSingleton(ApplicationRef); +export const NavController = makeSingleton(NavControllerService); +export const Router = makeSingleton(RouterService, ['routerState', 'url']); // Convert external libraries injectables. -export class Translate extends makeSingleton(TranslateService) { - - static instant(key: string | Array, interpolateParams?: Record): string | any { - return this.instance.instant(key, interpolateParams); - } - -} +export const Translate = makeSingleton(TranslateService, ['onLangChange']); diff --git a/src/core/singletons/object.ts b/src/core/singletons/object.ts index 589c8b834..8f6bf1fa3 100644 --- a/src/core/singletons/object.ts +++ b/src/core/singletons/object.ts @@ -38,7 +38,7 @@ export class CoreObject { * @param keys Keys to remove from the new object. * @return New object without the specified keys. */ - static without(obj: T, keys: K[]): Omit { + static without(obj: T, keys: K[]): Omit { const newObject: T = { ...obj }; for (const key of keys) { diff --git a/src/core/singletons/tests/singletons.test.ts b/src/core/singletons/tests/singletons.test.ts new file mode 100644 index 000000000..412a4fe8d --- /dev/null +++ b/src/core/singletons/tests/singletons.test.ts @@ -0,0 +1,53 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { mock } from '@/testing/utils'; +import { CoreSingletonProxy, makeSingleton, setSingletonsInjector } from '@singletons'; + +import { MilkyWayService } from './stubs'; + +describe('Singletons', () => { + + let MilkyWay: CoreSingletonProxy; + + beforeEach(() => { + setSingletonsInjector(mock({ get: serviceClass => new serviceClass() })); + + MilkyWay = makeSingleton(MilkyWayService, ['MEANING_OF_LIFE']); + }); + + it('works using the service instance', () => { + expect(MilkyWay.instance.getTheMeaningOfLife()).toBe(42); + }); + + it('works using magic methods', () => { + expect(MilkyWay.getTheMeaningOfLife()).toBe(42); + }); + + it('works using magic getters', () => { + expect(MilkyWay.MEANING_OF_LIFE).toBe(42); + }); + + it('magic getters use the same instance', () => { + expect(MilkyWay.addYears(1)).toBe(1); + expect(MilkyWay.instance.addYears(1)).toBe(2); + expect(MilkyWay.addYears(1)).toBe(3); + expect(MilkyWay.instance.addYears(2)).toBe(5); + }); + + it('magic methods respect inheritance', () => { + expect(MilkyWay.isGalaxy()).toBe(true); + }); + +}); diff --git a/src/core/singletons/tests/stubs.ts b/src/core/singletons/tests/stubs.ts new file mode 100644 index 000000000..7850cf6cd --- /dev/null +++ b/src/core/singletons/tests/stubs.ts @@ -0,0 +1,39 @@ +// (C) Copyright 2015 Moodle Pty Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +export class Galaxy { + + isGalaxy(): boolean { + return true; + } + +} + +export class MilkyWayService extends Galaxy { + + readonly MEANING_OF_LIFE = 42; + + private years = 0; + + getTheMeaningOfLife(): number { + return this.MEANING_OF_LIFE; + } + + addYears(years: number): number { + this.years += years; + + return this.years; + } + +} diff --git a/src/core/singletons/url.ts b/src/core/singletons/url.ts index 3cb945572..2f38ffbe5 100644 --- a/src/core/singletons/url.ts +++ b/src/core/singletons/url.ts @@ -197,7 +197,7 @@ export class CoreUrl { const partsB = CoreUrl.parse(urlB); return partsA?.domain == partsB?.domain && - CoreTextUtils.instance.removeEndingSlash(partsA?.path) == CoreTextUtils.instance.removeEndingSlash(partsB?.path); + CoreTextUtils.removeEndingSlash(partsA?.path) == CoreTextUtils.removeEndingSlash(partsB?.path); } } diff --git a/src/core/singletons/window.ts b/src/core/singletons/window.ts index 6932347a8..f04b6956d 100644 --- a/src/core/singletons/window.ts +++ b/src/core/singletons/window.ts @@ -52,34 +52,34 @@ export class CoreWindow { * @return Promise resolved when done. */ static async open(url: string, name?: string): Promise { - if (CoreUrlUtils.instance.isLocalFileUrl(url)) { + if (CoreUrlUtils.isLocalFileUrl(url)) { const filename = url.substr(url.lastIndexOf('/') + 1); - if (!CoreFileHelper.instance.isOpenableInApp({ filename })) { + if (!CoreFileHelper.isOpenableInApp({ filename })) { try { - await CoreFileHelper.instance.showConfirmOpenUnsupportedFile(); + await CoreFileHelper.showConfirmOpenUnsupportedFile(); } catch (error) { return; // Cancelled, stop. } } - await CoreUtils.instance.openFile(url); + await CoreUtils.openFile(url); } else { let treated = false; if (name != '_system') { // Check if it can be opened in the app. treated = false; - await CoreContentLinksHelper.instance.handleLink(url, undefined, true, true); + await CoreContentLinksHelper.handleLink(url, undefined, true, true); } if (!treated) { // Not opened in the app, open with browser. Check if we need to auto-login - if (!CoreSites.instance.isLoggedIn()) { + if (!CoreSites.isLoggedIn()) { // Not logged in, cannot auto-login. - CoreUtils.instance.openInBrowser(url); + CoreUtils.openInBrowser(url); } else { - await CoreSites.instance.getCurrentSite()!.openInBrowserWithAutoLoginIfSameSite(url); + await CoreSites.getCurrentSite()!.openInBrowserWithAutoLoginIfSameSite(url); } } } diff --git a/src/testing/utils.ts b/src/testing/utils.ts index ab2425723..d27ef231c 100644 --- a/src/testing/utils.ts +++ b/src/testing/utils.ts @@ -15,7 +15,7 @@ import { Component, CUSTOM_ELEMENTS_SCHEMA, Type, ViewChild } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { CoreSingletonClass } from '@singletons'; +import { CoreSingletonProxy } from '@singletons'; abstract class WrapperComponent { @@ -47,15 +47,15 @@ export function mock( return instance as T; } -export function mockSingleton(singletonClass: CoreSingletonClass, instance: T): T; -export function mockSingleton(singletonClass: CoreSingletonClass, instance?: Record): T; +export function mockSingleton(singletonClass: CoreSingletonProxy, instance: T): T; +export function mockSingleton(singletonClass: CoreSingletonProxy, instance?: Record): T; export function mockSingleton( - singletonClass: CoreSingletonClass, + singletonClass: CoreSingletonProxy, methods: string[], instance?: Record, ): T; export function mockSingleton( - singletonClass: CoreSingletonClass, + singleton: CoreSingletonProxy, methodsOrInstance: string[] | Record = [], instance: Record = {}, ): T { @@ -64,7 +64,18 @@ export function mockSingleton( const methods = Array.isArray(methodsOrInstance) ? methodsOrInstance : []; const mockInstance = mock(methods, instance); - singletonClass.setInstance(mockInstance); + singleton.setInstance(mockInstance); + + for (const [property, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(singleton))) { + if (typeof descriptor.value !== 'function' || property === 'setInstance') { + continue; + } + + Object.defineProperty(singleton, property, { + value: jest.fn(descriptor.value), + configurable: true, + }); + } return mockInstance; }