Merge pull request #2686 from NoelDeMartin/MOBILE-3320

Mobile 3320
main
Dani Palou 2021-03-03 10:04:01 +01:00 committed by GitHub
commit 95b6456388
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
686 changed files with 7553 additions and 7352 deletions

View File

@ -48,8 +48,8 @@ const tabletRoutes: Routes = [
]; ];
const routes: Routes = [ const routes: Routes = [
...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile),
...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet),
]; ];
@NgModule({ @NgModule({

View File

@ -41,10 +41,10 @@ const mainMenuRoutes: Routes = [
multi: true, multi: true,
deps: [], deps: [],
useFactory: () => () => { useFactory: () => () => {
CoreContentLinksDelegate.instance.registerHandler(AddonBadgesMyBadgesLinkHandler.instance); CoreContentLinksDelegate.registerHandler(AddonBadgesMyBadgesLinkHandler.instance);
CoreContentLinksDelegate.instance.registerHandler(AddonBadgesBadgeLinkHandler.instance); CoreContentLinksDelegate.registerHandler(AddonBadgesBadgeLinkHandler.instance);
CoreUserDelegate.instance.registerHandler(AddonBadgesUserHandler.instance); CoreUserDelegate.registerHandler(AddonBadgesUserHandler.instance);
CorePushNotificationsDelegate.instance.registerClickHandler(AddonBadgesPushClickHandler.instance); CorePushNotificationsDelegate.registerClickHandler(AddonBadgesPushClickHandler.instance);
}, },
}, },
], ],

View File

@ -54,9 +54,9 @@ export class AddonBadgesIssuedBadgePage implements OnInit {
this.route.queryParams.subscribe(() => { this.route.queryParams.subscribe(() => {
this.badgeLoaded = false; this.badgeLoaded = false;
this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || this.courseId; // Use 0 for site badges. this.courseId = CoreNavigator.getRouteNumberParam('courseId') || this.courseId; // Use 0 for site badges.
this.userId = CoreNavigator.instance.getRouteNumberParam('userId') || CoreSites.instance.getCurrentSite()!.getUserId(); this.userId = CoreNavigator.getRouteNumberParam('userId') || CoreSites.getCurrentSite()!.getUserId();
this.badgeHash = CoreNavigator.instance.getRouteParam('badgeHash') || ''; this.badgeHash = CoreNavigator.getRouteParam('badgeHash') || '';
this.fetchIssuedBadge().finally(() => { this.fetchIssuedBadge().finally(() => {
this.badgeLoaded = true; this.badgeLoaded = true;
@ -70,12 +70,12 @@ export class AddonBadgesIssuedBadgePage implements OnInit {
* @return Promise resolved when done. * @return Promise resolved when done.
*/ */
async fetchIssuedBadge(): Promise<void> { async fetchIssuedBadge(): Promise<void> {
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 { 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); const badge = badges.find((badge) => this.badgeHash == badge.uniquehash);
if (!badge) { if (!badge) {
@ -85,14 +85,14 @@ export class AddonBadgesIssuedBadgePage implements OnInit {
this.badge = badge; this.badge = badge;
if (badge.courseid) { if (badge.courseid) {
try { try {
this.course = await CoreCourses.instance.getUserCourse(badge.courseid, true); this.course = await CoreCourses.getUserCourse(badge.courseid, true);
} catch { } catch {
// Maybe an old deleted course. // Maybe an old deleted course.
this.course = undefined; this.course = undefined;
} }
} }
} catch (message) { } 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. * @param refresher Refresher.
*/ */
async refreshBadges(refresher?: CustomEvent<IonRefresher>): Promise<void> { async refreshBadges(refresher?: CustomEvent<IonRefresher>): Promise<void> {
await CoreUtils.instance.ignoreErrors(Promise.all([ await CoreUtils.ignoreErrors(Promise.all([
AddonBadges.instance.invalidateUserBadges(this.courseId, this.userId), AddonBadges.invalidateUserBadges(this.courseId, this.userId),
])); ]));
await CoreUtils.instance.ignoreErrors(Promise.all([ await CoreUtils.ignoreErrors(Promise.all([
this.fetchIssuedBadge(), this.fetchIssuedBadge(),
])); ]));

View File

@ -40,7 +40,7 @@ export class AddonBadgesUserBadgesPage implements AfterViewInit, OnDestroy {
constructor(route: ActivatedRoute) { constructor(route: ActivatedRoute) {
const courseId = parseInt(route.snapshot.queryParams.courseId ?? 0); // Use 0 for site badges. 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); this.badges = new AddonBadgesUserBadgesManager(AddonBadgesUserBadgesPage, courseId, userId);
} }
@ -67,8 +67,8 @@ export class AddonBadgesUserBadgesPage implements AfterViewInit, OnDestroy {
* @param refresher Refresher. * @param refresher Refresher.
*/ */
async refreshBadges(refresher?: IonRefresher): Promise<void> { async refreshBadges(refresher?: IonRefresher): Promise<void> {
await CoreUtils.instance.ignoreErrors(AddonBadges.instance.invalidateUserBadges(this.badges.courseId, this.badges.userId)); await CoreUtils.ignoreErrors(AddonBadges.invalidateUserBadges(this.badges.courseId, this.badges.userId));
await CoreUtils.instance.ignoreErrors(this.fetchBadges()); await CoreUtils.ignoreErrors(this.fetchBadges());
refresher?.complete(); refresher?.complete();
} }
@ -77,12 +77,12 @@ export class AddonBadgesUserBadgesPage implements AfterViewInit, OnDestroy {
* Obtain the initial list of badges. * Obtain the initial list of badges.
*/ */
private async fetchInitialBadges(): Promise<void> { private async fetchInitialBadges(): Promise<void> {
this.currentTime = CoreTimeUtils.instance.timestamp(); this.currentTime = CoreTimeUtils.timestamp();
try { try {
await this.fetchBadges(); await this.fetchBadges();
} catch (message) { } catch (message) {
CoreDomUtils.instance.showErrorModalDefault(message, 'Error loading badges'); CoreDomUtils.showErrorModalDefault(message, 'Error loading badges');
this.badges.setItems([]); this.badges.setItems([]);
} }
@ -92,7 +92,7 @@ export class AddonBadgesUserBadgesPage implements AfterViewInit, OnDestroy {
* Update the list of badges. * Update the list of badges.
*/ */
private async fetchBadges(): Promise<void> { private async fetchBadges(): Promise<void> {
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); this.badges.setItems(badges);
} }

View File

@ -37,7 +37,7 @@ export class AddonBadgesProvider {
* @return Promise resolved with true if enabled, false otherwise. * @return Promise resolved with true if enabled, false otherwise.
*/ */
async isPluginEnabled(siteId?: string): Promise<boolean> { async isPluginEnabled(siteId?: string): Promise<boolean> {
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'); 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<AddonBadgesUserBadge[]> { async getUserBadges(courseId: number, userId: number, siteId?: string): Promise<AddonBadgesUserBadge[]> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const data: AddonBadgesGetUserBadgesWSParams = { const data: AddonBadgesGetUserBadgesWSParams = {
courseid: courseId, courseid: courseId,
userid: userId, userid: userId,
@ -101,14 +101,14 @@ export class AddonBadgesProvider {
* @return Promise resolved when data is invalidated. * @return Promise resolved when data is invalidated.
*/ */
async invalidateUserBadges(courseId: number, userId: number, siteId?: string): Promise<void> { async invalidateUserBadges(courseId: number, userId: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getBadgesCacheKey(courseId, userId)); 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. * Params of core_badges_get_user_badges WS.

View File

@ -43,7 +43,7 @@ export class AddonBadgesBadgeLinkHandlerService extends CoreContentLinksHandlerB
return [{ return [{
action: (siteId: string): void => { 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. * @return Whether the handler is enabled for the URL and site.
*/ */
isEnabled(siteId: string): Promise<boolean> { isEnabled(siteId: string): Promise<boolean> {
return AddonBadges.instance.isPluginEnabled(siteId); return AddonBadges.isPluginEnabled(siteId);
} }
} }
export class AddonBadgesBadgeLinkHandler extends makeSingleton(AddonBadgesBadgeLinkHandlerService) {} export const AddonBadgesBadgeLinkHandler = makeSingleton(AddonBadgesBadgeLinkHandlerService);

View File

@ -37,7 +37,7 @@ export class AddonBadgesMyBadgesLinkHandlerService extends CoreContentLinksHandl
getActions(): CoreContentLinksAction[] { getActions(): CoreContentLinksAction[] {
return [{ return [{
action: (siteId: string): void => { 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. * @return Whether the handler is enabled for the URL and site.
*/ */
async isEnabled(siteId: string): Promise<boolean> { async isEnabled(siteId: string): Promise<boolean> {
return AddonBadges.instance.isPluginEnabled(siteId); return AddonBadges.isPluginEnabled(siteId);
} }
} }
export class AddonBadgesMyBadgesLinkHandler extends makeSingleton(AddonBadgesMyBadgesLinkHandlerService) {} export const AddonBadgesMyBadgesLinkHandler = makeSingleton(AddonBadgesMyBadgesLinkHandlerService);

View File

@ -40,9 +40,9 @@ export class AddonBadgesPushClickHandlerService implements CorePushNotifications
async handles(notification: CorePushNotificationsNotificationBasicData): Promise<boolean> { async handles(notification: CorePushNotificationsNotificationBasicData): Promise<boolean> {
const data = notification.customdata || {}; 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))) { (notification.name == 'badgerecipientnotice' || (notification.name == 'badgecreatornotice' && data.hash))) {
return AddonBadges.instance.isPluginEnabled(notification.site); return AddonBadges.isPluginEnabled(notification.site);
} }
return false; return false;
@ -59,7 +59,7 @@ export class AddonBadgesPushClickHandlerService implements CorePushNotifications
if (data.hash) { if (data.hash) {
// We have the hash, open the badge directly. // We have the hash, open the badge directly.
await CoreNavigator.instance.navigateToSitePath(`/badges/${data.hash}`, { await CoreNavigator.navigateToSitePath(`/badges/${data.hash}`, {
siteId: notification.site, siteId: notification.site,
}); });
@ -67,17 +67,17 @@ export class AddonBadgesPushClickHandlerService implements CorePushNotifications
} }
// No hash, open the list of user badges. // No hash, open the list of user badges.
await CoreUtils.instance.ignoreErrors( await CoreUtils.ignoreErrors(
AddonBadges.instance.invalidateUserBadges( AddonBadges.invalidateUserBadges(
0, 0,
Number(notification.usertoid), Number(notification.usertoid),
notification.site, 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);

View File

@ -37,7 +37,7 @@ export class AddonBadgesUserHandlerService implements CoreUserProfileHandler {
* @return Always enabled. * @return Always enabled.
*/ */
isEnabled(): Promise<boolean> { isEnabled(): Promise<boolean> {
return AddonBadges.instance.isPluginEnabled(); return AddonBadges.isPluginEnabled();
} }
/** /**
@ -73,7 +73,7 @@ export class AddonBadgesUserHandlerService implements CoreUserProfileHandler {
action: (event, user, courseId): void => { action: (event, user, courseId): void => {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
CoreNavigator.instance.navigateToSitePath('/badges', { CoreNavigator.navigateToSitePath('/badges', {
params: CoreObject.withoutEmpty({ courseId, userId: user.id }), 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);

View File

@ -30,7 +30,7 @@ import { AddonBlockActivityModulesComponentsModule } from './components/componen
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockActivityModulesHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockActivityModulesHandler.instance);
}, },
}, },
], ],

View File

@ -45,7 +45,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i
* @return Resolved when done. * @return Resolved when done.
*/ */
protected async invalidateContent(): Promise<void> { protected async invalidateContent(): Promise<void> {
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. * @return Promise resolved when done.
*/ */
protected async fetchContent(): Promise<void> { protected async fetchContent(): Promise<void> {
const sections = await CoreCourse.instance.getSections(this.getCourseId(), false, true); const sections = await CoreCourse.getSections(this.getCourseId(), false, true);
this.entries = []; this.entries = [];
const archetypes: Record<string, number> = {}; const archetypes: Record<string, number> = {};
@ -66,7 +66,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i
} }
section.modules.forEach((mod) => { section.modules.forEach((mod) => {
if (mod.uservisible === false || !CoreCourse.instance.moduleHasView(mod) || if (mod.uservisible === false || !CoreCourse.moduleHasView(mod) ||
typeof modFullNames[mod.modname] != 'undefined') { typeof modFullNames[mod.modname] != 'undefined') {
// Ignore this module. // Ignore this module.
return; return;
@ -74,7 +74,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i
// Get the archetype of the module type. // Get the archetype of the module type.
if (typeof archetypes[mod.modname] == 'undefined') { if (typeof archetypes[mod.modname] == 'undefined') {
archetypes[mod.modname] = CoreCourseModuleDelegate.instance.supportsFeature<number>( archetypes[mod.modname] = CoreCourseModuleDelegate.supportsFeature<number>(
mod.modname, mod.modname,
CoreConstants.FEATURE_MOD_ARCHETYPE, CoreConstants.FEATURE_MOD_ARCHETYPE,
CoreConstants.MOD_ARCHETYPE_OTHER, CoreConstants.MOD_ARCHETYPE_OTHER,
@ -85,7 +85,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i
if (archetypes[mod.modname] == CoreConstants.MOD_ARCHETYPE_RESOURCE) { if (archetypes[mod.modname] == CoreConstants.MOD_ARCHETYPE_RESOURCE) {
// All resources are gathered in a single "Resources" option. // All resources are gathered in a single "Resources" option.
if (!modFullNames['resources']) { if (!modFullNames['resources']) {
modFullNames['resources'] = Translate.instance.instant('core.resources'); modFullNames['resources'] = Translate.instant('core.resources');
} }
} else { } else {
modFullNames[mod.modname] = mod.modplural; modFullNames[mod.modname] = mod.modplural;
@ -94,14 +94,14 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i
}); });
}); });
// Sort the modnames alphabetically. // Sort the modnames alphabetically.
modFullNames = CoreUtils.instance.sortValues(modFullNames); modFullNames = CoreUtils.sortValues(modFullNames);
for (const modName in modFullNames) { for (const modName in modFullNames) {
let icon: string; let icon: string;
if (modName === 'resources') { if (modName === 'resources') {
icon = CoreCourse.instance.getModuleIconSrc('page', modIcons['page']); icon = CoreCourse.getModuleIconSrc('page', modIcons['page']);
} else { } else {
icon = CoreCourseModuleDelegate.instance.getModuleIconSrc(modName, modIcons[modName]); icon = CoreCourseModuleDelegate.getModuleIconSrc(modName, modIcons[modName]);
} }
this.entries.push({ this.entries.push({
@ -122,7 +122,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i
return this.instanceId; return this.instanceId;
} }
return CoreSites.instance.getCurrentSiteHomeId(); return CoreSites.getCurrentSiteHomeId();
} }
/** /**
@ -131,7 +131,7 @@ export class AddonBlockActivityModulesComponent extends CoreBlockBaseComponent i
* @param entry Selected entry. * @param entry Selected entry.
*/ */
gotoCoureListModType(entry: AddonBlockActivityModuleEntry): void { gotoCoureListModType(entry: AddonBlockActivityModuleEntry): void {
CoreNavigator.instance.navigateToSitePath('course/list-mod-type', { CoreNavigator.navigateToSitePath('course/list-mod-type', {
params: { params: {
courseId: this.getCourseId(), courseId: this.getCourseId(),
modName: entry.modName, modName: entry.modName,

View File

@ -43,4 +43,4 @@ export class AddonBlockActivityModulesHandlerService extends CoreBlockBaseHandle
} }
export class AddonBlockActivityModulesHandler extends makeSingleton(AddonBlockActivityModulesHandlerService) {} export const AddonBlockActivityModulesHandler = makeSingleton(AddonBlockActivityModulesHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockActivityResultsComponentsModule } from './components/componen
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockActivityResultsHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockActivityResultsHandler.instance);
}, },
}, },
], ],

View File

@ -44,4 +44,4 @@ export class AddonBlockActivityResultsHandlerService extends CoreBlockBaseHandle
} }
export class AddonBlockActivityResultsHandler extends makeSingleton(AddonBlockActivityResultsHandlerService) {} export const AddonBlockActivityResultsHandler = makeSingleton(AddonBlockActivityResultsHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockBadgesComponentsModule } from './components/components.module
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockBadgesHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockBadgesHandler.instance);
}, },
}, },
], ],

View File

@ -44,4 +44,4 @@ export class AddonBlockBadgesHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockBadgesHandler extends makeSingleton(AddonBlockBadgesHandlerService) {} export const AddonBlockBadgesHandler = makeSingleton(AddonBlockBadgesHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockBlogMenuComponentsModule } from './components/components.modu
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockBlogMenuHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockBlogMenuHandler.instance);
}, },
}, },
], ],

View File

@ -44,4 +44,4 @@ export class AddonBlockBlogMenuHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockBlogMenuHandler extends makeSingleton(AddonBlockBlogMenuHandlerService) {} export const AddonBlockBlogMenuHandler = makeSingleton(AddonBlockBlogMenuHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockBlogRecentComponentsModule } from './components/components.mo
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockBlogRecentHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockBlogRecentHandler.instance);
}, },
}, },
], ],

View File

@ -44,4 +44,4 @@ export class AddonBlockBlogRecentHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockBlogRecentHandler extends makeSingleton(AddonBlockBlogRecentHandlerService) {} export const AddonBlockBlogRecentHandler = makeSingleton(AddonBlockBlogRecentHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockBlogTagsComponentsModule } from './components/components.modu
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockBlogTagsHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockBlogTagsHandler.instance);
}, },
}, },
], ],

View File

@ -44,4 +44,4 @@ export class AddonBlockBlogTagsHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockBlogTagsHandler extends makeSingleton(AddonBlockBlogTagsHandlerService) {} export const AddonBlockBlogTagsHandler = makeSingleton(AddonBlockBlogTagsHandlerService);

View File

@ -28,7 +28,7 @@ import { AddonBlockCalendarMonthHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockCalendarMonthHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockCalendarMonthHandler.instance);
}, },
}, },
], ],

View File

@ -45,11 +45,11 @@ export class AddonBlockCalendarMonthHandlerService extends CoreBlockBaseHandler
title: 'addon.block_calendarmonth.pluginname', title: 'addon.block_calendarmonth.pluginname',
class: 'addon-block-calendar-month', class: 'addon-block-calendar-month',
component: CoreBlockOnlyTitleComponent, component: CoreBlockOnlyTitleComponent,
link: AddonCalendar.instance.getMainCalendarPagePath(), link: AddonCalendar.getMainCalendarPagePath(),
linkParams: linkParams, linkParams: linkParams,
}; };
} }
} }
export class AddonBlockCalendarMonthHandler extends makeSingleton(AddonBlockCalendarMonthHandlerService) {} export const AddonBlockCalendarMonthHandler = makeSingleton(AddonBlockCalendarMonthHandlerService);

View File

@ -28,7 +28,7 @@ import { AddonBlockCalendarUpcomingHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockCalendarUpcomingHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockCalendarUpcomingHandler.instance);
}, },
}, },
], ],

View File

@ -45,11 +45,11 @@ export class AddonBlockCalendarUpcomingHandlerService extends CoreBlockBaseHandl
title: 'addon.block_calendarupcoming.pluginname', title: 'addon.block_calendarupcoming.pluginname',
class: 'addon-block-calendar-upcoming', class: 'addon-block-calendar-upcoming',
component: CoreBlockOnlyTitleComponent, component: CoreBlockOnlyTitleComponent,
link: AddonCalendar.instance.getMainCalendarPagePath(), link: AddonCalendar.getMainCalendarPagePath(),
linkParams: linkParams, linkParams: linkParams,
}; };
} }
} }
export class AddonBlockCalendarUpcomingHandler extends makeSingleton(AddonBlockCalendarUpcomingHandlerService) {} export const AddonBlockCalendarUpcomingHandler = makeSingleton(AddonBlockCalendarUpcomingHandlerService);

View File

@ -28,7 +28,7 @@ import { AddonBlockCommentsHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockCommentsHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockCommentsHandler.instance);
}, },
}, },
], ],

View File

@ -50,4 +50,4 @@ export class AddonBlockCommentsHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockCommentsHandler extends makeSingleton(AddonBlockCommentsHandlerService) {} export const AddonBlockCommentsHandler = makeSingleton(AddonBlockCommentsHandlerService);

View File

@ -28,7 +28,7 @@ import { AddonBlockCompletionStatusHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockCompletionStatusHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockCompletionStatusHandler.instance);
}, },
}, },
], ],

View File

@ -52,4 +52,4 @@ export class AddonBlockCompletionStatusHandlerService extends CoreBlockBaseHandl
} }
export class AddonBlockCompletionStatusHandler extends makeSingleton(AddonBlockCompletionStatusHandlerService) {} export const AddonBlockCompletionStatusHandler = makeSingleton(AddonBlockCompletionStatusHandlerService);

View File

@ -28,7 +28,7 @@ import { AddonBlockGlossaryRandomHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockGlossaryRandomHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockGlossaryRandomHandler.instance);
}, },
}, },
], ],

View File

@ -45,4 +45,4 @@ export class AddonBlockGlossaryRandomHandlerService extends CoreBlockBaseHandler
} }
export class AddonBlockGlossaryRandomHandler extends makeSingleton(AddonBlockGlossaryRandomHandlerService) {} export const AddonBlockGlossaryRandomHandler = makeSingleton(AddonBlockGlossaryRandomHandlerService);

View File

@ -22,7 +22,7 @@ import { AddonBlockHtmlHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockHtmlHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockHtmlHandler.instance);
}, },
}, },
], ],

View File

@ -46,4 +46,4 @@ export class AddonBlockHtmlHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockHtmlHandler extends makeSingleton(AddonBlockHtmlHandlerService) {} export const AddonBlockHtmlHandler = makeSingleton(AddonBlockHtmlHandlerService);

View File

@ -30,7 +30,7 @@ import { CoreBlockComponentsModule } from '@features/block/components/components
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockLearningPlansHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockLearningPlansHandler.instance);
}, },
}, },
], ],

View File

@ -45,4 +45,4 @@ export class AddonBlockLearningPlansHandlerService extends CoreBlockBaseHandler
} }
export class AddonBlockLearningPlansHandler extends makeSingleton(AddonBlockLearningPlansHandlerService) {} export const AddonBlockLearningPlansHandler = makeSingleton(AddonBlockLearningPlansHandlerService);

View File

@ -148,15 +148,15 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
*/ */
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
// Refresh the enabled flags if enabled. // Refresh the enabled flags if enabled.
this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite();
this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite();
// Refresh the enabled flags if site is updated. // Refresh the enabled flags if site is updated.
this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => {
this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite();
this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite();
}, CoreSites.instance.getCurrentSiteId()); }, CoreSites.getCurrentSiteId());
this.coursesObserver = CoreEvents.on( this.coursesObserver = CoreEvents.on(
CoreCoursesProvider.EVENT_MY_COURSES_UPDATED, CoreCoursesProvider.EVENT_MY_COURSES_UPDATED,
@ -166,10 +166,10 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
this.refreshCourseList(); this.refreshCourseList();
} }
}, },
CoreSites.instance.getCurrentSiteId(), CoreSites.getCurrentSiteId(),
); );
this.currentSite = CoreSites.instance.getCurrentSite(); this.currentSite = CoreSites.getCurrentSite();
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
if (this.currentSite) { if (this.currentSite) {
@ -209,16 +209,16 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
// Invalidate course completion data. // Invalidate course completion data.
promises.push(CoreCourses.instance.invalidateUserCourses().finally(() => promises.push(CoreCourses.invalidateUserCourses().finally(() =>
CoreUtils.instance.allPromises(this.courseIds.map((courseId) => CoreUtils.allPromises(this.courseIds.map((courseId) =>
AddonCourseCompletion.instance.invalidateCourseCompletion(courseId))))); AddonCourseCompletion.invalidateCourseCompletion(courseId)))));
promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions()); promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions());
if (this.courseIds.length > 0) { 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; this.prefetchIconsInitialized = false;
}); });
} }
@ -233,7 +233,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
const showCategories = config?.displaycategories?.value == '1'; 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. // Check to show sort by short name only if the text is visible.
if (courses.length > 0) { if (courses.length > 0) {
@ -300,7 +300,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
false, false,
); );
if (this.showFilters.custom == 'show') { if (this.showFilters.custom == 'show') {
this.customFilter = CoreTextUtils.instance.parseJSON(config?.customfieldsexport?.value, []); this.customFilter = CoreTextUtils.parseJSON(config?.customfieldsexport?.value, []);
} else { } else {
this.customFilter = []; this.customFilter = [];
} }
@ -372,7 +372,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
Object.keys(this.prefetchCoursesData).forEach(async (filter) => { Object.keys(this.prefetchCoursesData).forEach(async (filter) => {
this.prefetchCoursesData[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; const initialIcon = this.prefetchCoursesData[selected].icon;
try { try {
await CoreCourseHelper.instance.prefetchCourses(this.courses[selected], this.prefetchCoursesData[selected]); await CoreCourseHelper.prefetchCourses(this.courses[selected], this.prefetchCoursesData[selected]);
} catch (error) { } catch (error) {
if (!this.isDestroyed) { if (!this.isDestroyed) {
CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true);
this.prefetchCoursesData[selected].icon = initialIcon; this.prefetchCoursesData[selected].icon = initialIcon;
} }
} }
@ -404,7 +404,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_REFRESHED); CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_REFRESHED);
try { try {
await CoreCourses.instance.invalidateUserCourses(); await CoreCourses.invalidateUserCourses();
} catch (error) { } catch (error) {
// Ignore errors. // Ignore errors.
} }
@ -435,7 +435,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
this.loaded = false; this.loaded = false;
try { 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. // Get the courses information from allincludinghidden to get the max info about the course.
const courseIds = courses.map((course) => course.id); const courseIds = courses.map((course) => course.id);
@ -443,7 +443,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
this.filteredCourses = this.courses.allincludinghidden.filter((allCourse) => this.filteredCourses = this.courses.allincludinghidden.filter((allCourse) =>
courseIds.indexOf(allCourse.id) !== -1); courseIds.indexOf(allCourse.id) !== -1);
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, this.fetchContentDefaultError); CoreDomUtils.showErrorModalDefault(error, this.fetchContentDefaultError);
} finally { } finally {
this.loaded = true; this.loaded = true;
} }
@ -500,7 +500,7 @@ export class AddonBlockMyOverviewComponent extends CoreBlockBaseComponent implem
this.courses.favourite = []; this.courses.favourite = [];
this.courses.hidden = []; this.courses.hidden = [];
const today = CoreTimeUtils.instance.timestamp(); const today = CoreTimeUtils.timestamp();
courses.forEach((course) => { courses.forEach((course) => {
if (course.hidden) { if (course.hidden) {
this.courses.hidden.push(course); this.courses.hidden.push(course);

View File

@ -30,7 +30,7 @@ import { AddonBlockMyOverviewHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockMyOverviewHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockMyOverviewHandler.instance);
}, },
}, },
], ],

View File

@ -35,8 +35,8 @@ export class AddonBlockMyOverviewHandlerService extends CoreBlockBaseHandler {
* @return Whether or not the handler is enabled on a site level. * @return Whether or not the handler is enabled on a site level.
*/ */
async isEnabled(): Promise<boolean> { async isEnabled(): Promise<boolean> {
return (CoreSites.instance.getCurrentSite()?.isVersionGreaterEqualThan('3.6')) || return (CoreSites.getCurrentSite()?.isVersionGreaterEqualThan('3.6')) ||
!CoreCourses.instance.isMyCoursesDisabledInSite(); !CoreCourses.isMyCoursesDisabledInSite();
} }
/** /**
@ -55,4 +55,4 @@ export class AddonBlockMyOverviewHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockMyOverviewHandler extends makeSingleton(AddonBlockMyOverviewHandlerService) {} export const AddonBlockMyOverviewHandler = makeSingleton(AddonBlockMyOverviewHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockNewsItemsComponentsModule } from './components/components.mod
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockNewsItemsHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockNewsItemsHandler.instance);
}, },
}, },
], ],

View File

@ -44,4 +44,4 @@ export class AddonBlockNewsItemsHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockNewsItemsHandler extends makeSingleton(AddonBlockNewsItemsHandlerService) {} export const AddonBlockNewsItemsHandler = makeSingleton(AddonBlockNewsItemsHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockOnlineUsersComponentsModule } from './components/components.m
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockOnlineUsersHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockOnlineUsersHandler.instance);
}, },
}, },
], ],

View File

@ -43,4 +43,4 @@ export class AddonBlockOnlineUsersHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockOnlineUsersHandler extends makeSingleton(AddonBlockOnlineUsersHandlerService) {} export const AddonBlockOnlineUsersHandler = makeSingleton(AddonBlockOnlineUsersHandlerService);

View File

@ -28,7 +28,7 @@ import { AddonBlockPrivateFilesHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockPrivateFilesHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockPrivateFilesHandler.instance);
}, },
}, },
], ],

View File

@ -46,4 +46,4 @@ export class AddonBlockPrivateFilesHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockPrivateFilesHandler extends makeSingleton(AddonBlockPrivateFilesHandlerService) {} export const AddonBlockPrivateFilesHandler = makeSingleton(AddonBlockPrivateFilesHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockRecentActivityComponentsModule } from './components/component
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockRecentActivityHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockRecentActivityHandler.instance);
}, },
}, },
], ],

View File

@ -44,4 +44,4 @@ export class AddonBlockRecentActivityHandlerService extends CoreBlockBaseHandler
} }
export class AddonBlockRecentActivityHandler extends makeSingleton(AddonBlockRecentActivityHandlerService) {} export const AddonBlockRecentActivityHandler = makeSingleton(AddonBlockRecentActivityHandlerService);

View File

@ -64,15 +64,15 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
// Refresh the enabled flags if enabled. // Refresh the enabled flags if enabled.
this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite();
this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite();
// Refresh the enabled flags if site is updated. // Refresh the enabled flags if site is updated.
this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => {
this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite();
this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite();
}, CoreSites.instance.getCurrentSiteId()); }, CoreSites.getCurrentSiteId());
this.coursesObserver = CoreEvents.on( this.coursesObserver = CoreEvents.on(
CoreCoursesProvider.EVENT_MY_COURSES_UPDATED, CoreCoursesProvider.EVENT_MY_COURSES_UPDATED,
@ -83,7 +83,7 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom
} }
}, },
CoreSites.instance.getCurrentSiteId(), CoreSites.getCurrentSiteId(),
); );
super.ngOnInit(); super.ngOnInit();
@ -107,17 +107,17 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom
protected async invalidateContent(): Promise<void> { protected async invalidateContent(): Promise<void> {
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
promises.push(CoreCourses.instance.invalidateUserCourses().finally(() => promises.push(CoreCourses.invalidateUserCourses().finally(() =>
// Invalidate course completion data. // Invalidate course completion data.
CoreUtils.instance.allPromises(this.courseIds.map((courseId) => CoreUtils.allPromises(this.courseIds.map((courseId) =>
AddonCourseCompletion.instance.invalidateCourseCompletion(courseId))))); AddonCourseCompletion.invalidateCourseCompletion(courseId)))));
promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions()); promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions());
if (this.courseIds.length > 0) { 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; this.prefetchIconsInitialized = false;
}); });
} }
@ -131,7 +131,7 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom
const showCategories = this.block.configsRecord && this.block.configsRecord.displaycategories && const showCategories = this.block.configsRecord && this.block.configsRecord.displaycategories &&
this.block.configsRecord.displaycategories.value == '1'; 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(); this.initPrefetchCoursesIcons();
} }
@ -144,7 +144,7 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom
CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_REFRESHED); CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_REFRESHED);
try { try {
await CoreCourses.instance.invalidateUserCourses(); await CoreCourses.invalidateUserCourses();
} catch (error) { } catch (error) {
// Ignore errors. // Ignore errors.
} }
@ -163,7 +163,7 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom
this.prefetchIconsInitialized = true; 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; 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) { 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. // Update list if user viewed a course that isn't the most recent one and isn't site home.
return true; return true;
@ -216,10 +216,10 @@ export class AddonBlockRecentlyAccessedCoursesComponent extends CoreBlockBaseCom
const initialIcon = this.prefetchCoursesData.icon; const initialIcon = this.prefetchCoursesData.icon;
try { try {
return CoreCourseHelper.instance.prefetchCourses(this.courses, this.prefetchCoursesData); return CoreCourseHelper.prefetchCourses(this.courses, this.prefetchCoursesData);
} catch (error) { } catch (error) {
if (!this.isDestroyed) { if (!this.isDestroyed) {
CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true);
this.prefetchCoursesData.icon = initialIcon; this.prefetchCoursesData.icon = initialIcon;
} }
} }

View File

@ -28,7 +28,7 @@ import { AddonBlockRecentlyAccessedCoursesHandler } from './services/block-handl
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockRecentlyAccessedCoursesHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockRecentlyAccessedCoursesHandler.instance);
}, },
}, },
], ],

View File

@ -43,4 +43,4 @@ export class AddonBlockRecentlyAccessedCoursesHandlerService extends CoreBlockBa
} }
export class AddonBlockRecentlyAccessedCoursesHandler extends makeSingleton(AddonBlockRecentlyAccessedCoursesHandlerService) {} export const AddonBlockRecentlyAccessedCoursesHandler = makeSingleton(AddonBlockRecentlyAccessedCoursesHandlerService);

View File

@ -48,7 +48,7 @@ export class AddonBlockRecentlyAccessedItemsComponent extends CoreBlockBaseCompo
* @return Resolved when done. * @return Resolved when done.
*/ */
protected async invalidateContent(): Promise<void> { protected async invalidateContent(): Promise<void> {
await AddonBlockRecentlyAccessedItems.instance.invalidateRecentItems(); await AddonBlockRecentlyAccessedItems.invalidateRecentItems();
} }
/** /**
@ -57,7 +57,7 @@ export class AddonBlockRecentlyAccessedItemsComponent extends CoreBlockBaseCompo
* @return Promise resolved when done. * @return Promise resolved when done.
*/ */
protected async fetchContent(): Promise<void> { protected async fetchContent(): Promise<void> {
this.items = await AddonBlockRecentlyAccessedItems.instance.getRecentItems(); this.items = await AddonBlockRecentlyAccessedItems.getRecentItems();
} }
/** /**
@ -70,13 +70,13 @@ export class AddonBlockRecentlyAccessedItemsComponent extends CoreBlockBaseCompo
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
const url = CoreTextUtils.instance.decodeHTMLEntities(item.viewurl); const url = CoreTextUtils.decodeHTMLEntities(item.viewurl);
const modal = await CoreDomUtils.instance.showModalLoading(); const modal = await CoreDomUtils.showModalLoading();
try { try {
const treated = await CoreContentLinksHelper.instance.handleLink(url); const treated = await CoreContentLinksHelper.handleLink(url);
if (!treated) { if (!treated) {
return CoreSites.instance.getCurrentSite()?.openInBrowserWithAutoLoginIfSameSite(url); return CoreSites.getCurrentSite()?.openInBrowserWithAutoLoginIfSameSite(url);
} }
} finally { } finally {
modal.dismiss(); modal.dismiss();

View File

@ -28,7 +28,7 @@ import { AddonBlockRecentlyAccessedItemsHandler } from './services/block-handler
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockRecentlyAccessedItemsHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockRecentlyAccessedItemsHandler.instance);
}, },
}, },
], ],

View File

@ -46,4 +46,4 @@ export class AddonBlockRecentlyAccessedItemsHandlerService extends CoreBlockBase
} }
export class AddonBlockRecentlyAccessedItemsHandler extends makeSingleton(AddonBlockRecentlyAccessedItemsHandlerService) {} export const AddonBlockRecentlyAccessedItemsHandler = makeSingleton(AddonBlockRecentlyAccessedItemsHandlerService);

View File

@ -43,7 +43,7 @@ export class AddonBlockRecentlyAccessedItemsProvider {
* @return Promise resolved when the info is retrieved. * @return Promise resolved when the info is retrieved.
*/ */
async getRecentItems(siteId?: string): Promise<AddonBlockRecentlyAccessedItemsItem[]> { async getRecentItems(siteId?: string): Promise<AddonBlockRecentlyAccessedItemsItem[]> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const preSets: CoreSiteWSPreSets = { const preSets: CoreSiteWSPreSets = {
cacheKey: this.getRecentItemsCacheKey(), cacheKey: this.getRecentItemsCacheKey(),
@ -53,9 +53,9 @@ export class AddonBlockRecentlyAccessedItemsProvider {
await site.read('block_recentlyaccesseditems_get_recent_items', undefined, preSets); await site.read('block_recentlyaccesseditems_get_recent_items', undefined, preSets);
return items.map((item) => { 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; return item;
}); });
@ -68,13 +68,13 @@ export class AddonBlockRecentlyAccessedItemsProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateRecentItems(siteId?: string): Promise<void> { async invalidateRecentItems(siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getRecentItemsCacheKey()); await site.invalidateWsCacheForKey(this.getRecentItemsCacheKey());
} }
} }
export class AddonBlockRecentlyAccessedItems extends makeSingleton(AddonBlockRecentlyAccessedItemsProvider) {} export const AddonBlockRecentlyAccessedItems = makeSingleton(AddonBlockRecentlyAccessedItemsProvider);
/** /**

View File

@ -30,7 +30,7 @@ import { AddonBlockRssClientComponentsModule } from './components/components.mod
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockRssClientHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockRssClientHandler.instance);
}, },
}, },
], ],

View File

@ -46,4 +46,4 @@ export class AddonBlockRssClientHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockRssClientHandler extends makeSingleton(AddonBlockRssClientHandlerService) {} export const AddonBlockRssClientHandler = makeSingleton(AddonBlockRssClientHandlerService);

View File

@ -28,7 +28,7 @@ import { AddonBlockSelfCompletionHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockSelfCompletionHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockSelfCompletionHandler.instance);
}, },
}, },
], ],

View File

@ -50,4 +50,4 @@ export class AddonBlockSelfCompletionHandlerService extends CoreBlockBaseHandler
} }
export class AddonBlockSelfCompletionHandler extends makeSingleton(AddonBlockSelfCompletionHandlerService) {} export const AddonBlockSelfCompletionHandler = makeSingleton(AddonBlockSelfCompletionHandlerService);

View File

@ -45,7 +45,7 @@ export class AddonBlockSiteMainMenuComponent extends CoreBlockBaseComponent impl
* Component being initialized. * Component being initialized.
*/ */
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
this.siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); this.siteHomeId = CoreSites.getCurrentSiteHomeId();
super.ngOnInit(); super.ngOnInit();
} }
@ -58,12 +58,12 @@ export class AddonBlockSiteMainMenuComponent extends CoreBlockBaseComponent impl
protected async invalidateContent(): Promise<void> { protected async invalidateContent(): Promise<void> {
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
promises.push(CoreCourse.instance.invalidateSections(this.siteHomeId)); promises.push(CoreCourse.invalidateSections(this.siteHomeId));
promises.push(CoreSiteHome.instance.invalidateNewsForum(this.siteHomeId)); promises.push(CoreSiteHome.invalidateNewsForum(this.siteHomeId));
if (this.mainMenuBlock && this.mainMenuBlock.modules) { if (this.mainMenuBlock && this.mainMenuBlock.modules) {
// Invalidate modules prefetch data. // 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); await Promise.all(promises);
@ -75,14 +75,14 @@ export class AddonBlockSiteMainMenuComponent extends CoreBlockBaseComponent impl
* @return Promise resolved when done. * @return Promise resolved when done.
*/ */
protected async fetchContent(): Promise<void> { protected async fetchContent(): Promise<void> {
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); const mainMenuBlock = sections.find((section) => section.section == 0);
if (!mainMenuBlock) { if (!mainMenuBlock) {
return; return;
} }
const currentSite = CoreSites.instance.getCurrentSite(); const currentSite = CoreSites.getCurrentSite();
const config = currentSite ? currentSite.getStoredConfig() || {} : {}; const config = currentSite ? currentSite.getStoredConfig() || {} : {};
if (!config.frontpageloggedin) { if (!config.frontpageloggedin) {
return; return;
@ -91,7 +91,7 @@ export class AddonBlockSiteMainMenuComponent extends CoreBlockBaseComponent impl
const items = config.frontpageloggedin.split(','); const items = config.frontpageloggedin.split(',');
const hasNewsItem = items.find((item) => parseInt(item, 10) == FrontPageItemNames['NEWS_ITEMS']); const hasNewsItem = items.find((item) => parseInt(item, 10) == FrontPageItemNames['NEWS_ITEMS']);
const result = CoreCourseHelper.instance.addHandlerDataForModules( const result = CoreCourseHelper.addHandlerDataForModules(
[mainMenuBlock], [mainMenuBlock],
this.siteHomeId, this.siteHomeId,
undefined, 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. // Remove forum activity (news one only) from the main menu block to prevent duplicates.
try { try {
const forum = await CoreSiteHome.instance.getNewsForum(this.siteHomeId); const forum = await CoreSiteHome.getNewsForum(this.siteHomeId);
// Search the module that belongs to site news. // Search the module that belongs to site news.
const forumIndex = const forumIndex =
this.mainMenuBlock.modules.findIndex((mod) => mod.modname == 'forum' && mod.instance == forum.id); this.mainMenuBlock.modules.findIndex((mod) => mod.modname == 'forum' && mod.instance == forum.id);

View File

@ -43,4 +43,4 @@ export class AddonBlockSiteMainMenuHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockSiteMainMenuHandler extends makeSingleton(AddonBlockSiteMainMenuHandlerService) {} export const AddonBlockSiteMainMenuHandler = makeSingleton(AddonBlockSiteMainMenuHandlerService);

View File

@ -28,7 +28,7 @@ import { AddonBlockSiteMainMenuHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockSiteMainMenuHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockSiteMainMenuHandler.instance);
}, },
}, },
], ],

View File

@ -63,15 +63,15 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im
*/ */
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
// Refresh the enabled flags if enabled. // Refresh the enabled flags if enabled.
this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite();
this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite();
// Refresh the enabled flags if site is updated. // Refresh the enabled flags if site is updated.
this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => { this.updateSiteObserver = CoreEvents.on(CoreEvents.SITE_UPDATED, () => {
this.downloadCourseEnabled = !CoreCourses.instance.isDownloadCourseDisabledInSite(); this.downloadCourseEnabled = !CoreCourses.isDownloadCourseDisabledInSite();
this.downloadCoursesEnabled = !CoreCourses.instance.isDownloadCoursesDisabledInSite(); this.downloadCoursesEnabled = !CoreCourses.isDownloadCoursesDisabledInSite();
}, CoreSites.instance.getCurrentSiteId()); }, CoreSites.getCurrentSiteId());
this.coursesObserver = CoreEvents.on( this.coursesObserver = CoreEvents.on(
CoreCoursesProvider.EVENT_MY_COURSES_UPDATED, CoreCoursesProvider.EVENT_MY_COURSES_UPDATED,
@ -83,7 +83,7 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im
this.refreshContent(); this.refreshContent();
}, },
CoreSites.instance.getCurrentSiteId(), CoreSites.getCurrentSiteId(),
); );
super.ngOnInit(); super.ngOnInit();
@ -107,17 +107,17 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im
protected async invalidateContent(): Promise<void> { protected async invalidateContent(): Promise<void> {
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
promises.push(CoreCourses.instance.invalidateUserCourses().finally(() => promises.push(CoreCourses.invalidateUserCourses().finally(() =>
// Invalidate course completion data. // Invalidate course completion data.
CoreUtils.instance.allPromises(this.courseIds.map((courseId) => CoreUtils.allPromises(this.courseIds.map((courseId) =>
AddonCourseCompletion.instance.invalidateCourseCompletion(courseId))))); AddonCourseCompletion.invalidateCourseCompletion(courseId)))));
promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions()); promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions());
if (this.courseIds.length > 0) { 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; this.prefetchIconsInitialized = false;
}); });
} }
@ -131,7 +131,7 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im
const showCategories = this.block.configsRecord && this.block.configsRecord.displaycategories && const showCategories = this.block.configsRecord && this.block.configsRecord.displaycategories &&
this.block.configsRecord.displaycategories.value == '1'; 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(); this.initPrefetchCoursesIcons();
} }
@ -144,7 +144,7 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im
CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_REFRESHED); CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_REFRESHED);
try { try {
await CoreCourses.instance.invalidateUserCourses(); await CoreCourses.invalidateUserCourses();
} catch (error) { } catch (error) {
// Ignore errors. // Ignore errors.
} }
@ -184,7 +184,7 @@ export class AddonBlockStarredCoursesComponent extends CoreBlockBaseComponent im
this.prefetchIconsInitialized = true; 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; const initialIcon = this.prefetchCoursesData.icon;
try { try {
return CoreCourseHelper.instance.prefetchCourses(this.courses, this.prefetchCoursesData); return CoreCourseHelper.prefetchCourses(this.courses, this.prefetchCoursesData);
} catch (error) { } catch (error) {
if (!this.isDestroyed) { if (!this.isDestroyed) {
CoreDomUtils.instance.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true); CoreDomUtils.showErrorModalDefault(error, 'core.course.errordownloadingcourse', true);
this.prefetchCoursesData.icon = initialIcon; this.prefetchCoursesData.icon = initialIcon;
} }
} }

View File

@ -43,4 +43,4 @@ export class AddonBlockStarredCoursesHandlerService extends CoreBlockBaseHandler
} }
export class AddonBlockStarredCoursesHandler extends makeSingleton(AddonBlockStarredCoursesHandlerService) {} export const AddonBlockStarredCoursesHandler = makeSingleton(AddonBlockStarredCoursesHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockStarredCoursesHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockStarredCoursesHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockStarredCoursesHandler.instance);
}, },
}, },
], ],

View File

@ -44,4 +44,4 @@ export class AddonBlockTagsHandlerService extends CoreBlockBaseHandler {
} }
export class AddonBlockTagsHandler extends makeSingleton(AddonBlockTagsHandlerService) {} export const AddonBlockTagsHandler = makeSingleton(AddonBlockTagsHandlerService);

View File

@ -30,7 +30,7 @@ import { AddonBlockTagsComponentsModule } from './components/components.module';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockTagsHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockTagsHandler.instance);
}, },
}, },
], ],

View File

@ -51,7 +51,7 @@ export class AddonBlockTimelineEventsComponent implements OnChanges {
* Detect changes on input properties. * Detect changes on input properties.
*/ */
ngOnChanges(changes: {[name: string]: SimpleChange}): void { 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 (changes.events || changes.from || changes.to) {
if (this.events && this.events.length > 0) { if (this.events && this.events.length > 0) {
@ -60,7 +60,7 @@ export class AddonBlockTimelineEventsComponent implements OnChanges {
const eventsByDay: Record<number, AddonCalendarEvent[]> = {}; const eventsByDay: Record<number, AddonCalendarEvent[]> = {};
filteredEvents.forEach((event) => { filteredEvents.forEach((event) => {
const dayTimestamp = CoreTimeUtils.instance.getMidnightForTimestamp(event.timesort); const dayTimestamp = CoreTimeUtils.getMidnightForTimestamp(event.timesort);
if (eventsByDay[dayTimestamp]) { if (eventsByDay[dayTimestamp]) {
eventsByDay[dayTimestamp].push(event); eventsByDay[dayTimestamp].push(event);
} else { } else {
@ -68,7 +68,7 @@ export class AddonBlockTimelineEventsComponent implements OnChanges {
} }
}); });
const todaysMidnight = CoreTimeUtils.instance.getMidnightForTimestamp(); const todaysMidnight = CoreTimeUtils.getMidnightForTimestamp();
this.filteredEvents = []; this.filteredEvents = [];
Object.keys(eventsByDay).forEach((key) => { Object.keys(eventsByDay).forEach((key) => {
const dayTimestamp = parseInt(key); const dayTimestamp = parseInt(key);
@ -102,7 +102,7 @@ export class AddonBlockTimelineEventsComponent implements OnChanges {
return start <= event.timesort; return start <= event.timesort;
}).map((event) => { }).map((event) => {
event.iconUrl = CoreCourse.instance.getModuleIconSrc(event.icon.component); event.iconUrl = CoreCourse.getModuleIconSrc(event.icon.component);
return event; return event;
}); });
@ -127,14 +127,14 @@ export class AddonBlockTimelineEventsComponent implements OnChanges {
e.stopPropagation(); e.stopPropagation();
// Fix URL format. // Fix URL format.
url = CoreTextUtils.instance.decodeHTMLEntities(url); url = CoreTextUtils.decodeHTMLEntities(url);
const modal = await CoreDomUtils.instance.showModalLoading(); const modal = await CoreDomUtils.showModalLoading();
try { try {
const treated = await CoreContentLinksHelper.instance.handleLink(url); const treated = await CoreContentLinksHelper.handleLink(url);
if (!treated) { if (!treated) {
return CoreSites.instance.getCurrentSite()?.openInBrowserWithAutoLoginIfSameSite(url); return CoreSites.getCurrentSite()?.openInBrowserWithAutoLoginIfSameSite(url);
} }
} finally { } finally {
modal.dismiss(); modal.dismiss();

View File

@ -69,7 +69,7 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen
* Component being initialized. * Component being initialized.
*/ */
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
this.currentSite = CoreSites.instance.getCurrentSite(); this.currentSite = CoreSites.getCurrentSite();
this.filter = await this.currentSite!.getLocalSiteConfig('AddonBlockTimelineFilter', this.filter); this.filter = await this.currentSite!.getLocalSiteConfig('AddonBlockTimelineFilter', this.filter);
this.switchFilter(); this.switchFilter();
@ -87,15 +87,15 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen
protected invalidateContent(): Promise<void> { protected invalidateContent(): Promise<void> {
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
promises.push(AddonBlockTimeline.instance.invalidateActionEventsByTimesort()); promises.push(AddonBlockTimeline.invalidateActionEventsByTimesort());
promises.push(AddonBlockTimeline.instance.invalidateActionEventsByCourses()); promises.push(AddonBlockTimeline.invalidateActionEventsByCourses());
promises.push(CoreCourses.instance.invalidateUserCourses()); promises.push(CoreCourses.invalidateUserCourses());
promises.push(CoreCourseOptionsDelegate.instance.clearAndInvalidateCoursesOptions()); promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions());
if (this.courseIds.length > 0) { 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 { try {
await this.fetchMyOverviewTimeline(this.timeline.canLoadMore); await this.fetchMyOverviewTimeline(this.timeline.canLoadMore);
} catch (error) { } 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<void> { async loadMoreCourse(course: AddonBlockTimelineCourse): Promise<void> {
try { 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.events = course.events?.concat(courseEvents.events);
course.canLoadMore = courseEvents.canLoadMore; course.canLoadMore = courseEvents.canLoadMore;
} catch (error) { } 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. * @return Promise resolved when done.
*/ */
protected async fetchMyOverviewTimeline(afterEventId?: number): Promise<void> { protected async fetchMyOverviewTimeline(afterEventId?: number): Promise<void> {
const events = await AddonBlockTimeline.instance.getActionEventsByTimesort(afterEventId); const events = await AddonBlockTimeline.getActionEventsByTimesort(afterEventId);
this.timeline.events = events.events; this.timeline.events = events.events;
this.timeline.canLoadMore = events.canLoadMore; this.timeline.canLoadMore = events.canLoadMore;
@ -163,8 +163,8 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen
* @return Promise resolved when done. * @return Promise resolved when done.
*/ */
protected async fetchMyOverviewTimelineByCourses(): Promise<void> { protected async fetchMyOverviewTimelineByCourses(): Promise<void> {
const courses = await CoreCoursesHelper.instance.getUserCoursesWithOptions(); const courses = await CoreCoursesHelper.getUserCoursesWithOptions();
const today = CoreTimeUtils.instance.timestamp(); const today = CoreTimeUtils.timestamp();
this.timelineCourses.courses = courses.filter((course) => this.timelineCourses.courses = courses.filter((course) =>
(course.startdate || 0) <= today && (!course.enddate || course.enddate >= today)); (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) { if (this.timelineCourses.courses.length > 0) {
this.courseIds = this.timelineCourses.courses.map((course) => course.id); 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) => { this.timelineCourses.courses.forEach((course) => {
course.events = courseEvents[course.id].events; course.events = courseEvents[course.id].events;

View File

@ -36,11 +36,11 @@ export class AddonBlockTimelineHandlerService extends CoreBlockBaseHandler {
* @return Whether or not the handler is enabled on a site level. * @return Whether or not the handler is enabled on a site level.
*/ */
async isEnabled(): Promise<boolean> { async isEnabled(): Promise<boolean> {
const enabled = await AddonBlockTimeline.instance.isAvailable(); const enabled = await AddonBlockTimeline.isAvailable();
const currentSite = CoreSites.instance.getCurrentSite(); const currentSite = CoreSites.getCurrentSite();
return enabled && ((currentSite && currentSite.isVersionGreaterEqualThan('3.6')) || 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);

View File

@ -53,7 +53,7 @@ export class AddonBlockTimelineProvider {
afterEventId?: number, afterEventId?: number,
siteId?: string, siteId?: string,
): Promise<{ events: AddonCalendarEvent[]; canLoadMore?: number }> { ): 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. const time = moment().subtract(14, 'days').unix(); // Check two weeks ago.
@ -104,7 +104,7 @@ export class AddonBlockTimelineProvider {
courseIds: number[], courseIds: number[],
siteId?: string, siteId?: string,
): Promise<{[courseId: string]: { events: AddonCalendarEvent[]; canLoadMore: number } }> { ): 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. const time = moment().subtract(14, 'days').unix(); // Check two weeks ago.
@ -156,7 +156,7 @@ export class AddonBlockTimelineProvider {
afterEventId?: number, afterEventId?: number,
siteId?: string, siteId?: string,
): Promise<{ events: AddonCalendarEvent[]; canLoadMore?: number }> { ): 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 timesortfrom = moment().subtract(14, 'days').unix(); // Check two weeks ago.
const limitnum = AddonBlockTimelineProvider.EVENTS_LIMIT; const limitnum = AddonBlockTimelineProvider.EVENTS_LIMIT;
@ -226,7 +226,7 @@ export class AddonBlockTimelineProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateActionEventsByCourses(siteId?: string): Promise<void> { async invalidateActionEventsByCourses(siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getActionEventsByCoursesCacheKey()); await site.invalidateWsCacheForKeyStartingWith(this.getActionEventsByCoursesCacheKey());
} }
@ -238,7 +238,7 @@ export class AddonBlockTimelineProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateActionEventsByTimesort(siteId?: string): Promise<void> { async invalidateActionEventsByTimesort(siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getActionEventsByTimesortPrefixCacheKey()); 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. * @return Promise resolved with true if available, resolved with false or rejected otherwise.
*/ */
async isAvailable(siteId?: string): Promise<boolean> { async isAvailable(siteId?: string): Promise<boolean> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
// First check if dashboard is disabled. // First check if dashboard is disabled.
if (CoreCoursesDashboard.instance.isDisabledInSite(site)) { if (CoreCoursesDashboard.isDisabledInSite(site)) {
return false; return false;
} }
@ -287,4 +287,4 @@ export class AddonBlockTimelineProvider {
} }
export class AddonBlockTimeline extends makeSingleton(AddonBlockTimelineProvider) {} export const AddonBlockTimeline = makeSingleton(AddonBlockTimelineProvider);

View File

@ -30,7 +30,7 @@ import { AddonBlockTimelineHandler } from './services/block-handler';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
useValue: () => { useValue: () => {
CoreBlockDelegate.instance.registerHandler(AddonBlockTimelineHandler.instance); CoreBlockDelegate.registerHandler(AddonBlockTimelineHandler.instance);
}, },
}, },
], ],

View File

@ -55,13 +55,13 @@ const mainMenuChildrenRoutes: Routes = [
multi: true, multi: true,
deps: [], deps: [],
useFactory: () => async () => { useFactory: () => async () => {
CoreContentLinksDelegate.instance.registerHandler(AddonCalendarViewLinkHandler.instance); CoreContentLinksDelegate.registerHandler(AddonCalendarViewLinkHandler.instance);
CoreMainMenuDelegate.instance.registerHandler(AddonCalendarMainMenuHandler.instance); CoreMainMenuDelegate.registerHandler(AddonCalendarMainMenuHandler.instance);
CoreCronDelegate.instance.register(AddonCalendarSyncCronHandler.instance); CoreCronDelegate.register(AddonCalendarSyncCronHandler.instance);
await AddonCalendar.instance.initialize(); await AddonCalendar.initialize();
AddonCalendar.instance.scheduleAllSitesEventsNotifications(); AddonCalendar.scheduleAllSitesEventsNotifications();
}, },
}, },
], ],

View File

@ -89,14 +89,14 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
differs: KeyValueDiffers, 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. // Re-schedule events if default time changes.
this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => { this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => {
this.weeks.forEach((week) => { this.weeks.forEach((week) => {
week.days.forEach((day) => { week.days.forEach((day) => {
AddonCalendar.instance.scheduleEventsNotifications(day.eventsFormated!); AddonCalendar.scheduleEventsNotifications(day.eventsFormated!);
}); });
}); });
}, this.currentSiteId); }, this.currentSiteId);
@ -144,9 +144,9 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
* Detect and act upon changes that Angular cant or wont detect on its own (objects and arrays). * Detect and act upon changes that Angular cant or wont detect on its own (objects and arrays).
*/ */
ngDoCheck(): void { 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 : this.displayNavButtons = typeof this.displayNavButtons == 'undefined' ? true :
CoreUtils.instance.isTrueOrOne(this.displayNavButtons); CoreUtils.isTrueOrOne(this.displayNavButtons);
if (this.weeks) { if (this.weeks) {
// Check if there's any change in the filter object. // 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()); promises.push(this.loadCategories());
// Get offline events. // Get offline events.
promises.push(AddonCalendarOffline.instance.getAllEditedEvents().then((events) => { promises.push(AddonCalendarOffline.getAllEditedEvents().then((events) => {
// Classify them by month. // Classify them by month.
this.offlineEvents = AddonCalendarHelper.instance.classifyIntoMonths(events); this.offlineEvents = AddonCalendarHelper.classifyIntoMonths(events);
// Get the IDs of events edited in offline. // Get the IDs of events edited in offline.
const filtered = events.filter((event) => event.id! > 0); const filtered = events.filter((event) => event.id! > 0);
@ -180,14 +180,14 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
})); }));
// Get events deleted in offline. // Get events deleted in offline.
promises.push(AddonCalendarOffline.instance.getAllDeletedEventsIds().then((ids) => { promises.push(AddonCalendarOffline.getAllDeletedEventsIds().then((ids) => {
this.deletedEvents = ids; this.deletedEvents = ids;
return; return;
})); }));
// Get time format to use. // Get time format to use.
promises.push(AddonCalendar.instance.getCalendarTimeFormat().then((value) => { promises.push(AddonCalendar.getCalendarTimeFormat().then((value) => {
this.timeFormat = value; this.timeFormat = value;
return; return;
@ -199,7 +199,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
await this.fetchEvents(); await this.fetchEvents();
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
} }
this.loaded = 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. // Don't pass courseId and categoryId, we'll filter them locally.
let result: { daynames: Partial<AddonCalendarDayName>[]; weeks: Partial<AddonCalendarWeek>[] }; let result: { daynames: Partial<AddonCalendarDayName>[]; weeks: Partial<AddonCalendarWeek>[] };
try { try {
result = await AddonCalendar.instance.getMonthlyEvents(this.year!, this.month!); result = await AddonCalendar.getMonthlyEvents(this.year!, this.month!);
} catch (error) { } catch (error) {
if (!CoreApp.instance.isOnline()) { if (!CoreApp.isOnline()) {
// Allow navigating to non-cached months in offline (behave as if using emergency cache). // 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 { } else {
throw error; throw error;
} }
} }
// Calculate the period name. We don't use the one in result because it's in server's language. // 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(), new Date(this.year!, this.month! - 1).getTime(),
'core.strftimemonthyear', '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.weeks = result.weeks as AddonCalendarWeek[];
this.calculateIsCurrentMonth(); this.calculateIsCurrentMonth();
@ -239,7 +239,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
day.filteredEvents = day.filteredEvents || []; day.filteredEvents = day.filteredEvents || [];
day.events.forEach((event) => { day.events.forEach((event) => {
/// Format online events. /// 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 { try {
const cats = await CoreCourses.instance.getCategories(0, true); const cats = await CoreCourses.getCategories(0, true);
this.categoriesRetrieved = true; this.categoriesRetrieved = true;
this.categories = {}; this.categories = {};
@ -299,14 +299,14 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
filterEvents(): void { filterEvents(): void {
this.weeks.forEach((week) => { this.weeks.forEach((week) => {
week.days.forEach((day) => { week.days.forEach((day) => {
day.filteredEvents = AddonCalendarHelper.instance.getFilteredEvents( day.filteredEvents = AddonCalendarHelper.getFilteredEvents(
day.eventsFormated!, day.eventsFormated!,
this.filter!, this.filter!,
this.categories, this.categories,
); );
// Re-calculate some properties. // 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. // Don't invalidate monthly events after a change, it has already been handled.
if (!afterChange) { 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(CoreCourses.invalidateCategories(0, true));
promises.push(AddonCalendar.instance.invalidateTimeFormat()); promises.push(AddonCalendar.invalidateTimeFormat());
this.categoriesRetrieved = false; // Get categories again. this.categoriesRetrieved = false; // Get categories again.
@ -345,7 +345,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
try { try {
await this.fetchEvents(); await this.fetchEvents();
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
this.decreaseMonth(); this.decreaseMonth();
} }
this.loaded = true; this.loaded = true;
@ -362,7 +362,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
try { try {
await this.fetchEvents(); await this.fetchEvents();
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
this.increaseMonth(); this.increaseMonth();
} }
this.loaded = true; this.loaded = true;
@ -394,7 +394,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
calculateIsCurrentMonth(): void { calculateIsCurrentMonth(): void {
const now = new Date(); 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.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); 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(); await this.fetchEvents();
this.isCurrentMonth = true; this.isCurrentMonth = true;
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
this.year = initialYear; this.year = initialYear;
this.month = initialMonth; this.month = initialMonth;
} }
@ -454,13 +454,13 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
*/ */
protected mergeEvents(): void { protected mergeEvents(): void {
const monthOfflineEvents: { [day: number]: AddonCalendarEventToDisplay[] } = 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) => { this.weeks.forEach((week) => {
week.days.forEach((day) => { week.days.forEach((day) => {
// Schedule notifications for the events retrieved (only future events will be scheduled). // 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) { if (monthOfflineEvents || this.deletedEvents.length) {
// There is offline data, merge it. // There is offline data, merge it.
@ -480,7 +480,7 @@ export class AddonCalendarCalendarComponent implements OnInit, DoCheck, OnDestro
if (monthOfflineEvents && monthOfflineEvents[day.mday]) { if (monthOfflineEvents && monthOfflineEvents[day.mday]) {
// Add the offline events (either new or edited). // Add the offline events (either new or edited).
day.eventsFormated = day.eventsFormated =
AddonCalendarHelper.instance.sortEvents(day.eventsFormated!.concat(monthOfflineEvents[day.mday])); AddonCalendarHelper.sortEvents(day.eventsFormated!.concat(monthOfflineEvents[day.mday]));
} }
} }
}); });

View File

@ -48,7 +48,7 @@ export class AddonCalendarFilterPopoverComponent implements OnInit {
types: string[] = []; types: string[] = [];
constructor() { constructor() {
CoreUtils.instance.enumKeys(AddonCalendarEventType).forEach((name) => { CoreUtils.enumKeys(AddonCalendarEventType).forEach((name) => {
const value = AddonCalendarEventType[name]; const value = AddonCalendarEventType[name];
this.typeIcons[value] = AddonCalendarEventIcons[name]; this.typeIcons[value] = AddonCalendarEventIcons[name];
this.types.push(value); this.types.push(value);

View File

@ -64,11 +64,11 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On
constructor( constructor(
differs: KeyValueDiffers, 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, () => { this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => {
AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); AddonCalendar.scheduleEventsNotifications(this.onlineEvents);
}, this.currentSiteId); }, this.currentSiteId);
} }
@ -124,31 +124,31 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On
promises.push(this.loadCategories()); promises.push(this.loadCategories());
// Get offline events. // Get offline events.
promises.push(AddonCalendarOffline.instance.getAllEditedEvents().then((offlineEvents) => { promises.push(AddonCalendarOffline.getAllEditedEvents().then((offlineEvents) => {
// Format data. // Format data.
const events: AddonCalendarEventToDisplay[] = offlineEvents.map((event) => 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; return;
})); }));
// Get events deleted in offline. // Get events deleted in offline.
promises.push(AddonCalendarOffline.instance.getAllDeletedEventsIds().then((ids) => { promises.push(AddonCalendarOffline.getAllDeletedEventsIds().then((ids) => {
this.deletedEvents = ids; this.deletedEvents = ids;
return; return;
})); }));
// Get user preferences. // Get user preferences.
promises.push(AddonCalendar.instance.getCalendarLookAhead().then((value) => { promises.push(AddonCalendar.getCalendarLookAhead().then((value) => {
this.lookAhead = value; this.lookAhead = value;
return; return;
})); }));
promises.push(AddonCalendar.instance.getCalendarTimeFormat().then((value) => { promises.push(AddonCalendar.getCalendarTimeFormat().then((value) => {
this.timeFormat = value; this.timeFormat = value;
return; return;
@ -160,7 +160,7 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On
this.fetchEvents(); this.fetchEvents();
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
} }
this.loaded = true; this.loaded = true;
@ -173,10 +173,10 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On
*/ */
async fetchEvents(): Promise<void> { async fetchEvents(): Promise<void> {
// Don't pass courseId and categoryId, we'll filter them locally. // Don't pass courseId and categoryId, we'll filter them locally.
const result = await AddonCalendar.instance.getUpcomingEvents(); const result = await AddonCalendar.getUpcomingEvents();
this.onlineEvents = result.events.map((event) => AddonCalendarHelper.instance.formatEventData(event)); this.onlineEvents = result.events.map((event) => AddonCalendarHelper.formatEventData(event));
// Schedule notifications for the events retrieved. // Schedule notifications for the events retrieved.
AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); AddonCalendar.scheduleEventsNotifications(this.onlineEvents);
// Merge the online events with offline data. // Merge the online events with offline data.
this.events = this.mergeEvents(); this.events = this.mergeEvents();
// Filter events by course. // 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. // Re-calculate the formatted time so it uses the device date.
const promises = this.events.map((event) => const promises = this.events.map((event) =>
AddonCalendar.instance.formatEventTime(event, this.timeFormat!).then((time) => { AddonCalendar.formatEventTime(event, this.timeFormat!).then((time) => {
event.formattedtime = time; event.formattedtime = time;
return; return;
@ -205,7 +205,7 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On
} }
try { try {
const cats = await CoreCourses.instance.getCategories(0, true); const cats = await CoreCourses.getCategories(0, true);
this.categoriesRetrieved = true; this.categoriesRetrieved = true;
this.categories = {}; this.categories = {};
@ -222,7 +222,7 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On
* Filter events based on the filter popover. * Filter events based on the filter popover.
*/ */
protected filterEvents(): void { 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. // Don't invalidate upcoming events after a change, it has already been handled.
if (!afterChange) { if (!afterChange) {
promises.push(AddonCalendar.instance.invalidateAllUpcomingEvents()); promises.push(AddonCalendar.invalidateAllUpcomingEvents());
} }
promises.push(CoreCourses.instance.invalidateCategories(0, true)); promises.push(CoreCourses.invalidateCategories(0, true));
promises.push(AddonCalendar.instance.invalidateLookAhead()); promises.push(AddonCalendar.invalidateLookAhead());
promises.push(AddonCalendar.instance.invalidateTimeFormat()); promises.push(AddonCalendar.invalidateTimeFormat());
this.categoriesRetrieved = false; // Get categories again. this.categoriesRetrieved = false; // Get categories again.
@ -297,7 +297,7 @@ export class AddonCalendarUpcomingEventsComponent implements OnInit, DoCheck, On
// Merge both arrays and sort them. // Merge both arrays and sort them.
result = result.concat(periodOfflineEvents); result = result.concat(periodOfflineEvents);
return AddonCalendarHelper.instance.sortEvents(result); return AddonCalendarHelper.sortEvents(result);
} }
/** /**

View File

@ -102,12 +102,12 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
}; };
constructor() { constructor() {
this.currentSiteId = CoreSites.instance.getCurrentSiteId(); this.currentSiteId = CoreSites.getCurrentSiteId();
if (CoreLocalNotifications.instance.isAvailable()) { if (CoreLocalNotifications.isAvailable()) {
// Re-schedule events if default time changes. // Re-schedule events if default time changes.
this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => { this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => {
AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); AddonCalendar.scheduleEventsNotifications(this.onlineEvents);
}, this.currentSiteId); }, this.currentSiteId);
} }
@ -210,17 +210,17 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
this.filter = data; this.filter = data;
// Course viewed has changed, check if the user can create events for this course calendar. // 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(); this.filterEvents();
}, },
); );
// Refresh online status when changes. // 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. // Execute the callback in the Angular zone, so change detection doesn't stop working.
NgZone.instance.run(() => { NgZone.run(() => {
this.isOnline = CoreApp.instance.isOnline(); this.isOnline = CoreApp.isOnline();
}); });
}); });
} }
@ -231,20 +231,20 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
ngOnInit(): void { ngOnInit(): void {
const types: string[] = []; const types: string[] = [];
CoreUtils.instance.enumKeys(AddonCalendarEventType).forEach((name) => { CoreUtils.enumKeys(AddonCalendarEventType).forEach((name) => {
const value = AddonCalendarEventType[name]; const value = AddonCalendarEventType[name];
this.filter[name] = CoreNavigator.instance.getRouteBooleanParam(name) ?? true; this.filter[name] = CoreNavigator.getRouteBooleanParam(name) ?? true;
types.push(value); types.push(value);
}); });
this.filter.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || -1; this.filter.courseId = CoreNavigator.getRouteNumberParam('courseId') || -1;
this.filter.categoryId = CoreNavigator.instance.getRouteNumberParam('categoryId'); this.filter.categoryId = CoreNavigator.getRouteNumberParam('categoryId');
this.filter.filtered = typeof this.filter.courseId != 'undefined' || types.some((name) => !this.filter[name]); this.filter.filtered = typeof this.filter.courseId != 'undefined' || types.some((name) => !this.filter[name]);
const now = new Date(); const now = new Date();
this.year = CoreNavigator.instance.getRouteNumberParam('year') || now.getFullYear(); this.year = CoreNavigator.getRouteNumberParam('year') || now.getFullYear();
this.month = CoreNavigator.instance.getRouteNumberParam('month') || (now.getMonth() + 1); this.month = CoreNavigator.getRouteNumberParam('month') || (now.getMonth() + 1);
this.day = CoreNavigator.instance.getRouteNumberParam('day') || now.getDate(); this.day = CoreNavigator.getRouteNumberParam('day') || now.getDate();
this.calculateCurrentMoment(); this.calculateCurrentMoment();
this.calculateIsCurrentDay(); this.calculateIsCurrentDay();
@ -262,7 +262,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
async fetchData(sync?: boolean): Promise<void> { async fetchData(sync?: boolean): Promise<void> {
this.syncIcon = CoreConstants.ICON_LOADING; this.syncIcon = CoreConstants.ICON_LOADING;
this.isOnline = CoreApp.instance.isOnline(); this.isOnline = CoreApp.isOnline();
if (sync) { if (sync) {
await this.sync(); await this.sync();
@ -272,7 +272,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
// Load courses for the popover. // 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; this.courses = data.courses;
return; return;
@ -282,9 +282,9 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
promises.push(this.loadCategories()); promises.push(this.loadCategories());
// Get offline events. // Get offline events.
promises.push(AddonCalendarOffline.instance.getAllEditedEvents().then((offlineEvents) => { promises.push(AddonCalendarOffline.getAllEditedEvents().then((offlineEvents) => {
// Classify them by month & day. // Classify them by month & day.
this.offlineEvents = AddonCalendarHelper.instance.classifyIntoMonths(offlineEvents); this.offlineEvents = AddonCalendarHelper.classifyIntoMonths(offlineEvents);
// Get the IDs of events edited in offline. // Get the IDs of events edited in offline.
this.offlineEditedEventsIds = offlineEvents.filter((event) => event.id! > 0).map((event) => event.id!); 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. // Get events deleted in offline.
promises.push(AddonCalendarOffline.instance.getAllDeletedEventsIds().then((ids) => { promises.push(AddonCalendarOffline.getAllDeletedEventsIds().then((ids) => {
this.deletedEvents = ids; this.deletedEvents = ids;
return; return;
})); }));
// Check if user can create events. // 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; this.canCreate = canEdit;
return; return;
})); }));
// Get user preferences. // Get user preferences.
promises.push(AddonCalendar.instance.getCalendarTimeFormat().then((value) => { promises.push(AddonCalendar.getCalendarTimeFormat().then((value) => {
this.timeFormat = value; this.timeFormat = value;
return; return;
@ -317,7 +317,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
await this.fetchEvents(); await this.fetchEvents();
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
} }
this.loaded = true; this.loaded = true;
@ -333,10 +333,10 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
let result: AddonCalendarCalendarDay; let result: AddonCalendarCalendarDay;
try { try {
// Don't pass courseId and categoryId, we'll filter them locally. // Don't pass courseId and categoryId, we'll filter them locally.
result = await AddonCalendar.instance.getDayEvents(this.year, this.month, this.day); result = await AddonCalendar.getDayEvents(this.year, this.month, this.day);
this.onlineEvents = result.events.map((event) => AddonCalendarHelper.instance.formatEventData(event)); this.onlineEvents = result.events.map((event) => AddonCalendarHelper.formatEventData(event));
} catch (error) { } catch (error) {
if (CoreApp.instance.isOnline()) { if (CoreApp.isOnline()) {
throw error; throw error;
} }
// Allow navigating to non-cached days in offline (behave as if using emergency cache). // 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. // 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(), new Date(this.year, this.month - 1, this.day).getTime(),
'core.strftimedaydate', 'core.strftimedaydate',
); );
// Schedule notifications for the events retrieved (only future events will be scheduled). // 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. // Merge the online events with offline data.
this.events = this.mergeEvents(); this.events = this.mergeEvents();
// Filter events by course. // Filter events by course.
@ -362,7 +362,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
const promises = this.events.map((event) => { const promises = this.events.map((event) => {
event.ispast = this.isPastDay || (this.isCurrentDay && this.isEventPast(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; event.formattedtime = time;
return; return;
@ -385,7 +385,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
return this.onlineEvents; 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]; const dayOfflineEvents = monthOfflineEvents && monthOfflineEvents[this.day];
let result = this.onlineEvents; let result = this.onlineEvents;
@ -412,7 +412,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
if (dayOfflineEvents && dayOfflineEvents.length) { if (dayOfflineEvents && dayOfflineEvents.length) {
// Add the offline events (either new or edited). // Add the offline events (either new or edited).
this.hasOffline = true; this.hasOffline = true;
result = AddonCalendarHelper.instance.sortEvents(result.concat(dayOfflineEvents)); result = AddonCalendarHelper.sortEvents(result.concat(dayOfflineEvents));
} }
return result; return result;
@ -422,7 +422,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
* Filter events based on the filter popover. * Filter events based on the filter popover.
*/ */
protected filterEvents(): void { 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. // Don't invalidate day events after a change, it has already been handled.
if (!afterChange) { 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(AddonCalendar.invalidateAllowedEventTypes());
promises.push(CoreCourses.instance.invalidateCategories(0, true)); promises.push(CoreCourses.invalidateCategories(0, true));
promises.push(AddonCalendar.instance.invalidateTimeFormat()); promises.push(AddonCalendar.invalidateTimeFormat());
await Promise.all(promises).finally(() => await Promise.all(promises).finally(() =>
this.fetchData(sync)); this.fetchData(sync));
@ -474,7 +474,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
*/ */
protected async loadCategories(): Promise<void> { protected async loadCategories(): Promise<void> {
try { try {
const cats = await CoreCourses.instance.getCategories(0, true); const cats = await CoreCourses.getCategories(0, true);
this.categories = {}; this.categories = {};
// Index categories by ID. // Index categories by ID.
@ -494,10 +494,10 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
*/ */
protected async sync(showErrors?: boolean): Promise<void> { protected async sync(showErrors?: boolean): Promise<void> {
try { try {
const result = await AddonCalendarSync.instance.syncEvents(); const result = await AddonCalendarSync.syncEvents();
if (result.warnings && result.warnings.length) { if (result.warnings && result.warnings.length) {
CoreDomUtils.instance.showErrorModal(result.warnings[0]); CoreDomUtils.showErrorModal(result.warnings[0]);
} }
if (result.updated) { if (result.updated) {
@ -511,7 +511,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
if (showErrors) { 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. // It's an offline event, go to the edit page.
this.openEdit(eventId); this.openEdit(eventId);
} else { } 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. * @param event Event.
*/ */
async openFilter(event: MouseEvent): Promise<void> { async openFilter(event: MouseEvent): Promise<void> {
const popover = await PopoverController.instance.create({ const popover = await PopoverController.create({
component: AddonCalendarFilterPopoverComponent, component: AddonCalendarFilterPopoverComponent,
componentProps: { componentProps: {
courses: this.courses, courses: this.courses,
@ -566,7 +566,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
params.courseId = this.filter.courseId; 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 { calculateIsCurrentDay(): void {
const now = new Date(); 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.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()) || 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; this.isCurrentDay = true;
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
this.year = initialYear; this.year = initialYear;
this.month = initialMonth; this.month = initialMonth;
@ -632,7 +632,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
try { try {
await this.fetchEvents(); await this.fetchEvents();
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
this.decreaseDay(); this.decreaseDay();
} }
this.loaded = true; this.loaded = true;
@ -649,7 +649,7 @@ export class AddonCalendarDayPage implements OnInit, OnDestroy {
try { try {
await this.fetchEvents(); await this.fetchEvents();
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
this.increaseDay(); this.increaseDay();
} }
this.loaded = true; this.loaded = true;

View File

@ -94,13 +94,13 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
@Optional() protected svComponent: CoreSplitViewComponent, @Optional() protected svComponent: CoreSplitViewComponent,
) { ) {
this.currentSite = CoreSites.instance.getCurrentSite()!; this.currentSite = CoreSites.getCurrentSite()!;
this.errors = { 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. // 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, ''); .replace(/[[\]]/g, '');
this.form = new FormGroup({}); this.form = new FormGroup({});
@ -127,18 +127,18 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
* Component being initialized. * Component being initialized.
*/ */
ngOnInit(): void { ngOnInit(): void {
this.eventId = CoreNavigator.instance.getRouteNumberParam('eventId'); this.eventId = CoreNavigator.getRouteNumberParam('eventId');
this.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || 0; this.courseId = CoreNavigator.getRouteNumberParam('courseId') || 0;
this.title = this.eventId ? 'addon.calendar.editevent' : 'addon.calendar.newevent'; this.title = this.eventId ? 'addon.calendar.editevent' : 'addon.calendar.newevent';
const timestamp = CoreNavigator.instance.getRouteNumberParam('timestamp'); const timestamp = CoreNavigator.getRouteNumberParam('timestamp');
const currentDate = CoreTimeUtils.instance.toDatetimeFormat(timestamp); const currentDate = CoreTimeUtils.toDatetimeFormat(timestamp);
this.form.addControl('timestart', this.fb.control(currentDate, Validators.required)); this.form.addControl('timestart', this.fb.control(currentDate, Validators.required));
this.form.addControl('timedurationuntil', this.fb.control(currentDate)); this.form.addControl('timedurationuntil', this.fb.control(currentDate));
this.form.addControl('courseid', this.fb.control(this.courseId)); this.form.addControl('courseid', this.fb.control(this.courseId));
this.fetchData().finally(() => { this.fetchData().finally(() => {
this.originalData = CoreUtils.instance.clone(this.form.value); this.originalData = CoreUtils.clone(this.form.value);
this.loaded = true; this.loaded = true;
}); });
} }
@ -156,29 +156,29 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
// Get access info. // Get access info.
try { try {
accessInfo = await AddonCalendar.instance.getAccessInformation(this.courseId); accessInfo = await AddonCalendar.getAccessInformation(this.courseId);
this.types = await AddonCalendar.instance.getAllowedEventTypes(this.courseId); this.types = await AddonCalendar.getAllowedEventTypes(this.courseId);
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
const eventTypes = AddonCalendarHelper.instance.getEventTypeOptions(this.types); const eventTypes = AddonCalendarHelper.getEventTypeOptions(this.types);
if (!eventTypes.length) { 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) { if (this.eventId && !this.gotEventData) {
// Editing an event, get the event data. Wait for sync first. // 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. // Do not block if the scope is already destroyed.
if (!this.isDestroyed && this.eventId) { if (!this.isDestroyed && this.eventId) {
CoreSync.instance.blockOperation(AddonCalendarProvider.COMPONENT, this.eventId); CoreSync.blockOperation(AddonCalendarProvider.COMPONENT, this.eventId);
} }
let eventForm: AddonCalendarEvent | AddonCalendarOfflineEventDBRecord | undefined; let eventForm: AddonCalendarEvent | AddonCalendarOfflineEventDBRecord | undefined;
// Get the event offline data if there's any. // Get the event offline data if there's any.
try { try {
eventForm = await AddonCalendarOffline.instance.getEvent(this.eventId!); eventForm = await AddonCalendarOffline.getEvent(this.eventId!);
this.hasOffline = true; this.hasOffline = true;
} catch { } catch {
@ -188,7 +188,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
if (this.eventId! > 0) { if (this.eventId! > 0) {
// It's an online event. get its data from server. // 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) { if (!eventForm) {
eventForm = event; // Use offline data first. eventForm = event; // Use offline data first.
@ -217,7 +217,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
promises.push(this.fetchCategories()); 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; accessInfo.canmanageentries;
if (this.types.course || this.types.groups) { if (this.types.course || this.types.groups) {
@ -236,18 +236,18 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
this.eventTypes = eventTypes; this.eventTypes = eventTypes;
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting data.'); CoreDomUtils.showErrorModalDefault(error, 'Error getting data.');
this.error = true; this.error = true;
} }
} }
protected async fetchCategories(): Promise<void> { protected async fetchCategories(): Promise<void> {
this.categories = await CoreCourses.instance.getCategories(0, true); this.categories = await CoreCourses.getCategories(0, true);
} }
protected async fetchCourses(): Promise<void> { protected async fetchCourses(): Promise<void> {
// Get the courses. // 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) { if (courses.length < 0) {
this.courses = []; this.courses = [];
@ -256,7 +256,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
} }
const courseFillterFullname = (course: CoreCourseSearchedData | CoreEnrolledCourseData): Promise<void> => const courseFillterFullname = (course: CoreCourseSearchedData | CoreEnrolledCourseData): Promise<void> =>
CoreFilterHelper.instance.getFiltersAndFormatText(course.fullname, 'course', course.id) CoreFilterHelper.getFiltersAndFormatText(course.fullname, 'course', course.id)
.then((result) => { .then((result) => {
course.fullname = result.text; course.fullname = result.text;
@ -268,7 +268,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
if (this.showAll) { if (this.showAll) {
// Remove site home from the list of courses. // Remove site home from the list of courses.
const siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); const siteHomeId = CoreSites.getCurrentSiteHomeId();
if ('contacts' in courses[0]) { if ('contacts' in courses[0]) {
courses = (courses as CoreCourseSearchedData[]).filter((course) => course.id != siteHomeId); 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; const courseId = isOffline ? offlineEvent.courseid : onlineEvent.course?.id;
this.form.controls.name.setValue(event.name); 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.eventtype.setValue(event.eventtype);
this.form.controls.categoryid.setValue(event.categoryid || ''); this.form.controls.categoryid.setValue(event.categoryid || '');
this.form.controls.courseid.setValue(courseId || ''); 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. // It's an offline event, use the data as it is.
this.form.controls.duration.setValue(offlineEvent.duration); this.form.controls.duration.setValue(offlineEvent.duration);
this.form.controls.timedurationuntil.setValue( 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.timedurationminutes.setValue(offlineEvent.timedurationminutes || '');
this.form.controls.repeat.setValue(!!offlineEvent.repeat); this.form.controls.repeat.setValue(!!offlineEvent.repeat);
@ -340,13 +340,13 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
if (onlineEvent.timeduration > 0) { if (onlineEvent.timeduration > 0) {
this.form.controls.duration.setValue(1); 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, (onlineEvent.timestart + onlineEvent.timeduration) * 1000,
)); ));
} else { } else {
// No duration. // No duration.
this.form.controls.duration.setValue(0); 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(''); this.form.controls.timedurationminutes.setValue('');
@ -367,19 +367,19 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
*/ */
refreshData(refresher?: CustomEvent<IonRefresher>): void { refreshData(refresher?: CustomEvent<IonRefresher>): void {
const promises = [ const promises = [
AddonCalendar.instance.invalidateAccessInformation(this.courseId), AddonCalendar.invalidateAccessInformation(this.courseId),
AddonCalendar.instance.invalidateAllowedEventTypes(this.courseId), AddonCalendar.invalidateAllowedEventTypes(this.courseId),
]; ];
if (this.types) { if (this.types) {
if (this.types.category) { 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.types.course || this.types.groups) {
if (this.showAll) { if (this.showAll) {
promises.push(CoreCourses.instance.invalidateCoursesByField()); promises.push(CoreCourses.invalidateCoursesByField());
} else { } else {
promises.push(CoreCourses.instance.invalidateUserCourses()); promises.push(CoreCourses.invalidateUserCourses());
} }
} }
} }
@ -401,14 +401,14 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
return; return;
} }
const modal = await CoreDomUtils.instance.showModalLoading(); const modal = await CoreDomUtils.showModalLoading();
try { try {
await this.loadGroups(courseId); await this.loadGroups(courseId);
this.groupControl.setValue(''); this.groupControl.setValue('');
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'Error getting data.'); CoreDomUtils.showErrorModalDefault(error, 'Error getting data.');
} }
modal.dismiss(); modal.dismiss();
@ -424,7 +424,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
this.loadingGroups = true; this.loadingGroups = true;
try { try {
this.groups = await CoreGroups.instance.getUserGroupsInCourse(courseId); this.groups = await CoreGroups.getUserGroupsInCourse(courseId);
this.courseGroupSet = true; this.courseGroupSet = true;
} finally { } finally {
this.loadingGroups = false; this.loadingGroups = false;
@ -448,8 +448,8 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
async submit(): Promise<void> { async submit(): Promise<void> {
// Validate data. // Validate data.
const formData = this.form.value; const formData = this.form.value;
const timeStartDate = CoreTimeUtils.instance.convertToTimestamp(formData.timestart); const timeStartDate = CoreTimeUtils.convertToTimestamp(formData.timestart);
const timeUntilDate = CoreTimeUtils.instance.convertToTimestamp(formData.timedurationuntil); const timeUntilDate = CoreTimeUtils.convertToTimestamp(formData.timedurationuntil);
const timeDurationMinutes = parseInt(formData.timedurationminutes || '', 10); const timeDurationMinutes = parseInt(formData.timedurationminutes || '', 10);
let error: string | undefined; let error: string | undefined;
@ -469,7 +469,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
if (error) { if (error) {
// Show error and stop. // Show error and stop.
CoreDomUtils.instance.showErrorModal(Translate.instance.instant(error)); CoreDomUtils.showErrorModal(Translate.instant(error));
return; return;
} }
@ -513,14 +513,14 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
} }
// Send the data. // Send the data.
const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); const modal = await CoreDomUtils.showModalLoading('core.sending', true);
let event: AddonCalendarEvent | AddonCalendarOfflineEventDBRecord; let event: AddonCalendarEvent | AddonCalendarOfflineEventDBRecord;
try { try {
const result = await AddonCalendar.instance.submitEvent(this.eventId, data); const result = await AddonCalendar.submitEvent(this.eventId, data);
event = result.event; 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) { if (result.sent) {
// Event created or edited, invalidate right days & months. // 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); (data.repeateditall && this.otherEventsCount ? this.otherEventsCount + 1 : 1);
try { try {
await AddonCalendarHelper.instance.refreshAfterChangeEvent(result.event, numberOfRepetitions); await AddonCalendarHelper.refreshAfterChangeEvent(result.event, numberOfRepetitions);
} catch { } catch {
// Ignore errors. // Ignore errors.
} }
@ -536,7 +536,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
this.returnToList(event); this.returnToList(event);
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'Error sending data.'); CoreDomUtils.showErrorModalDefault(error, 'Error sending data.');
} }
modal.dismiss(); modal.dismiss();
@ -574,10 +574,10 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
// Empty form. // Empty form.
this.hasOffline = false; this.hasOffline = false;
this.form.reset(this.originalData); this.form.reset(this.originalData);
this.originalData = CoreUtils.instance.clone(this.form.value); this.originalData = CoreUtils.clone(this.form.value);
} else { } else {
this.originalData = undefined; // Avoid asking for confirmation. 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<void> { async discard(): Promise<void> {
try { try {
await CoreDomUtils.instance.showConfirm(Translate.instance.instant('core.areyousure')); await CoreDomUtils.showConfirm(Translate.instant('core.areyousure'));
try { 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(); this.returnToList();
} catch { } catch {
// Shouldn't happen. // Shouldn't happen.
CoreDomUtils.instance.showErrorModal('Error discarding event.'); CoreDomUtils.showErrorModal('Error discarding event.');
} }
} catch { } catch {
// Ignore errors // Ignore errors
@ -608,12 +608,12 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy {
* @return Resolved if we can leave it, rejected if not. * @return Resolved if we can leave it, rejected if not.
*/ */
async ionViewCanLeave(): Promise<void> { async ionViewCanLeave(): Promise<void> {
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. // 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 { protected unblockSync(): void {
if (this.eventId) { if (this.eventId) {
CoreSync.instance.unblockOperation(AddonCalendarProvider.COMPONENT, this.eventId); CoreSync.unblockOperation(AddonCalendarProvider.COMPONENT, this.eventId);
} }
} }

View File

@ -93,14 +93,14 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
protected route: ActivatedRoute, protected route: ActivatedRoute,
) { ) {
this.notificationsEnabled = CoreLocalNotifications.instance.isAvailable(); this.notificationsEnabled = CoreLocalNotifications.isAvailable();
this.siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); this.siteHomeId = CoreSites.getCurrentSiteHomeId();
this.currentSiteId = CoreSites.instance.getCurrentSiteId(); this.currentSiteId = CoreSites.getCurrentSiteId();
this.isSplitViewOn = this.svComponent?.outletActivated; this.isSplitViewOn = this.svComponent?.outletActivated;
// Check if site supports editing and deleting. No need to check allowed types, event.canedit already does it. // Check if site supports editing and deleting. No need to check allowed types, event.canedit already does it.
this.canEdit = AddonCalendar.instance.canEditEventsInSite(); this.canEdit = AddonCalendar.canEditEventsInSite();
this.canDelete = AddonCalendar.instance.canDeleteEventsInSite(); this.canDelete = AddonCalendar.canDeleteEventsInSite();
this.asyncConstructor(); this.asyncConstructor();
@ -127,23 +127,23 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
); );
// Refresh online status when changes. // 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. // Execute the callback in the Angular zone, so change detection doesn't stop working.
NgZone.instance.run(() => { NgZone.run(() => {
this.isOnline = CoreApp.instance.isOnline(); this.isOnline = CoreApp.isOnline();
}); });
}); });
} }
protected async asyncConstructor(): Promise<void> { protected async asyncConstructor(): Promise<void> {
if (this.notificationsEnabled) { if (this.notificationsEnabled) {
this.reminders = await AddonCalendar.instance.getEventReminders(this.eventId); this.reminders = await AddonCalendar.getEventReminders(this.eventId);
this.defaultTime = await AddonCalendar.instance.getDefaultNotificationTime() * 60; this.defaultTime = await AddonCalendar.getDefaultNotificationTime() * 60;
// Calculate format to use. // Calculate format to use.
this.notificationFormat = this.notificationFormat =
CoreTimeUtils.instance.fixFormatForDatetime(CoreTimeUtils.instance.convertPHPToMoment( CoreTimeUtils.fixFormatForDatetime(CoreTimeUtils.convertPHPToMoment(
Translate.instance.instant('core.strftimedatetime'), Translate.instant('core.strftimedatetime'),
)); ));
} }
} }
@ -155,10 +155,10 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
this.route.queryParams.subscribe(() => { this.route.queryParams.subscribe(() => {
this.eventLoaded = false; this.eventLoaded = false;
const eventId = CoreNavigator.instance.getRouteNumberParam('id'); const eventId = CoreNavigator.getRouteNumberParam('id');
if (!eventId) { if (!eventId) {
CoreDomUtils.instance.showErrorModal('Event ID not supplied.'); CoreDomUtils.showErrorModal('Event ID not supplied.');
CoreNavigator.instance.back(); CoreNavigator.back();
return; return;
} }
@ -178,18 +178,18 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
* @return Promise resolved when done. * @return Promise resolved when done.
*/ */
async fetchEvent(sync = false, showErrors = false): Promise<void> { async fetchEvent(sync = false, showErrors = false): Promise<void> {
const currentSite = CoreSites.instance.getCurrentSite(); const currentSite = CoreSites.getCurrentSite();
const canGetById = AddonCalendar.instance.isGetEventByIdAvailableInSite(); const canGetById = AddonCalendar.isGetEventByIdAvailableInSite();
let deleted = false; let deleted = false;
this.isOnline = CoreApp.instance.isOnline(); this.isOnline = CoreApp.isOnline();
if (sync) { if (sync) {
// Try to synchronize offline events. // Try to synchronize offline events.
try { try {
const result = await AddonCalendarSync.instance.syncEvents(); const result = await AddonCalendarSync.syncEvents();
if (result.warnings && result.warnings.length) { 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) { if (result.deleted && result.deleted.indexOf(this.eventId) != -1) {
@ -209,7 +209,7 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
if (showErrors) { 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; let event: AddonCalendarEvent | AddonCalendarEventBase | AddonCalendarGetEventsEvent;
// Get the event data. // Get the event data.
if (canGetById) { if (canGetById) {
event = await AddonCalendar.instance.getEventById(this.eventId); event = await AddonCalendar.getEventById(this.eventId);
} else { } 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 { try {
const offlineEvent = AddonCalendarHelper.instance.formatOfflineEventData( const offlineEvent = AddonCalendarHelper.formatOfflineEventData(
await AddonCalendarOffline.instance.getEvent(this.eventId), await AddonCalendarOffline.getEvent(this.eventId),
); );
// There is offline data, apply it. // There is offline data, apply it.
@ -242,9 +242,9 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
this.hasOffline = false; this.hasOffline = false;
} }
this.currentTime = CoreTimeUtils.instance.timestamp(); this.currentTime = CoreTimeUtils.timestamp();
this.notificationMin = CoreTimeUtils.instance.userDate(this.currentTime * 1000, 'YYYY-MM-DDTHH:mm', false); this.notificationMin = CoreTimeUtils.userDate(this.currentTime * 1000, 'YYYY-MM-DDTHH:mm', false);
this.notificationMax = CoreTimeUtils.instance.userDate( this.notificationMax = CoreTimeUtils.userDate(
(this.event!.timestart + this.event!.timeduration) * 1000, (this.event!.timestart + this.event!.timeduration) * 1000,
'YYYY-MM-DDTHH:mm', 'YYYY-MM-DDTHH:mm',
false, false,
@ -258,7 +258,7 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
if (this.event!.moduleIcon) { if (this.event!.moduleIcon) {
// It's a module event, translate the module name to the current language. // 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) { if (name.indexOf('core.mod_') === -1) {
this.event!.modulename = name; this.event!.modulename = name;
} }
@ -280,10 +280,10 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
this.courseUrl = this.event.course.viewurl; this.courseUrl = this.event.course.viewurl;
} else if (!canGetById && this.event.courseid ) { } else if (!canGetById && this.event.courseid ) {
// Retrieve the course. // 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.courseId = course.id;
this.courseName = course.fullname; this.courseName = course.fullname;
this.courseUrl = currentSite ? CoreTextUtils.instance.concatenatePaths( this.courseUrl = currentSite ? CoreTextUtils.concatenatePaths(
currentSite.siteUrl, currentSite.siteUrl,
'/course/view.php?id=' + this.courseId, '/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 it's a group event, get the name of the group.
if (courseId && this.event.groupid) { 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); const group = groups.find((group) => group.id == this.event!.groupid);
this.groupName = group ? group.name : ''; this.groupName = group ? group.name : '';
@ -315,27 +315,27 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
if (this.event.location) { if (this.event.location) {
// Build a link to open the address in maps. // Build a link to open the address in maps.
this.event.location = CoreTextUtils.instance.decodeHTML(this.event.location); this.event.location = CoreTextUtils.decodeHTML(this.event.location);
this.event.encodedLocation = CoreTextUtils.instance.buildAddressURL(this.event.location); this.event.encodedLocation = CoreTextUtils.buildAddressURL(this.event.location);
} }
// Check if event was deleted in offine. // 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; this.event!.deleted = deleted;
return; return;
})); }));
// Re-calculate the formatted time so it uses the device date. // Re-calculate the formatted time so it uses the device date.
promises.push(AddonCalendar.instance.getCalendarTimeFormat().then(async (timeFormat) => { promises.push(AddonCalendar.getCalendarTimeFormat().then(async (timeFormat) => {
this.event!.formattedtime = await AddonCalendar.instance.formatEventTime(this.event!, timeFormat); this.event!.formattedtime = await AddonCalendar.formatEventTime(this.event!, timeFormat);
return; return;
})); }));
await Promise.all(promises); await Promise.all(promises);
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevent', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevent', true);
} }
this.eventLoaded = true; this.eventLoaded = true;
@ -347,9 +347,9 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
*/ */
async addNotificationTime(): Promise<void> { async addNotificationTime(): Promise<void> {
if (this.notificationTimeText && this.event && this.event.id) { 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; 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. // 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; notificationTime = currentTime + 1;
} }
await AddonCalendar.instance.addEventReminder(this.event, notificationTime); await AddonCalendar.addEventReminder(this.event, notificationTime);
this.reminders = await AddonCalendar.instance.getEventReminders(this.eventId); this.reminders = await AddonCalendar.getEventReminders(this.eventId);
this.notificationTimeText = undefined; this.notificationTimeText = undefined;
} }
} }
@ -374,15 +374,15 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
e.stopPropagation(); e.stopPropagation();
try { 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 { try {
await AddonCalendar.instance.deleteEventReminder(id); await AddonCalendar.deleteEventReminder(id);
this.reminders = await AddonCalendar.instance.getEventReminders(this.eventId); this.reminders = await AddonCalendar.getEventReminders(this.eventId);
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'Error deleting reminder'); CoreDomUtils.showErrorModalDefault(error, 'Error deleting reminder');
} finally { } finally {
modal.dismiss(); modal.dismiss();
} }
@ -422,10 +422,10 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
promises.push(AddonCalendar.instance.invalidateEvent(this.eventId)); promises.push(AddonCalendar.invalidateEvent(this.eventId));
promises.push(AddonCalendar.instance.invalidateTimeFormat()); promises.push(AddonCalendar.invalidateTimeFormat());
await CoreUtils.instance.allPromisesIgnoringErrors(promises); await CoreUtils.allPromisesIgnoringErrors(promises);
await this.fetchEvent(sync, showErrors); await this.fetchEvent(sync, showErrors);
} }
@ -436,7 +436,7 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
openEdit(): void { openEdit(): void {
// Decide which navCtrl to use. If this page is inside a split view, use the split view's master nav. // 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; // @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; return;
} }
const title = Translate.instance.instant('addon.calendar.deleteevent'); const title = Translate.instant('addon.calendar.deleteevent');
const options: AlertOptions = {}; const options: AlertOptions = {};
let message: string; let message: string;
if (this.event.eventcount > 1) { if (this.event.eventcount > 1) {
// It's a repeated event. // It's a repeated event.
message = Translate.instance.instant( message = Translate.instant(
'addon.calendar.confirmeventseriesdelete', 'addon.calendar.confirmeventseriesdelete',
{ $a: { name: this.event.name, count: this.event.eventcount } }, { $a: { name: this.event.name, count: this.event.eventcount } },
); );
@ -464,39 +464,39 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
name: 'deleteall', name: 'deleteall',
checked: true, checked: true,
value: false, value: false,
label: Translate.instance.instant('addon.calendar.deleteoneevent'), label: Translate.instant('addon.calendar.deleteoneevent'),
}, },
{ {
type: 'radio', type: 'radio',
name: 'deleteall', name: 'deleteall',
checked: false, checked: false,
value: true, value: true,
label: Translate.instance.instant('addon.calendar.deleteallevents'), label: Translate.instant('addon.calendar.deleteallevents'),
}, },
]; ];
} else { } else {
// Not repeated, display a simple confirm. // 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; let deleteAll = false;
try { try {
deleteAll = await CoreDomUtils.instance.showConfirm(message, title, undefined, undefined, options); deleteAll = await CoreDomUtils.showConfirm(message, title, undefined, undefined, options);
} catch { } catch {
// User canceled. // User canceled.
return; return;
} }
const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); const modal = await CoreDomUtils.showModalLoading('core.sending', true);
try { 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) { if (sent) {
// Event deleted, invalidate right days & months. // Event deleted, invalidate right days & months.
try { try {
await AddonCalendarHelper.instance.refreshAfterChangeEvent(this.event, deleteAll ? this.event.eventcount : 1); await AddonCalendarHelper.refreshAfterChangeEvent(this.event, deleteAll ? this.event.eventcount : 1);
} catch { } catch {
// Ignore errors. // Ignore errors.
} }
@ -506,21 +506,21 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
CoreEvents.trigger<AddonCalendarUpdatedEventEvent>(AddonCalendarProvider.DELETED_EVENT_EVENT, { CoreEvents.trigger<AddonCalendarUpdatedEventEvent>(AddonCalendarProvider.DELETED_EVENT_EVENT, {
eventId: this.eventId, eventId: this.eventId,
sent: sent, sent: sent,
}, CoreSites.instance.getCurrentSiteId()); }, CoreSites.getCurrentSiteId());
if (sent) { if (sent) {
CoreDomUtils.instance.showToast('addon.calendar.eventcalendareventdeleted', true, 3000); CoreDomUtils.showToast('addon.calendar.eventcalendareventdeleted', true, 3000);
// Event deleted, close the view. // Event deleted, close the view.
if (CoreScreen.instance.isMobile) { if (CoreScreen.isMobile) {
CoreNavigator.instance.back(); CoreNavigator.back();
} }
} else { } else {
// Event deleted in offline, just mark it as deleted. // Event deleted in offline, just mark it as deleted.
this.event.deleted = true; this.event.deleted = true;
} }
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'Error deleting event.'); CoreDomUtils.showErrorModalDefault(error, 'Error deleting event.');
} }
modal.dismiss(); modal.dismiss();
@ -534,21 +534,21 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
return; return;
} }
const modal = await CoreDomUtils.instance.showModalLoading('core.sending', true); const modal = await CoreDomUtils.showModalLoading('core.sending', true);
try { try {
await AddonCalendarOffline.instance.unmarkDeleted(this.event.id); await AddonCalendarOffline.unmarkDeleted(this.event.id);
// Trigger an event. // Trigger an event.
CoreEvents.trigger<AddonCalendarUpdatedEventEvent>(AddonCalendarProvider.UNDELETED_EVENT_EVENT, { CoreEvents.trigger<AddonCalendarUpdatedEventEvent>(AddonCalendarProvider.UNDELETED_EVENT_EVENT, {
eventId: this.eventId, eventId: this.eventId,
}, CoreSites.instance.getCurrentSiteId()); }, CoreSites.getCurrentSiteId());
this.event.deleted = false; this.event.deleted = false;
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'Error undeleting event.'); CoreDomUtils.showErrorModalDefault(error, 'Error undeleting event.');
} }
modal.dismiss(); modal.dismiss();
@ -566,11 +566,11 @@ export class AddonCalendarEventPage implements OnInit, OnDestroy {
} }
if (data.deleted && data.deleted.indexOf(this.eventId) != -1) { 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. // Event was deleted, close the view.
if (CoreScreen.instance.isMobile) { if (CoreScreen.isMobile) {
CoreNavigator.instance.back(); CoreNavigator.back();
} }
} else if (data.events && (!isManual || data.source != 'event')) { } else if (data.events && (!isManual || data.source != 'event')) {
const event = data.events.find((ev) => ev.id == this.eventId); const event = data.events.find((ev) => ev.id == this.eventId);

View File

@ -86,7 +86,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy {
constructor( constructor(
protected route: ActivatedRoute, protected route: ActivatedRoute,
) { ) {
this.currentSiteId = CoreSites.instance.getCurrentSiteId(); this.currentSiteId = CoreSites.getCurrentSiteId();
// Listen for events added. When an event is added, reload the data. // Listen for events added. When an event is added, reload the data.
this.newEventObserver = CoreEvents.on<AddonCalendarUpdatedEventEvent>( this.newEventObserver = CoreEvents.on<AddonCalendarUpdatedEventEvent>(
@ -140,7 +140,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy {
// Update the "hasOffline" property if an event deleted in offline is restored. // Update the "hasOffline" property if an event deleted in offline is restored.
this.undeleteEventObserver = CoreEvents.on(AddonCalendarProvider.UNDELETED_EVENT_EVENT, async () => { this.undeleteEventObserver = CoreEvents.on(AddonCalendarProvider.UNDELETED_EVENT_EVENT, async () => {
this.hasOffline = await AddonCalendarOffline.instance.hasOfflineData(); this.hasOffline = await AddonCalendarOffline.hasOfflineData();
}, this.currentSiteId); }, this.currentSiteId);
this.filterChangedObserver = CoreEvents.on<AddonCalendarFilter>( this.filterChangedObserver = CoreEvents.on<AddonCalendarFilter>(
@ -149,15 +149,15 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy {
this.filter = filterData; this.filter = filterData;
// Course viewed has changed, check if the user can create events for this course calendar. // 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. // 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. // Execute the callback in the Angular zone, so change detection doesn't stop working.
NgZone.instance.run(() => { NgZone.run(() => {
this.isOnline = CoreApp.instance.isOnline(); this.isOnline = CoreApp.isOnline();
}); });
}); });
} }
@ -166,14 +166,14 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy {
* View loaded. * View loaded.
*/ */
ngOnInit(): void { ngOnInit(): void {
this.notificationsEnabled = CoreLocalNotifications.instance.isAvailable(); this.notificationsEnabled = CoreLocalNotifications.isAvailable();
this.route.queryParams.subscribe(() => { this.route.queryParams.subscribe(() => {
this.eventId = CoreNavigator.instance.getRouteNumberParam('eventId'); this.eventId = CoreNavigator.getRouteNumberParam('eventId');
this.filter.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || -1; this.filter.courseId = CoreNavigator.getRouteNumberParam('courseId') || -1;
this.year = CoreNavigator.instance.getRouteNumberParam('year'); this.year = CoreNavigator.getRouteNumberParam('year');
this.month = CoreNavigator.instance.getRouteNumberParam('month'); this.month = CoreNavigator.getRouteNumberParam('month');
this.loadUpcoming = !!CoreNavigator.instance.getRouteBooleanParam('upcoming'); this.loadUpcoming = !!CoreNavigator.getRouteBooleanParam('upcoming');
this.showCalendar = !this.loadUpcoming; this.showCalendar = !this.loadUpcoming;
this.filter.filtered = this.filter.courseId > 0; this.filter.filtered = this.filter.courseId > 0;
@ -196,14 +196,14 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy {
async fetchData(sync?: boolean, showErrors?: boolean): Promise<void> { async fetchData(sync?: boolean, showErrors?: boolean): Promise<void> {
this.syncIcon = CoreConstants.ICON_LOADING; this.syncIcon = CoreConstants.ICON_LOADING;
this.isOnline = CoreApp.instance.isOnline(); this.isOnline = CoreApp.isOnline();
if (sync) { if (sync) {
// Try to synchronize offline events. // Try to synchronize offline events.
try { try {
const result = await AddonCalendarSync.instance.syncEvents(); const result = await AddonCalendarSync.syncEvents();
if (result.warnings && result.warnings.length) { if (result.warnings && result.warnings.length) {
CoreDomUtils.instance.showErrorModal(result.warnings[0]); CoreDomUtils.showErrorModal(result.warnings[0]);
} }
if (result.updated) { if (result.updated) {
@ -218,7 +218,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
if (showErrors) { 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; this.hasOffline = false;
// Load courses for the popover. // 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; this.courses = data.courses;
return; return;
})); }));
// Check if user can create events. // 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; this.canCreate = canEdit;
return; return;
})); }));
// Check if there is offline data. // Check if there is offline data.
promises.push(AddonCalendarOffline.instance.hasOfflineData().then((hasOffline) => { promises.push(AddonCalendarOffline.hasOfflineData().then((hasOffline) => {
this.hasOffline = hasOffline; this.hasOffline = hasOffline;
return; return;
@ -251,7 +251,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy {
await Promise.all(promises); await Promise.all(promises);
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
} }
this.loaded = true; this.loaded = true;
@ -290,7 +290,7 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy {
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
promises.push(AddonCalendar.instance.invalidateAllowedEventTypes()); promises.push(AddonCalendar.invalidateAllowedEventTypes());
// Refresh the sub-component. // Refresh the sub-component.
if (this.showCalendar && this.calendarComponent) { 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. // It's an offline event, go to the edit page.
this.openEdit(eventId); this.openEdit(eventId);
} else { } 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]; 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. * @param event Event.
*/ */
async openFilter(event: MouseEvent): Promise<void> { async openFilter(event: MouseEvent): Promise<void> {
const popover = await PopoverController.instance.create({ const popover = await PopoverController.create({
component: AddonCalendarFilterPopoverComponent, component: AddonCalendarFilterPopoverComponent,
componentProps: { componentProps: {
courses: this.courses, courses: this.courses,
@ -367,14 +367,14 @@ export class AddonCalendarIndexPage implements OnInit, OnDestroy {
params.courseId = this.filter.courseId; params.courseId = this.filter.courseId;
} }
CoreNavigator.instance.navigateToSitePath('/calendar/edit', { params }); CoreNavigator.navigateToSitePath('/calendar/edit', { params });
} }
/** /**
* Open calendar events settings. * Open calendar events settings.
*/ */
openSettings(): void { openSettings(): void {
CoreNavigator.instance.navigateToSitePath('/calendar/settings'); CoreNavigator.navigateToSitePath('/calendar/settings');
} }
/** /**

View File

@ -43,8 +43,8 @@ const tabletRoutes: Routes = [
]; ];
const routes: Routes = [ const routes: Routes = [
...conditionalRoutes(mobileRoutes, () => CoreScreen.instance.isMobile), ...conditionalRoutes(mobileRoutes, () => CoreScreen.isMobile),
...conditionalRoutes(tabletRoutes, () => CoreScreen.instance.isTablet), ...conditionalRoutes(tabletRoutes, () => CoreScreen.isTablet),
]; ];

View File

@ -103,14 +103,14 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
constructor() { constructor() {
this.siteHomeId = CoreSites.instance.getCurrentSiteHomeId(); this.siteHomeId = CoreSites.getCurrentSiteHomeId();
this.notificationsEnabled = CoreLocalNotifications.instance.isAvailable(); this.notificationsEnabled = CoreLocalNotifications.isAvailable();
this.currentSiteId = CoreSites.instance.getCurrentSiteId(); this.currentSiteId = CoreSites.getCurrentSiteId();
if (this.notificationsEnabled) { if (this.notificationsEnabled) {
// Re-schedule events if default time changes. // Re-schedule events if default time changes.
this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => { this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => {
AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); AddonCalendar.scheduleEventsNotifications(this.onlineEvents);
}, this.currentSiteId); }, this.currentSiteId);
} }
@ -225,7 +225,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
this.filter = data; this.filter = data;
// Course viewed has changed, check if the user can create events for this course calendar. // 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(); this.filterEvents();
@ -233,10 +233,10 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
}); });
// Refresh online status when changes. // 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. // Execute the callback in the Angular zone, so change detection doesn't stop working.
NgZone.instance.run(() => { NgZone.run(() => {
this.isOnline = CoreApp.instance.isOnline(); this.isOnline = CoreApp.isOnline();
}); });
}); });
} }
@ -245,8 +245,8 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
* View loaded. * View loaded.
*/ */
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
this.eventId = CoreNavigator.instance.getRouteNumberParam('eventId'); this.eventId = CoreNavigator.getRouteNumberParam('eventId');
this.filter.courseId = CoreNavigator.instance.getRouteNumberParam('courseId') || -1; this.filter.courseId = CoreNavigator.getRouteNumberParam('courseId') || -1;
if (this.eventId) { if (this.eventId) {
// There is an event to load, open the event in a new state. // 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 { protected emptySplitView(): void {
// Empty details. // Empty details.
const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/event') || const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/calendar/list/event') ||
CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/edit'); CoreNavigator.isCurrentPathInTablet('**/calendar/list/edit');
if (splitViewLoaded) { if (splitViewLoaded) {
CoreNavigator.instance.navigate('../'); CoreNavigator.navigate('../');
} }
} }
@ -288,17 +288,17 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
* @return Promise resolved when done. * @return Promise resolved when done.
*/ */
async fetchData(refresh = false, sync = false, showErrors = false): Promise<void> { async fetchData(refresh = false, sync = false, showErrors = false): Promise<void> {
this.initialTime = CoreTimeUtils.instance.timestamp(); this.initialTime = CoreTimeUtils.timestamp();
this.daysLoaded = 0; this.daysLoaded = 0;
this.emptyEventsTimes = 0; this.emptyEventsTimes = 0;
this.isOnline = CoreApp.instance.isOnline(); this.isOnline = CoreApp.isOnline();
if (sync) { if (sync) {
// Try to synchronize offline events. // Try to synchronize offline events.
try { try {
const result = await AddonCalendarSync.instance.syncEvents(); const result = await AddonCalendarSync.syncEvents();
if (result.warnings && result.warnings.length) { if (result.warnings && result.warnings.length) {
CoreDomUtils.instance.showErrorModal(result.warnings[0]); CoreDomUtils.showErrorModal(result.warnings[0]);
} }
if (result.updated) { if (result.updated) {
@ -313,7 +313,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
} }
} catch (error) { } catch (error) {
if (showErrors) { 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; 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; this.canCreate = canEdit;
return; return;
})); }));
// Load courses for the popover. // 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; this.courses = result.courses;
return this.fetchEvents(refresh); return this.fetchEvents(refresh);
})); }));
// Get offline events. // Get offline events.
promises.push(AddonCalendarOffline.instance.getAllEditedEvents().then((offlineEvents) => { promises.push(AddonCalendarOffline.getAllEditedEvents().then((offlineEvents) => {
this.hasOffline = this.hasOffline || !!offlineEvents.length; this.hasOffline = this.hasOffline || !!offlineEvents.length;
// Format data and sort by timestart. // Format data and sort by timestart.
const events: AddonCalendarEventToDisplay[] = offlineEvents.map((event) => 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; return;
})); }));
// Get events deleted in offline. // 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.hasOffline = this.hasOffline || !!ids.length;
this.deletedEvents = ids; this.deletedEvents = ids;
@ -359,7 +359,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
await Promise.all(promises); await Promise.all(promises);
} catch (error) { } catch (error) {
CoreDomUtils.instance.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true);
} }
this.eventsLoaded = true; this.eventsLoaded = true;
@ -377,7 +377,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
try { try {
const onlineEventsTemp = 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) { if (onlineEventsTemp.length === 0) {
this.emptyEventsTimes++; this.emptyEventsTimes++;
@ -395,7 +395,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
return this.fetchEvents(); return this.fetchEvents();
} }
} else { } 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. // Get the merged events of this period.
const events = this.mergeEvents(onlineEvents); const events = this.mergeEvents(onlineEvents);
@ -407,8 +407,8 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
this.events = events; this.events = events;
} else { } else {
// Filter events with same ID. Repeated events are returned once per WS call, show them only once. // 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.onlineEvents = CoreUtils.mergeArraysWithoutDuplicates(this.onlineEvents, onlineEvents, 'id');
this.events = CoreUtils.instance.mergeArraysWithoutDuplicates(this.events, events, 'id'); this.events = CoreUtils.mergeArraysWithoutDuplicates(this.events, events, 'id');
} }
this.filterEvents(); this.filterEvents();
@ -420,7 +420,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
this.canLoadMore = true; this.canLoadMore = true;
// Schedule notifications for the events retrieved (might have new events). // Schedule notifications for the events retrieved (might have new events).
AddonCalendar.instance.scheduleEventsNotifications(this.onlineEvents); AddonCalendar.scheduleEventsNotifications(this.onlineEvents);
this.daysLoaded += AddonCalendarProvider.DAYS_INTERVAL; 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. // @todo: Infinite loading is not working if content is not high enough.
// this.content.resize(); // this.content.resize();
} catch (error) { } 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. this.loadMoreError = true; // Set to prevent infinite calls with infinite-loading.
} }
@ -454,7 +454,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
} }
protected filterEvents(): void { 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<void> { protected async loadCategories(): Promise<void> {
try { try {
const cats = await CoreCourses.instance.getCategories(0, true); const cats = await CoreCourses.getCategories(0, true);
this.categoriesRetrieved = true; this.categoriesRetrieved = true;
this.categories = {}; this.categories = {};
// Index categories by ID. // Index categories by ID.
@ -539,7 +539,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
// Merge both arrays and sort them. // Merge both arrays and sort them.
result = result.concat(periodOfflineEvents); 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<void>[] = []; const promises: Promise<void>[] = [];
promises.push(AddonCalendar.instance.invalidateEventsList()); promises.push(AddonCalendar.invalidateEventsList());
promises.push(AddonCalendar.instance.invalidateAllowedEventTypes()); promises.push(AddonCalendar.invalidateAllowedEventTypes());
if (this.categoriesRetrieved) { if (this.categoriesRetrieved) {
promises.push(CoreCourses.instance.invalidateCategories(0, true)); promises.push(CoreCourses.invalidateCategories(0, true));
this.categoriesRetrieved = false; this.categoriesRetrieved = false;
} }
@ -624,7 +624,7 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
* @param event Event. * @param event Event.
*/ */
async openFilter(event: MouseEvent): Promise<void> { async openFilter(event: MouseEvent): Promise<void> {
const popover = await PopoverController.instance.create({ const popover = await PopoverController.create({
component: AddonCalendarFilterPopoverComponent, component: AddonCalendarFilterPopoverComponent,
componentProps: { componentProps: {
courses: this.courses, courses: this.courses,
@ -652,17 +652,17 @@ export class AddonCalendarListPage implements OnInit, OnDestroy {
params.courseId = this.filter.courseId; params.courseId = this.filter.courseId;
} }
const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/event') || const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/calendar/list/event') ||
CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/edit'); CoreNavigator.isCurrentPathInTablet('**/calendar/list/edit');
const path = (splitViewLoaded ? '../' : '') + 'edit'; const path = (splitViewLoaded ? '../' : '') + 'edit';
CoreNavigator.instance.navigate(path, { params }); CoreNavigator.navigate(path, { params });
} }
/** /**
* Open calendar events settings. * Open calendar events settings.
*/ */
openSettings(): void { 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. // It's an offline event, go to the edit page.
this.openEdit(eventId); this.openEdit(eventId);
} else { } else {
const splitViewLoaded = CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/event') || const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/calendar/list/event') ||
CoreNavigator.instance.isCurrentPathInTablet('**/calendar/list/edit'); CoreNavigator.isCurrentPathInTablet('**/calendar/list/edit');
const path = (splitViewLoaded ? '../' : '') + 'event'; const path = (splitViewLoaded ? '../' : '') + 'event';
CoreNavigator.instance.navigate(path, { params: { CoreNavigator.navigate(path, { params: {
id: eventId, id: eventId,
} }); } });
} }

View File

@ -32,7 +32,7 @@ export class AddonCalendarSettingsPage implements OnInit {
* View loaded. * View loaded.
*/ */
async ngOnInit(): Promise<void> { async ngOnInit(): Promise<void> {
this.defaultTime = await AddonCalendar.instance.getDefaultNotificationTime(); this.defaultTime = await AddonCalendar.getDefaultNotificationTime();
} }
/** /**
@ -41,12 +41,12 @@ export class AddonCalendarSettingsPage implements OnInit {
* @param newTime New time. * @param newTime New time.
*/ */
updateDefaultTime(newTime: number): void { updateDefaultTime(newTime: number): void {
AddonCalendar.instance.setDefaultNotificationTime(newTime); AddonCalendar.setDefaultNotificationTime(newTime);
CoreEvents.trigger( CoreEvents.trigger(
AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED,
{ time: newTime }, { time: newTime },
CoreSites.instance.getCurrentSiteId(), CoreSites.getCurrentSiteId(),
); );
} }

View File

@ -64,7 +64,7 @@ export class AddonCalendarHelperProvider {
*/ */
getEventIcon(eventType: AddonCalendarEventType): string { getEventIcon(eventType: AddonCalendarEventType): string {
if (this.eventTypeIcons.length == 0) { if (this.eventTypeIcons.length == 0) {
CoreUtils.instance.enumKeys(AddonCalendarEventType).forEach((name) => { CoreUtils.enumKeys(AddonCalendarEventType).forEach((name) => {
const value = AddonCalendarEventType[name]; const value = AddonCalendarEventType[name];
this.eventTypeIcons[value] = AddonCalendarEventIcons[name]; this.eventTypeIcons[value] = AddonCalendarEventIcons[name];
}); });
@ -104,12 +104,12 @@ export class AddonCalendarHelperProvider {
*/ */
async canEditEvents(courseId?: number, siteId?: string): Promise<boolean> { async canEditEvents(courseId?: number, siteId?: string): Promise<boolean> {
try { try {
const canEdit = await AddonCalendar.instance.canEditEvents(siteId); const canEdit = await AddonCalendar.canEditEvents(siteId);
if (!canEdit) { if (!canEdit) {
return false; return false;
} }
const types = await AddonCalendar.instance.getAllowedEventTypes(courseId, siteId); const types = await AddonCalendar.getAllowedEventTypes(courseId, siteId);
return Object.keys(types).length > 0; return Object.keys(types).length > 0;
} catch { } catch {
@ -129,7 +129,7 @@ export class AddonCalendarHelperProvider {
): { [monthId: string]: { [day: number]: AddonCalendarEventToDisplay[] } } { ): { [monthId: string]: { [day: number]: AddonCalendarEventToDisplay[] } } {
// Format data. // Format data.
const events: AddonCalendarEventToDisplay[] = offlineEvents.map((event) => const events: AddonCalendarEventToDisplay[] = offlineEvents.map((event) =>
AddonCalendarHelper.instance.formatOfflineEventData(event)); AddonCalendarHelper.formatOfflineEventData(event));
const result = {}; const result = {};
@ -180,7 +180,7 @@ export class AddonCalendarHelperProvider {
userid: event.userid, userid: event.userid,
timemodified: event.timemodified, timemodified: event.timemodified,
eventIcon: this.getEventIcon(event.eventtype), eventIcon: this.getEventIcon(event.eventtype),
formattedType: AddonCalendar.instance.getEventType(event), formattedType: AddonCalendar.getEventType(event),
modulename: event.modulename, modulename: event.modulename,
format: 1, format: 1,
visible: 1, visible: 1,
@ -188,11 +188,11 @@ export class AddonCalendarHelperProvider {
}; };
if (event.modulename) { if (event.modulename) {
eventFormatted.eventIcon = CoreCourse.instance.getModuleIconSrc(event.modulename); eventFormatted.eventIcon = CoreCourse.getModuleIconSrc(event.modulename);
eventFormatted.moduleIcon = eventFormatted.eventIcon; eventFormatted.moduleIcon = eventFormatted.eventIcon;
} }
eventFormatted.formattedType = AddonCalendar.instance.getEventType(event); eventFormatted.formattedType = AddonCalendar.getEventType(event);
// Calculate context. // Calculate context.
if ('course' in event) { if ('course' in event) {
@ -345,10 +345,10 @@ export class AddonCalendarHelperProvider {
month: number, month: number,
siteId?: string, siteId?: string,
): Promise<{ daynames: Partial<AddonCalendarDayName>[]; weeks: Partial<AddonCalendarWeek>[] }> { ): Promise<{ daynames: Partial<AddonCalendarDayName>[]; weeks: Partial<AddonCalendarWeek>[] }> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
// Get starting week day user preference, fallback to site configuration. // Get starting week day user preference, fallback to site configuration.
let startWeekDayStr = site.getStoredConfig('calendar_startwday'); 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 startWeekDay = parseInt(startWeekDayStr, 10);
const today = moment(); const today = moment();
@ -531,7 +531,7 @@ export class AddonCalendarHelperProvider {
const eventCourse = (event.course && event.course.id) || event.courseid; 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. // 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. * @return Resolved when done.
*/ */
async refreshAfterChangeEvents(events: AddonCalendarSyncInvalidateEvent[], siteId?: string): Promise<void> { async refreshAfterChangeEvents(events: AddonCalendarSyncInvalidateEvent[], siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const fetchTimestarts: number[] = []; const fetchTimestarts: number[] = [];
const invalidateTimestarts: number[] = []; const invalidateTimestarts: number[] = [];
const promises: Promise<unknown>[] = []; const promises: Promise<unknown>[] = [];
// Always fetch upcoming events. // 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) => { promises.concat(events.map(async (eventData) => {
@ -557,7 +557,7 @@ export class AddonCalendarHelperProvider {
// Not repeated. // Not repeated.
fetchTimestarts.push(eventData.timestart); fetchTimestarts.push(eventData.timestart);
return AddonCalendar.instance.invalidateEvent(eventData.id); return AddonCalendar.invalidateEvent(eventData.id);
} }
if (eventData.repeatid) { if (eventData.repeatid) {
@ -573,10 +573,10 @@ export class AddonCalendarHelperProvider {
// Get the repeated events to invalidate them. // Get the repeated events to invalidate them.
const repeatedEvents = const repeatedEvents =
await AddonCalendar.instance.getLocalEventsByRepeatIdFromLocalDb(eventData.repeatid, site.id); await AddonCalendar.getLocalEventsByRepeatIdFromLocalDb(eventData.repeatid, site.id);
await CoreUtils.instance.allPromises(repeatedEvents.map((event) => await CoreUtils.allPromises(repeatedEvents.map((event) =>
AddonCalendar.instance.invalidateEvent(event.id!))); AddonCalendar.invalidateEvent(event.id!)));
return; return;
} }
@ -596,11 +596,11 @@ export class AddonCalendarHelperProvider {
})); }));
try { try {
await CoreUtils.instance.allPromisesIgnoringErrors(promises); await CoreUtils.allPromisesIgnoringErrors(promises);
} finally { } finally {
const treatedMonths = {}; const treatedMonths = {};
const treatedDays = {}; const treatedDays = {};
const finalPromises: Promise<unknown>[] =[AddonCalendar.instance.invalidateAllUpcomingEvents()]; const finalPromises: Promise<unknown>[] =[AddonCalendar.invalidateAllUpcomingEvents()];
// Fetch months and days. // Fetch months and days.
fetchTimestarts.map((fetchTime) => { fetchTimestarts.map((fetchTime) => {
@ -611,7 +611,7 @@ export class AddonCalendarHelperProvider {
// Month not refetch or invalidated already, do it now. // Month not refetch or invalidated already, do it now.
treatedMonths[monthId] = true; treatedMonths[monthId] = true;
finalPromises.push(AddonCalendar.instance.getMonthlyEvents( finalPromises.push(AddonCalendar.getMonthlyEvents(
day.year(), day.year(),
day.month() + 1, day.month() + 1,
undefined, undefined,
@ -626,7 +626,7 @@ export class AddonCalendarHelperProvider {
// Dat not refetch or invalidated already, do it now. // Dat not refetch or invalidated already, do it now.
treatedDays[dayId] = true; treatedDays[dayId] = true;
finalPromises.push(AddonCalendar.instance.getDayEvents( finalPromises.push(AddonCalendar.getDayEvents(
day.year(), day.year(),
day.month() + 1, day.month() + 1,
day.date(), day.date(),
@ -647,7 +647,7 @@ export class AddonCalendarHelperProvider {
// Month not refetch or invalidated already, do it now. // Month not refetch or invalidated already, do it now.
treatedMonths[monthId] = true; 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(); const dayId = monthId + '#' + day.date();
@ -655,7 +655,7 @@ export class AddonCalendarHelperProvider {
// Dat not refetch or invalidated already, do it now. // Dat not refetch or invalidated already, do it now.
treatedDays[dayId] = true; treatedDays[dayId] = true;
finalPromises.push(AddonCalendar.instance.invalidateDayEvents( finalPromises.push(AddonCalendar.invalidateDayEvents(
day.year(), day.year(),
day.month() + 1, day.month() + 1,
day.date(), 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. * Calculated data for Calendar filtering.

View File

@ -39,7 +39,7 @@ export class AddonCalendarOfflineProvider {
* @return Promise resolved if deleted, rejected if failure. * @return Promise resolved if deleted, rejected if failure.
*/ */
async deleteEvent(eventId: number, siteId?: string): Promise<void> { async deleteEvent(eventId: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const conditions: SQLiteDBRecordValues = { const conditions: SQLiteDBRecordValues = {
id: eventId, id: eventId,
@ -62,7 +62,7 @@ export class AddonCalendarOfflineProvider {
const result = await Promise.all(promises); 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. * @return Promise resolved with all the events deleted in offline.
*/ */
async getAllDeletedEvents(siteId?: string): Promise<AddonCalendarOfflineDeletedEventDBRecord[]> { async getAllDeletedEvents(siteId?: string): Promise<AddonCalendarOfflineDeletedEventDBRecord[]> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return await site.getDb().getRecords(DELETED_EVENTS_TABLE); return await site.getDb().getRecords(DELETED_EVENTS_TABLE);
} }
@ -96,7 +96,7 @@ export class AddonCalendarOfflineProvider {
* @return Promise resolved with events. * @return Promise resolved with events.
*/ */
async getAllEditedEvents(siteId?: string): Promise<AddonCalendarOfflineEventDBRecord[]> { async getAllEditedEvents(siteId?: string): Promise<AddonCalendarOfflineEventDBRecord[]> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return await site.getDb().getRecords(EVENTS_TABLE); return await site.getDb().getRecords(EVENTS_TABLE);
} }
@ -121,7 +121,7 @@ export class AddonCalendarOfflineProvider {
* @return Promise resolved with the deleted event. * @return Promise resolved with the deleted event.
*/ */
async getDeletedEvent(eventId: number, siteId?: string): Promise<AddonCalendarOfflineDeletedEventDBRecord> { async getDeletedEvent(eventId: number, siteId?: string): Promise<AddonCalendarOfflineDeletedEventDBRecord> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const conditions: SQLiteDBRecordValues = { const conditions: SQLiteDBRecordValues = {
id: eventId, id: eventId,
}; };
@ -137,7 +137,7 @@ export class AddonCalendarOfflineProvider {
* @return Promise resolved with the event. * @return Promise resolved with the event.
*/ */
async getEvent(eventId: number, siteId?: string): Promise<AddonCalendarOfflineEventDBRecord> { async getEvent(eventId: number, siteId?: string): Promise<AddonCalendarOfflineEventDBRecord> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const conditions: SQLiteDBRecordValues = { const conditions: SQLiteDBRecordValues = {
id: eventId, id: eventId,
}; };
@ -201,7 +201,7 @@ export class AddonCalendarOfflineProvider {
* @return Promise resolved when done. * @return Promise resolved when done.
*/ */
async markDeleted(eventId: number, name: string, deleteAll?: boolean, siteId?: string): Promise<number> { async markDeleted(eventId: number, name: string, deleteAll?: boolean, siteId?: string): Promise<number> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const event: AddonCalendarOfflineDeletedEventDBRecord = { const event: AddonCalendarOfflineDeletedEventDBRecord = {
id: eventId, id: eventId,
name: name || '', name: name || '',
@ -227,7 +227,7 @@ export class AddonCalendarOfflineProvider {
timeCreated?: number, timeCreated?: number,
siteId?: string, siteId?: string,
): Promise<AddonCalendarOfflineEventDBRecord> { ): Promise<AddonCalendarOfflineEventDBRecord> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
timeCreated = timeCreated || Date.now(); timeCreated = timeCreated || Date.now();
const event: AddonCalendarOfflineEventDBRecord = { const event: AddonCalendarOfflineEventDBRecord = {
id: eventId || -timeCreated, id: eventId || -timeCreated,
@ -263,7 +263,7 @@ export class AddonCalendarOfflineProvider {
* @return Promise resolved if deleted, rejected if failure. * @return Promise resolved if deleted, rejected if failure.
*/ */
async unmarkDeleted(eventId: number, siteId?: string): Promise<void> { async unmarkDeleted(eventId: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const conditions: SQLiteDBRecordValues = { const conditions: SQLiteDBRecordValues = {
id: eventId, id: eventId,
}; };
@ -272,5 +272,4 @@ export class AddonCalendarOfflineProvider {
} }
} }
export class AddonCalendarOffline extends makeSingleton(AddonCalendarOfflineProvider) {} export const AddonCalendarOffline = makeSingleton(AddonCalendarOfflineProvider);

View File

@ -81,7 +81,7 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
* @return Promise resolved when the events are synced or if it doesn't need to be synced. * @return Promise resolved when the events are synced or if it doesn't need to be synced.
*/ */
async syncEventsIfNeeded(siteId?: string): Promise<AddonCalendarSyncEvents | undefined> { async syncEventsIfNeeded(siteId?: string): Promise<AddonCalendarSyncEvents | undefined> {
siteId = siteId || CoreSites.instance.getCurrentSiteId(); siteId = siteId || CoreSites.getCurrentSiteId();
const needed = await this.isSyncNeeded(AddonCalendarSyncProvider.SYNC_ID, siteId); const needed = await this.isSyncNeeded(AddonCalendarSyncProvider.SYNC_ID, siteId);
@ -97,7 +97,7 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
* @return Promise resolved if sync is successful, rejected otherwise. * @return Promise resolved if sync is successful, rejected otherwise.
*/ */
async syncEvents(siteId?: string): Promise<AddonCalendarSyncEvents> { async syncEvents(siteId?: string): Promise<AddonCalendarSyncEvents> {
siteId = siteId || CoreSites.instance.getCurrentSiteId(); siteId = siteId || CoreSites.getCurrentSiteId();
if (this.isSyncing(AddonCalendarSyncProvider.SYNC_ID, siteId)) { if (this.isSyncing(AddonCalendarSyncProvider.SYNC_ID, siteId)) {
// There's already a sync ongoing for this site, return the promise. // There's already a sync ongoing for this site, return the promise.
@ -127,32 +127,32 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
updated: false, updated: false,
}; };
const eventIds: number[] = await CoreUtils.instance.ignoreErrors(AddonCalendarOffline.instance.getAllEventsIds(siteId), []); const eventIds: number[] = await CoreUtils.ignoreErrors(AddonCalendarOffline.getAllEventsIds(siteId), []);
if (eventIds.length > 0) { if (eventIds.length > 0) {
if (!CoreApp.instance.isOnline()) { if (!CoreApp.isOnline()) {
// Cannot sync in offline. // Cannot sync in offline.
throw new CoreNetworkError(); throw new CoreNetworkError();
} }
const promises = eventIds.map((eventId) => this.syncOfflineEvent(eventId, result, siteId)); const promises = eventIds.map((eventId) => this.syncOfflineEvent(eventId, result, siteId));
await CoreUtils.instance.allPromises(promises); await CoreUtils.allPromises(promises);
if (result.updated) { if (result.updated) {
// Data has been sent to server. Now invalidate the WS calls. // Data has been sent to server. Now invalidate the WS calls.
const promises = [ const promises = [
AddonCalendar.instance.invalidateEventsList(siteId), AddonCalendar.invalidateEventsList(siteId),
AddonCalendarHelper.instance.refreshAfterChangeEvents(result.toinvalidate, siteId), AddonCalendarHelper.refreshAfterChangeEvents(result.toinvalidate, siteId),
]; ];
await CoreUtils.instance.ignoreErrors(Promise.all(promises)); await CoreUtils.ignoreErrors(Promise.all(promises));
} }
} }
// Sync finished, set sync time. // 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. // All done, return the result.
return result; return result;
@ -169,21 +169,21 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
protected async syncOfflineEvent(eventId: number, result: AddonCalendarSyncEvents, siteId?: string): Promise<void> { protected async syncOfflineEvent(eventId: number, result: AddonCalendarSyncEvents, siteId?: string): Promise<void> {
// Verify that event isn't blocked. // 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.'); this.logger.debug('Cannot sync event ' + eventId + ' because it is blocked.');
throw new CoreSyncBlockedError(Translate.instance.instant( throw new CoreSyncBlockedError(Translate.instant(
'core.errorsyncblocked', '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. // First of all, check if the event has been deleted.
try { try {
const data = await AddonCalendarOffline.instance.getDeletedEvent(eventId, siteId); const data = await AddonCalendarOffline.getDeletedEvent(eventId, siteId);
// Delete the event. // Delete the event.
try { try {
await AddonCalendar.instance.deleteEventOnline(data.id, !!data.repeat, siteId); await AddonCalendar.deleteEventOnline(data.id, !!data.repeat, siteId);
result.updated = true; result.updated = true;
result.deleted.push(eventId); result.deleted.push(eventId);
@ -191,13 +191,13 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
// Event sent, delete the offline data. // Event sent, delete the offline data.
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
promises.push(AddonCalendarOffline.instance.unmarkDeleted(eventId, siteId)); promises.push(AddonCalendarOffline.unmarkDeleted(eventId, siteId));
promises.push(AddonCalendarOffline.instance.deleteEvent(eventId, siteId).catch(() => { promises.push(AddonCalendarOffline.deleteEvent(eventId, siteId).catch(() => {
// Ignore errors, maybe there was no edit data. // Ignore errors, maybe there was no edit data.
})); }));
// We need the event data to invalidate it. Get it from local DB. // 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({ result.toinvalidate.push({
id: event.id, id: event.id,
repeatid: event.repeatid, repeatid: event.repeatid,
@ -213,7 +213,7 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
await Promise.all(promises); await Promise.all(promises);
} catch (error) { } catch (error) {
if (!CoreUtils.instance.isWebServiceError(error)) { if (!CoreUtils.isWebServiceError(error)) {
// Local error, reject. // Local error, reject.
throw error; throw error;
} }
@ -223,17 +223,17 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
promises.push(AddonCalendarOffline.instance.unmarkDeleted(eventId, siteId)); promises.push(AddonCalendarOffline.unmarkDeleted(eventId, siteId));
promises.push(AddonCalendarOffline.instance.deleteEvent(eventId, siteId).catch(() => { promises.push(AddonCalendarOffline.deleteEvent(eventId, siteId).catch(() => {
// Ignore errors, maybe there was no edit data. // Ignore errors, maybe there was no edit data.
})); }));
await Promise.all(promises); await Promise.all(promises);
// Event deleted, add a warning. // Event deleted, add a warning.
result.warnings.push(Translate.instance.instant('core.warningofflinedatadeleted', { result.warnings.push(Translate.instant('core.warningofflinedatadeleted', {
component: Translate.instance.instant('addon.calendar.calendarevent'), component: Translate.instant('addon.calendar.calendarevent'),
name: data.name, name: data.name,
error: CoreTextUtils.instance.getErrorMessageFromError(error), error: CoreTextUtils.getErrorMessageFromError(error),
})); }));
} }
@ -243,11 +243,11 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
} }
// Not deleted. Now get the event data. // Not deleted. Now get the event data.
const event = await AddonCalendarOffline.instance.getEvent(eventId, siteId); const event = await AddonCalendarOffline.getEvent(eventId, siteId);
// Try to send the data. // Try to send the data.
const data: AddonCalendarSubmitCreateUpdateFormDataWSParams = Object.assign( const data: AddonCalendarSubmitCreateUpdateFormDataWSParams = Object.assign(
CoreUtils.instance.clone(event), CoreUtils.clone(event),
{ {
description: { description: {
text: event.description || '', text: event.description || '',
@ -257,7 +257,7 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
); // Clone the object because it will be modified in the submit function. ); // Clone the object because it will be modified in the submit function.
try { try {
const newEvent = await AddonCalendar.instance.submitEventOnline(eventId > 0 ? eventId : 0, data, siteId); const newEvent = await AddonCalendar.submitEventOnline(eventId > 0 ? eventId : 0, data, siteId);
result.updated = true; result.updated = true;
result.events.push(newEvent); result.events.push(newEvent);
@ -274,10 +274,10 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
}); });
// Event sent, delete the offline data. // Event sent, delete the offline data.
return AddonCalendarOffline.instance.deleteEvent(event.id!, siteId); return AddonCalendarOffline.deleteEvent(event.id!, siteId);
} catch (error) { } catch (error) {
if (!CoreUtils.instance.isWebServiceError(error)) { if (!CoreUtils.isWebServiceError(error)) {
// Local error, reject. // Local error, reject.
throw error; throw error;
} }
@ -285,19 +285,19 @@ export class AddonCalendarSyncProvider extends CoreSyncBaseProvider<AddonCalenda
// The WebService has thrown an error, this means that the event cannot be created. Delete it. // The WebService has thrown an error, this means that the event cannot be created. Delete it.
result.updated = true; result.updated = true;
await AddonCalendarOffline.instance.deleteEvent(event.id!, siteId); await AddonCalendarOffline.deleteEvent(event.id!, siteId);
// Event deleted, add a warning. // Event deleted, add a warning.
result.warnings.push(Translate.instance.instant('core.warningofflinedatadeleted', { result.warnings.push(Translate.instant('core.warningofflinedatadeleted', {
component: Translate.instance.instant('addon.calendar.calendarevent'), component: Translate.instant('addon.calendar.calendarevent'),
name: event.name, name: event.name,
error: CoreTextUtils.instance.getErrorMessageFromError(error), error: CoreTextUtils.getErrorMessageFromError(error),
})); }));
} }
} }
} }
export class AddonCalendarSync extends makeSingleton(AddonCalendarSyncProvider) {} export const AddonCalendarSync = makeSingleton(AddonCalendarSyncProvider, ['component', 'syncInterval']);
export type AddonCalendarSyncEvents = { export type AddonCalendarSyncEvents = {
warnings: string[]; warnings: string[];

View File

@ -113,7 +113,7 @@ export class AddonCalendarProvider {
*/ */
async canDeleteEvents(siteId?: string): Promise<boolean> { async canDeleteEvents(siteId?: string): Promise<boolean> {
try { try {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return this.canDeleteEventsInSite(site); return this.canDeleteEventsInSite(site);
} catch { } catch {
@ -129,7 +129,7 @@ export class AddonCalendarProvider {
* @since 3.3 * @since 3.3
*/ */
canDeleteEventsInSite(site?: CoreSite): boolean { canDeleteEventsInSite(site?: CoreSite): boolean {
site = site || CoreSites.instance.getCurrentSite(); site = site || CoreSites.getCurrentSite();
return !!site?.wsAvailable('core_calendar_delete_calendar_events'); return !!site?.wsAvailable('core_calendar_delete_calendar_events');
} }
@ -143,7 +143,7 @@ export class AddonCalendarProvider {
*/ */
async canEditEvents(siteId?: string): Promise<boolean> { async canEditEvents(siteId?: string): Promise<boolean> {
try { try {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return this.canEditEventsInSite(site); return this.canEditEventsInSite(site);
} catch { } catch {
@ -159,7 +159,7 @@ export class AddonCalendarProvider {
* @since 3.7.1 * @since 3.7.1
*/ */
canEditEventsInSite(site?: CoreSite): boolean { 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. // The WS to create/edit events requires a fix that was integrated in 3.7.1.
return !!site?.isVersionGreaterEqualThan('3.7.1'); return !!site?.isVersionGreaterEqualThan('3.7.1');
@ -174,7 +174,7 @@ export class AddonCalendarProvider {
*/ */
async canViewMonth(siteId?: string): Promise<boolean> { async canViewMonth(siteId?: string): Promise<boolean> {
try { try {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return this.canViewMonthInSite(site); return this.canViewMonthInSite(site);
} catch { } catch {
@ -190,7 +190,7 @@ export class AddonCalendarProvider {
* @since 3.4 * @since 3.4
*/ */
canViewMonthInSite(site?: CoreSite): boolean { canViewMonthInSite(site?: CoreSite): boolean {
site = site || CoreSites.instance.getCurrentSite(); site = site || CoreSites.getCurrentSite();
return !!site?.wsAvailable('core_calendar_get_calendar_monthly_view'); return !!site?.wsAvailable('core_calendar_get_calendar_monthly_view');
} }
@ -212,7 +212,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when done. * @return Promise resolved when done.
*/ */
async cleanExpiredEvents(siteId?: string): Promise<void> { async cleanExpiredEvents(siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
if (this.canViewMonthInSite(site)) { if (this.canViewMonthInSite(site)) {
// Site supports monthly view, don't clean expired events because user can see past events. // Site supports monthly view, don't clean expired events because user can see past events.
return; return;
@ -220,7 +220,7 @@ export class AddonCalendarProvider {
const events = await site.getDb().getRecordsSelect<AddonCalendarEventDBRecord>( const events = await site.getDb().getRecordsSelect<AddonCalendarEventDBRecord>(
EVENTS_TABLE, EVENTS_TABLE,
'timestart + timeduration < ?', 'timestart + timeduration < ?',
[CoreTimeUtils.instance.timestamp()], [CoreTimeUtils.timestamp()],
); );
await Promise.all(events.map((event) => this.deleteLocalEvent(event.id!, siteId))); await Promise.all(events.map((event) => this.deleteLocalEvent(event.id!, siteId)));
@ -244,25 +244,25 @@ export class AddonCalendarProvider {
siteId?: string, siteId?: string,
): Promise<boolean> { ): Promise<boolean> {
siteId = siteId || CoreSites.instance.getCurrentSiteId(); siteId = siteId || CoreSites.getCurrentSiteId();
// Function to store the submission to be synchronized later. // Function to store the submission to be synchronized later.
const storeOffline = (): Promise<boolean> => const storeOffline = (): Promise<boolean> =>
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. // App is offline, store the action.
return storeOffline(); return storeOffline();
} }
// If the event is already stored, discard it first. // If the event is already stored, discard it first.
await AddonCalendarOffline.instance.unmarkDeleted(eventId, siteId); await AddonCalendarOffline.unmarkDeleted(eventId, siteId);
try { try {
await this.deleteEventOnline(eventId, deleteAll, siteId); await this.deleteEventOnline(eventId, deleteAll, siteId);
return true; return true;
} catch (error) { } catch (error) {
if (error && !CoreUtils.instance.isWebServiceError(error)) { if (error && !CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, store in offline. // Couldn't connect to server, store in offline.
return storeOffline(); return storeOffline();
} else { } else {
@ -281,7 +281,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when done. * @return Promise resolved when done.
*/ */
async deleteEventOnline(eventId: number, deleteAll = false, siteId?: string): Promise<void> { async deleteEventOnline(eventId: number, deleteAll = false, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const params: AddonCalendarDeleteCalendarEventsWSParams = { const params: AddonCalendarDeleteCalendarEventsWSParams = {
events: [ events: [
{ {
@ -305,7 +305,7 @@ export class AddonCalendarProvider {
* @return Resolved when done. * @return Resolved when done.
*/ */
protected async deleteLocalEvent(eventId: number, siteId?: string): Promise<void> { protected async deleteLocalEvent(eventId: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
siteId = site.getId(); siteId = site.getId();
const promises: Promise<unknown>[] = []; const promises: Promise<unknown>[] = [];
@ -334,11 +334,11 @@ export class AddonCalendarProvider {
*/ */
async initialize(): Promise<void> { async initialize(): Promise<void> {
CoreLocalNotifications.instance.registerClick<AddonCalendarPushNotificationData>( CoreLocalNotifications.registerClick<AddonCalendarPushNotificationData>(
AddonCalendarProvider.COMPONENT, AddonCalendarProvider.COMPONENT,
async (notification) => { async (notification) => {
if (notification.eventId) { if (notification.eventId) {
await ApplicationInit.instance.donePromise; await ApplicationInit.donePromise;
const disabled = await this.isDisabled(notification.siteId); const disabled = await this.isDisabled(notification.siteId);
if (disabled) { if (disabled) {
@ -347,10 +347,10 @@ export class AddonCalendarProvider {
} }
// Check which page we should load. // 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); const pageName = this.getMainCalendarPagePath(site);
CoreNavigator.instance.navigateToSitePath( CoreNavigator.navigateToSitePath(
pageName, pageName,
{ params: { eventId: notification.eventId }, siteId: notification.siteId }, { params: { eventId: notification.eventId }, siteId: notification.siteId },
); );
@ -389,16 +389,16 @@ export class AddonCalendarProvider {
if (moment(start).isSame(end, 'day')) { if (moment(start).isSame(end, 'day')) {
// Event starts and ends the same day. // Event starts and ends the same day.
if (event.timeduration == CoreConstants.SECONDS_DAY) { if (event.timeduration == CoreConstants.SECONDS_DAY) {
time = Translate.instance.instant('addon.calendar.allday'); time = Translate.instant('addon.calendar.allday');
} else { } else {
time = CoreTimeUtils.instance.userDate(start, format) + ' <strong>&raquo;</strong> ' + time = CoreTimeUtils.userDate(start, format) + ' <strong>&raquo;</strong> ' +
CoreTimeUtils.instance.userDate(end, format); CoreTimeUtils.userDate(end, format);
} }
} else { } else {
// Event lasts more than one day. // Event lasts more than one day.
const timeStart = CoreTimeUtils.instance.userDate(start, format); const timeStart = CoreTimeUtils.userDate(start, format);
const timeEnd = CoreTimeUtils.instance.userDate(end, format); const timeEnd = CoreTimeUtils.userDate(end, format);
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
// Don't use common words when the event lasts more than one day. // 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. // Add links to the days if needed.
if (dayStart && (!seenDay || !moment(seenDay).isSame(start, 'day'))) { if (dayStart && (!seenDay || !moment(seenDay).isSame(start, 'day'))) {
promises.push(this.getViewUrl('day', event.timestart, undefined, siteId).then((url) => { promises.push(this.getViewUrl('day', event.timestart, undefined, siteId).then((url) => {
dayStart = CoreUrlUtils.instance.buildLink(url, dayStart); dayStart = CoreUrlUtils.buildLink(url, dayStart);
return; return;
})); }));
} }
if (dayEnd && (!seenDay || !moment(seenDay).isSame(end, 'day'))) { if (dayEnd && (!seenDay || !moment(seenDay).isSame(end, 'day'))) {
promises.push(this.getViewUrl('day', end / 1000, undefined, siteId).then((url) => { promises.push(this.getViewUrl('day', end / 1000, undefined, siteId).then((url) => {
dayEnd = CoreUrlUtils.instance.buildLink(url, dayEnd); dayEnd = CoreUrlUtils.buildLink(url, dayEnd);
return; return;
})); }));
@ -427,7 +427,7 @@ export class AddonCalendarProvider {
} }
} else { } else {
// There is no time duration. // There is no time duration.
time = CoreTimeUtils.instance.userDate(start, format); time = CoreTimeUtils.userDate(start, format);
} }
if (showTime) { if (showTime) {
@ -443,7 +443,7 @@ export class AddonCalendarProvider {
// Add link to view the day. // Add link to view the day.
const url = await this.getViewUrl('day', event.timestart, undefined, siteId); 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 * @since 3.7
*/ */
async getAccessInformation(courseId?: number, siteId?: string): Promise<AddonCalendarGetCalendarAccessInformationWSResponse> { async getAccessInformation(courseId?: number, siteId?: string): Promise<AddonCalendarGetCalendarAccessInformationWSResponse> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const params: AddonCalendarGetCalendarAccessInformationWSParams = {}; const params: AddonCalendarGetCalendarAccessInformationWSParams = {};
const preSets: CoreSiteWSPreSets = { const preSets: CoreSiteWSPreSets = {
cacheKey: this.getAccessInformationCacheKey(courseId), cacheKey: this.getAccessInformationCacheKey(courseId),
@ -484,7 +484,7 @@ export class AddonCalendarProvider {
* @return Promise resolved with all the events. * @return Promise resolved with all the events.
*/ */
async getAllEventsFromLocalDb(siteId?: string): Promise<AddonCalendarEventDBRecord[]> { async getAllEventsFromLocalDb(siteId?: string): Promise<AddonCalendarEventDBRecord[]> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return await site.getDb().getAllRecords(EVENTS_TABLE); return await site.getDb().getAllRecords(EVENTS_TABLE);
} }
@ -498,7 +498,7 @@ export class AddonCalendarProvider {
* @since 3.7 * @since 3.7
*/ */
async getAllowedEventTypes(courseId?: number, siteId?: string): Promise<{[name: string]: boolean}> { 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 params: AddonCalendarGetAllowedEventTypesWSParams = {};
const preSets: CoreSiteWSPreSets = { const preSets: CoreSiteWSPreSets = {
cacheKey: this.getAllowedEventTypesCacheKey(courseId), cacheKey: this.getAllowedEventTypesCacheKey(courseId),
@ -537,10 +537,10 @@ export class AddonCalendarProvider {
* @return Promise resolved with the look ahead (number of days). * @return Promise resolved with the look ahead (number of days).
*/ */
async getCalendarLookAhead(siteId?: string): Promise<number> { async getCalendarLookAhead(siteId?: string): Promise<number> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
let value: string | undefined; let value: string | undefined;
try { try {
value = await CoreUser.instance.getUserPreference('calendar_lookahead'); value = await CoreUser.getUserPreference('calendar_lookahead');
} catch { } catch {
// Ignore errors. // Ignore errors.
} }
@ -559,11 +559,11 @@ export class AddonCalendarProvider {
* @return Promise resolved with the format. * @return Promise resolved with the format.
*/ */
async getCalendarTimeFormat(siteId?: string): Promise<string> { async getCalendarTimeFormat(siteId?: string): Promise<string> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
let format: string | undefined; let format: string | undefined;
try { try {
format = await CoreUser.instance.getUserPreference('calendar_timeformat'); format = await CoreUser.getUserPreference('calendar_timeformat');
} catch { } catch {
// Ignore errors. // Ignore errors.
} }
@ -573,12 +573,12 @@ export class AddonCalendarProvider {
} }
if (format === AddonCalendarProvider.CALENDAR_TF_12) { if (format === AddonCalendarProvider.CALENDAR_TF_12) {
format = Translate.instance.instant('core.strftimetime12'); format = Translate.instant('core.strftimetime12');
} else if (format === AddonCalendarProvider.CALENDAR_TF_24) { } 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) { if (!useCommonWords) {
// We don't want words, just a date. // 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 date = moment(time);
const today = moment(); const today = moment();
if (date.isSame(today, 'day')) { 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')) { 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')) { 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. * @return Promise resolved with the default time.
*/ */
async getDefaultNotificationTime(siteId?: string): Promise<number> { async getDefaultNotificationTime(siteId?: string): Promise<number> {
siteId = siteId || CoreSites.instance.getCurrentSiteId(); siteId = siteId || CoreSites.getCurrentSiteId();
const key = AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_SETTING + '#' + siteId; 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. * @return Promise resolved when the event data is retrieved.
*/ */
async getEvent(id: number, siteId?: string): Promise<AddonCalendarGetEventsEvent | AddonCalendarEventBase> { async getEvent(id: number, siteId?: string): Promise<AddonCalendarGetEventsEvent | AddonCalendarEventBase> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const preSets: CoreSiteWSPreSets = { const preSets: CoreSiteWSPreSets = {
cacheKey: this.getEventCacheKey(id), cacheKey: this.getEventCacheKey(id),
updateFrequency: CoreSite.FREQUENCY_RARELY, updateFrequency: CoreSite.FREQUENCY_RARELY,
@ -670,7 +670,7 @@ export class AddonCalendarProvider {
* @since 3.4 * @since 3.4
*/ */
async getEventById(id: number, siteId?: string): Promise<AddonCalendarEvent> { async getEventById(id: number, siteId?: string): Promise<AddonCalendarEvent> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const preSets: CoreSiteWSPreSets = { const preSets: CoreSiteWSPreSets = {
cacheKey: this.getEventCacheKey(id), cacheKey: this.getEventCacheKey(id),
updateFrequency: CoreSite.FREQUENCY_RARELY, updateFrequency: CoreSite.FREQUENCY_RARELY,
@ -710,7 +710,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the event data is retrieved. * @return Promise resolved when the event data is retrieved.
*/ */
async getEventFromLocalDb(id: number, siteId?: string): Promise<AddonCalendarGetEventsEvent | AddonCalendarEvent> { async getEventFromLocalDb(id: number, siteId?: string): Promise<AddonCalendarGetEventsEvent | AddonCalendarEvent> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const record: AddonCalendarGetEventsEvent | AddonCalendarEvent | AddonCalendarEventDBRecord = const record: AddonCalendarGetEventsEvent | AddonCalendarEvent | AddonCalendarEventDBRecord =
await site.getDb().getRecord(EVENTS_TABLE, { id: id }); await site.getDb().getRecord(EVENTS_TABLE, { id: id });
@ -729,18 +729,18 @@ export class AddonCalendarProvider {
eventConverted.iscategoryevent = originalEvent.eventtype == AddonCalendarEventType.CATEGORY; eventConverted.iscategoryevent = originalEvent.eventtype == AddonCalendarEventType.CATEGORY;
eventConverted.normalisedeventtype = this.getEventType(recordAsRecord); eventConverted.normalisedeventtype = this.getEventType(recordAsRecord);
try { try {
eventConverted.category = CoreTextUtils.instance.parseJSON(recordAsRecord.category!); eventConverted.category = CoreTextUtils.parseJSON(recordAsRecord.category!);
} catch { } catch {
// Ignore errors. // Ignore errors.
} }
try { try {
eventConverted.course = CoreTextUtils.instance.parseJSON(recordAsRecord.course!); eventConverted.course = CoreTextUtils.parseJSON(recordAsRecord.course!);
} catch { } catch {
// Ignore errors. // Ignore errors.
} }
try { try {
eventConverted.subscription = CoreTextUtils.instance.parseJSON(recordAsRecord.subscription!); eventConverted.subscription = CoreTextUtils.parseJSON(recordAsRecord.subscription!);
} catch { } catch {
// Ignore errors. // Ignore errors.
} }
@ -761,7 +761,7 @@ export class AddonCalendarProvider {
time: number, time: number,
siteId?: string, siteId?: string,
): Promise<void> { ): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const reminder: AddonCalendarReminderDBRecord = { const reminder: AddonCalendarReminderDBRecord = {
eventid: event.id, eventid: event.id,
time: time, time: time,
@ -794,10 +794,10 @@ export class AddonCalendarProvider {
* @return Promise resolved when the notification is updated. * @return Promise resolved when the notification is updated.
*/ */
async deleteEventReminder(id: number, siteId?: string): Promise<void> { async deleteEventReminder(id: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
if (CoreLocalNotifications.instance.isAvailable()) { if (CoreLocalNotifications.isAvailable()) {
CoreLocalNotifications.instance.cancel(id, AddonCalendarProvider.COMPONENT, site.getId()); CoreLocalNotifications.cancel(id, AddonCalendarProvider.COMPONENT, site.getId());
} }
await site.getDb().deleteRecords(REMINDERS_TABLE, { id: id }); await site.getDb().deleteRecords(REMINDERS_TABLE, { id: id });
@ -825,7 +825,7 @@ export class AddonCalendarProvider {
siteId?: string, siteId?: string,
): Promise<AddonCalendarCalendarDay> { ): Promise<AddonCalendarCalendarDay> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const params: AddonCalendarGetCalendarDayViewWSParams = { const params: AddonCalendarGetCalendarDayViewWSParams = {
year: year, year: year,
month: month, month: month,
@ -895,7 +895,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the event data is retrieved. * @return Promise resolved when the event data is retrieved.
*/ */
async getEventReminders(id: number, siteId?: string): Promise<AddonCalendarReminderDBRecord[]> { async getEventReminders(id: number, siteId?: string): Promise<AddonCalendarReminderDBRecord[]> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return await site.getDb().getRecords(REMINDERS_TABLE, { eventid: id }, 'time ASC'); return await site.getDb().getRecords(REMINDERS_TABLE, { eventid: id }, 'time ASC');
} }
@ -920,9 +920,9 @@ export class AddonCalendarProvider {
siteId?: string, siteId?: string,
): Promise<AddonCalendarGetEventsEvent[]> { ): Promise<AddonCalendarGetEventsEvent[]> {
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(); siteId = site.getId();
const start = initialTime + (CoreConstants.SECONDS_DAY * daysToStart); const start = initialTime + (CoreConstants.SECONDS_DAY * daysToStart);
@ -943,7 +943,7 @@ export class AddonCalendarProvider {
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
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 = courses.map((course) => course.id);
params.events!.courseids.push(site.getSiteHomeId()); // Add front page. params.events!.courseids.push(site.getSiteHomeId()); // Add front page.
@ -951,7 +951,7 @@ export class AddonCalendarProvider {
return; return;
})); }));
promises.push(CoreGroups.instance.getAllUserGroups(siteId).then((groups) => { promises.push(CoreGroups.getAllUserGroups(siteId).then((groups) => {
params.events!.groupids = groups.map((group) => group.id); params.events!.groupids = groups.map((group) => group.id);
return; return;
@ -1004,7 +1004,7 @@ export class AddonCalendarProvider {
* @return Promise resolved with all the events. * @return Promise resolved with all the events.
*/ */
async getLocalEventsByRepeatIdFromLocalDb(repeatId: number, siteId?: string): Promise<AddonCalendarEventDBRecord[]> { async getLocalEventsByRepeatIdFromLocalDb(repeatId: number, siteId?: string): Promise<AddonCalendarEventDBRecord[]> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return await site.getDb().getRecords(EVENTS_TABLE, { repeatid: repeatId }); return await site.getDb().getRecords(EVENTS_TABLE, { repeatid: repeatId });
} }
@ -1029,7 +1029,7 @@ export class AddonCalendarProvider {
siteId?: string, siteId?: string,
): Promise<AddonCalendarMonth> { ): Promise<AddonCalendarMonth> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const params: AddonCalendarGetCalendarMonthlyViewWSParams = { const params: AddonCalendarGetCalendarMonthlyViewWSParams = {
year: year, year: year,
month: month, 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. // Store starting week day preference, we need it in offline to show months that are not in cache.
if (CoreApp.instance.isOnline()) { if (CoreApp.isOnline()) {
CoreConfig.instance.set(AddonCalendarProvider.STARTING_WEEK_DAY, response.daynames[0].dayno); CoreConfig.set(AddonCalendarProvider.STARTING_WEEK_DAY, response.daynames[0].dayno);
} }
return response; return response;
@ -1120,7 +1120,7 @@ export class AddonCalendarProvider {
siteId?: string, siteId?: string,
): Promise<AddonCalendarUpcoming> { ): Promise<AddonCalendarUpcoming> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const params: AddonCalendarGetCalendarUpcomingViewWSParams = {}; const params: AddonCalendarGetCalendarUpcomingViewWSParams = {};
if (courseId) { if (courseId) {
@ -1177,8 +1177,8 @@ export class AddonCalendarProvider {
* @return Promise resolved with the URL.x * @return Promise resolved with the URL.x
*/ */
async getViewUrl(view: string, time?: number, courseId?: string, siteId?: string): Promise<string> { async getViewUrl(view: string, time?: number, courseId?: string, siteId?: string): Promise<string> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
let url = CoreTextUtils.instance.concatenatePaths(site.getURL(), 'calendar/view.php?view=' + view); let url = CoreTextUtils.concatenatePaths(site.getURL(), 'calendar/view.php?view=' + view);
if (time) { if (time) {
url += '&time=' + time; url += '&time=' + time;
@ -1210,7 +1210,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateAccessInformation(courseId?: number, siteId?: string): Promise<void> { async invalidateAccessInformation(courseId?: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getAccessInformationCacheKey(courseId)); await site.invalidateWsCacheForKey(this.getAccessInformationCacheKey(courseId));
} }
@ -1223,7 +1223,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateAllowedEventTypes(courseId?: number, siteId?: string): Promise<void> { async invalidateAllowedEventTypes(courseId?: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getAllowedEventTypesCacheKey(courseId)); await site.invalidateWsCacheForKey(this.getAllowedEventTypesCacheKey(courseId));
} }
@ -1235,7 +1235,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateAllDayEvents(siteId?: string): Promise<void> { async invalidateAllDayEvents(siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getDayEventsPrefixCacheKey()); await site.invalidateWsCacheForKeyStartingWith(this.getDayEventsPrefixCacheKey());
} }
@ -1249,7 +1249,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateDayEvents(year: number, month: number, day: number, siteId?: string): Promise<void> { async invalidateDayEvents(year: number, month: number, day: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getDayEventsDayPrefixCacheKey(year, month, day)); await site.invalidateWsCacheForKeyStartingWith(this.getDayEventsDayPrefixCacheKey(year, month, day));
} }
@ -1261,12 +1261,12 @@ export class AddonCalendarProvider {
* @return Promise resolved when the list is invalidated. * @return Promise resolved when the list is invalidated.
*/ */
async invalidateEventsList(siteId?: string): Promise<void> { async invalidateEventsList(siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
siteId = site.getId(); siteId = site.getId();
const promises: Promise<void>[] = []; const promises: Promise<void>[] = [];
promises.push(CoreCourses.instance.invalidateUserCourses(siteId)); promises.push(CoreCourses.invalidateUserCourses(siteId));
promises.push(CoreGroups.instance.invalidateAllUserGroups(siteId)); promises.push(CoreGroups.invalidateAllUserGroups(siteId));
promises.push(site.invalidateWsCacheForKeyStartingWith(this.getEventsListPrefixCacheKey())); promises.push(site.invalidateWsCacheForKeyStartingWith(this.getEventsListPrefixCacheKey()));
await Promise.all(promises); await Promise.all(promises);
@ -1280,7 +1280,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the list is invalidated. * @return Promise resolved when the list is invalidated.
*/ */
async invalidateEvent(eventId: number, siteId?: string): Promise<void> { async invalidateEvent(eventId: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getEventCacheKey(eventId)); await site.invalidateWsCacheForKey(this.getEventCacheKey(eventId));
} }
@ -1292,7 +1292,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateAllMonthlyEvents(siteId?: string): Promise<void> { async invalidateAllMonthlyEvents(siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getMonthlyEventsPrefixCacheKey()); await site.invalidateWsCacheForKeyStartingWith(this.getMonthlyEventsPrefixCacheKey());
} }
@ -1305,7 +1305,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateMonthlyEvents(year: number, month: number, siteId?: string): Promise<void> { async invalidateMonthlyEvents(year: number, month: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getMonthlyEventsMonthPrefixCacheKey(year, month)); await site.invalidateWsCacheForKeyStartingWith(this.getMonthlyEventsMonthPrefixCacheKey(year, month));
} }
@ -1317,7 +1317,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateAllUpcomingEvents(siteId?: string): Promise<void> { async invalidateAllUpcomingEvents(siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getUpcomingEventsPrefixCacheKey()); await site.invalidateWsCacheForKeyStartingWith(this.getUpcomingEventsPrefixCacheKey());
} }
@ -1331,7 +1331,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateUpcomingEvents(courseId?: number, categoryId?: number, siteId?: string): Promise<void> { async invalidateUpcomingEvents(courseId?: number, categoryId?: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getUpcomingEventsCacheKey(courseId, categoryId)); await site.invalidateWsCacheForKeyStartingWith(this.getUpcomingEventsCacheKey(courseId, categoryId));
} }
@ -1343,7 +1343,7 @@ export class AddonCalendarProvider {
* @return Promise resolved when the data is invalidated. * @return Promise resolved when the data is invalidated.
*/ */
async invalidateLookAhead(siteId?: string): Promise<void> { async invalidateLookAhead(siteId?: string): Promise<void> {
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. * @return Promise resolved when the data is invalidated.
*/ */
invalidateTimeFormat(siteId?: string): Promise<void> { invalidateTimeFormat(siteId?: string): Promise<void> {
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. * @return Whether it's disabled.
*/ */
isCalendarDisabledInSite(site?: CoreSite): boolean { isCalendarDisabledInSite(site?: CoreSite): boolean {
site = site || CoreSites.instance.getCurrentSite(); site = site || CoreSites.getCurrentSite();
return !!site?.isFeatureDisabled('CoreMainMenuDelegate_AddonCalendar'); 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. * @return Promise resolved with true if disabled, rejected or resolved with false otherwise.
*/ */
async isDisabled(siteId?: string): Promise<boolean> { async isDisabled(siteId?: string): Promise<boolean> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return this.isCalendarDisabledInSite(site); return this.isCalendarDisabledInSite(site);
} }
@ -1389,7 +1389,7 @@ export class AddonCalendarProvider {
*/ */
async isGetEventByIdAvailable(siteId?: string): Promise<boolean> { async isGetEventByIdAvailable(siteId?: string): Promise<boolean> {
try { try {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
return this.isGetEventByIdAvailableInSite(site); return this.isGetEventByIdAvailableInSite(site);
} catch { } catch {
@ -1405,7 +1405,7 @@ export class AddonCalendarProvider {
* @since 3.4 * @since 3.4
*/ */
isGetEventByIdAvailableInSite(site?: CoreSite): boolean { isGetEventByIdAvailableInSite(site?: CoreSite): boolean {
site = site || CoreSites.instance.getCurrentSite(); site = site || CoreSites.getCurrentSite();
return !!site?.wsAvailable('core_calendar_get_calendar_event_by_id'); 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. * @return Promise resolved when all the notifications have been scheduled.
*/ */
async scheduleAllSitesEventsNotifications(): Promise<void> { async scheduleAllSitesEventsNotifications(): Promise<void> {
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() => { const promises = siteIds.map((siteId: string) => this.cleanExpiredEvents(siteId).then(async() => {
if (notificationsEnabled) { if (notificationsEnabled) {
@ -1458,15 +1458,15 @@ export class AddonCalendarProvider {
siteId?: string, siteId?: string,
): Promise<void> { ): Promise<void> {
if (!CoreLocalNotifications.instance.isAvailable()) { if (!CoreLocalNotifications.isAvailable()) {
return; return;
} }
siteId = siteId || CoreSites.instance.getCurrentSiteId(); siteId = siteId || CoreSites.getCurrentSiteId();
if (time === 0) { if (time === 0) {
// Cancel if it was scheduled. // Cancel if it was scheduled.
return CoreLocalNotifications.instance.cancel(reminderId, AddonCalendarProvider.COMPONENT, siteId); return CoreLocalNotifications.cancel(reminderId, AddonCalendarProvider.COMPONENT, siteId);
} }
if (time == -1) { if (time == -1) {
@ -1475,7 +1475,7 @@ export class AddonCalendarProvider {
if (time == 0) { if (time == 0) {
// Default notification time is disabled, do not show. // 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); time = event.timestart - (time * 60);
@ -1485,7 +1485,7 @@ export class AddonCalendarProvider {
if (time <= Date.now()) { if (time <= Date.now()) {
// This reminder is over, don't schedule. Cancel if it was scheduled. // 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 = { const notificationData: AddonCalendarPushNotificationData = {
@ -1497,7 +1497,7 @@ export class AddonCalendarProvider {
const notification: ILocalNotification = { const notification: ILocalNotification = {
id: reminderId, id: reminderId,
title: event.name, 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', icon: 'file://assets/img/icons/calendar.png',
trigger: { trigger: {
at: new Date(time), at: new Date(time),
@ -1505,7 +1505,7 @@ export class AddonCalendarProvider {
data: notificationData, 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, siteId?: string,
): Promise<void> { ): Promise<void> {
if (!CoreLocalNotifications.instance.isAvailable()) { if (!CoreLocalNotifications.isAvailable()) {
return; return;
} }
siteId = siteId || CoreSites.instance.getCurrentSiteId(); siteId = siteId || CoreSites.getCurrentSiteId();
const promises = events.map(async (event) => { const promises = events.map(async (event) => {
const timeEnd = (event.timestart + event.timeduration) * 1000; const timeEnd = (event.timestart + event.timeduration) * 1000;
@ -1555,11 +1555,11 @@ export class AddonCalendarProvider {
* @return Promise resolved when stored. * @return Promise resolved when stored.
*/ */
async setDefaultNotificationTime(time: number, siteId?: string): Promise<void> { async setDefaultNotificationTime(time: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.instance.getCurrentSiteId(); siteId = siteId || CoreSites.getCurrentSiteId();
const key = AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_SETTING + '#' + siteId; 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. * @return Promise resolved when stored.
*/ */
async storeEventInLocalDb(event: AddonCalendarGetEventsEvent | AddonCalendarCalendarEvent, siteId?: string): Promise<void> { async storeEventInLocalDb(event: AddonCalendarGetEventsEvent | AddonCalendarCalendarEvent, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
siteId = site.getId(); siteId = site.getId();
try { try {
await this.getEventFromLocalDb(event.id, site.id); await this.getEventFromLocalDb(event.id, site.id);
@ -1646,7 +1646,7 @@ export class AddonCalendarProvider {
events: (AddonCalendarGetEventsEvent | AddonCalendarCalendarEvent)[], events: (AddonCalendarGetEventsEvent | AddonCalendarCalendarEvent)[],
siteId?: string, siteId?: string,
): Promise<void> { ): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
siteId = site.getId(); siteId = site.getId();
await Promise.all(events.map((event: AddonCalendarGetEventsEvent| AddonCalendarCalendarEvent) => await Promise.all(events.map((event: AddonCalendarGetEventsEvent| AddonCalendarCalendarEvent) =>
@ -1672,28 +1672,28 @@ export class AddonCalendarProvider {
siteId?: string, siteId?: string,
): Promise<{sent: boolean; event: AddonCalendarOfflineEventDBRecord | AddonCalendarEvent}> { ): Promise<{sent: boolean; event: AddonCalendarOfflineEventDBRecord | AddonCalendarEvent}> {
siteId = siteId || CoreSites.instance.getCurrentSiteId(); siteId = siteId || CoreSites.getCurrentSiteId();
// Function to store the event to be synchronized later. // Function to store the event to be synchronized later.
const storeOffline = (): Promise<{ sent: boolean; event: AddonCalendarOfflineEventDBRecord }> => 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 })); ({ sent: false, event }));
if (forceOffline || !CoreApp.instance.isOnline()) { if (forceOffline || !CoreApp.isOnline()) {
// App is offline, store the event. // App is offline, store the event.
return storeOffline(); return storeOffline();
} }
if (eventId) { if (eventId) {
// If the event is already stored, discard it first. // If the event is already stored, discard it first.
await AddonCalendarOffline.instance.deleteEvent(eventId, siteId); await AddonCalendarOffline.deleteEvent(eventId, siteId);
} }
try { try {
const event = await this.submitEventOnline(eventId, formData, siteId); const event = await this.submitEventOnline(eventId, formData, siteId);
return ({ sent: true, event }); return ({ sent: true, event });
} catch (error) { } catch (error) {
if (error && !CoreUtils.instance.isWebServiceError(error)) { if (error && !CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, store in offline. // Couldn't connect to server, store in offline.
return storeOffline(); return storeOffline();
} else { } else {
@ -1716,7 +1716,7 @@ export class AddonCalendarProvider {
formData: AddonCalendarSubmitCreateUpdateFormDataWSParams, formData: AddonCalendarSubmitCreateUpdateFormDataWSParams,
siteId?: string, siteId?: string,
): Promise<AddonCalendarEvent> { ): Promise<AddonCalendarEvent> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
// Add data that is "hidden" in web. // Add data that is "hidden" in web.
formData.id = eventId; formData.id = eventId;
formData.userid = site.getUserId(); formData.userid = site.getUserId();
@ -1728,14 +1728,14 @@ export class AddonCalendarProvider {
formData['_qf__core_calendar_local_event_forms_create'] = 1; formData['_qf__core_calendar_local_event_forms_create'] = 1;
} }
const params: AddonCalendarSubmitCreateUpdateFormWSParams = { const params: AddonCalendarSubmitCreateUpdateFormWSParams = {
formdata: CoreUtils.instance.objectToGetParams(formData), formdata: CoreUtils.objectToGetParams(formData),
}; };
const result = const result =
await site.write<AddonCalendarSubmitCreateUpdateFormWSResponse>('core_calendar_submit_create_update_form', params); await site.write<AddonCalendarSubmitCreateUpdateFormWSResponse>('core_calendar_submit_create_update_form', params);
if (result.validationerror) { if (result.validationerror) {
// Simulate a WS error. // Simulate a WS error.
throw new CoreWSError({ throw new CoreWSError({
message: Translate.instance.instant('core.invalidformdata'), message: Translate.instant('core.invalidformdata'),
errorcode: 'validationerror', 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. * Data returned by calendar's events_exporter.

View File

@ -35,7 +35,7 @@ export class AddonCalendarMainMenuHandlerService implements CoreMainMenuHandler
* @return Whether or not the handler is enabled on a site level. * @return Whether or not the handler is enabled on a site level.
*/ */
async isEnabled(): Promise<boolean> { async isEnabled(): Promise<boolean> {
return !AddonCalendar.instance.isCalendarDisabledInSite(); return !AddonCalendar.isCalendarDisabledInSite();
} }
/** /**
@ -47,11 +47,11 @@ export class AddonCalendarMainMenuHandlerService implements CoreMainMenuHandler
return { return {
icon: 'far-calendar', icon: 'far-calendar',
title: 'addon.calendar.calendar', title: 'addon.calendar.calendar',
page: AddonCalendar.instance.getMainCalendarPagePath(), page: AddonCalendar.getMainCalendarPagePath(),
class: 'addon-calendar-handler', class: 'addon-calendar-handler',
}; };
} }
} }
export class AddonCalendarMainMenuHandler extends makeSingleton(AddonCalendarMainMenuHandlerService) {} export const AddonCalendarMainMenuHandler = makeSingleton(AddonCalendarMainMenuHandlerService);

View File

@ -34,7 +34,7 @@ export class AddonCalendarSyncCronHandlerService implements CoreCronHandler {
* @return Promise resolved when done, rejected if failure. * @return Promise resolved when done, rejected if failure.
*/ */
async execute(siteId?: string, force?: boolean): Promise<void> { async execute(siteId?: string, force?: boolean): Promise<void> {
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). * @return Time between consecutive executions (in ms).
*/ */
getInterval(): number { getInterval(): number {
return AddonCalendarSync.instance.syncInterval; return AddonCalendarSync.syncInterval;
} }
} }
export class AddonCalendarSyncCronHandler extends makeSingleton(AddonCalendarSyncCronHandlerService) {} export const AddonCalendarSyncCronHandler = makeSingleton(AddonCalendarSyncCronHandlerService);

View File

@ -59,7 +59,7 @@ export class AddonCalendarViewLinkHandlerService extends CoreContentLinksHandler
stateParams.month = date.getMonth() + 1; stateParams.month = date.getMonth() + 1;
// @todo: Add checkMenu param. // @todo: Add checkMenu param.
CoreNavigator.instance.navigateToSitePath('/calendar/index', { params: stateParams, siteId }); CoreNavigator.navigateToSitePath('/calendar/index', { params: stateParams, siteId });
} else if (params.view == 'day') { } else if (params.view == 'day') {
// Daily view, open the page. // Daily view, open the page.
@ -73,7 +73,7 @@ export class AddonCalendarViewLinkHandlerService extends CoreContentLinksHandler
stateParams.month = date.getMonth() + 1; stateParams.month = date.getMonth() + 1;
stateParams.day = date.getDate(); 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') { } else if (params.view == 'upcoming' || params.view == 'upcoming_mini') {
// Upcoming view, open the calendar tab. // Upcoming view, open the calendar tab.
@ -83,7 +83,7 @@ export class AddonCalendarViewLinkHandlerService extends CoreContentLinksHandler
}; };
// @todo: Add checkMenu param. // @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 false;
} }
return AddonCalendar.instance.isDisabled(siteId).then((disabled) => { return AddonCalendar.isDisabled(siteId).then((disabled) => {
if (disabled) { if (disabled) {
return false; return false;
} }
return AddonCalendar.instance.canViewMonth(siteId); return AddonCalendar.canViewMonth(siteId);
}); });
} }
} }
export class AddonCalendarViewLinkHandler extends makeSingleton(AddonCalendarViewLinkHandlerService) {} export const AddonCalendarViewLinkHandler = makeSingleton(AddonCalendarViewLinkHandlerService);

View File

@ -45,7 +45,7 @@ export class AddonCourseCompletionProvider {
* @return True if user can mark course as self completed, false otherwise. * @return True if user can mark course as self completed, false otherwise.
*/ */
canMarkSelfCompleted(userId: number, completion: AddonCourseCompletionCourseCompletionStatus): boolean { canMarkSelfCompleted(userId: number, completion: AddonCourseCompletionCourseCompletionStatus): boolean {
if (CoreSites.instance.getCurrentSiteUserId() != userId) { if (CoreSites.getCurrentSiteUserId() != userId) {
return false; return false;
} }
@ -100,7 +100,7 @@ export class AddonCourseCompletionProvider {
siteId?: string, siteId?: string,
): Promise<AddonCourseCompletionCourseCompletionStatus> { ): Promise<AddonCourseCompletionCourseCompletionStatus> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId(); userId = userId || site.getUserId();
this.logger.debug('Get completion for course ' + courseId + ' and user ' + userId); 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. * @return Promise resolved when the list is invalidated.
*/ */
async invalidateCourseCompletion(courseId: number, userId?: number, siteId?: string): Promise<void> { async invalidateCourseCompletion(courseId: number, userId?: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId(); userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getCompletionCacheKey(courseId, userId)); await site.invalidateWsCacheForKey(this.getCompletionCacheKey(courseId, userId));
@ -154,7 +154,7 @@ export class AddonCourseCompletionProvider {
* @return True if plugin enabled, false otherwise. * @return True if plugin enabled, false otherwise.
*/ */
isPluginViewEnabled(): boolean { isPluginViewEnabled(): boolean {
return CoreSites.instance.isLoggedIn(); return CoreSites.isLoggedIn();
} }
/** /**
@ -169,7 +169,7 @@ export class AddonCourseCompletionProvider {
throw new CoreError('No courseId provided'); throw new CoreError('No courseId provided');
} }
const course = await CoreCourses.instance.getUserCourse(courseId, preferCache); const course = await CoreCourses.getUserCourse(courseId, preferCache);
if (course) { if (course) {
if (typeof course.enablecompletion != 'undefined' && !course.enablecompletion) { 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. * @return Promise resolved with true if plugin is enabled, rejected or resolved with false otherwise.
*/ */
async isPluginViewEnabledForUser(courseId: number, userId?: number, siteId?: string): Promise<boolean> { async isPluginViewEnabledForUser(courseId: number, userId?: number, siteId?: string): Promise<boolean> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const currentUserId = site.getUserId(); const currentUserId = site.getUserId();
// Check if user wants to view his own completion. // Check if user wants to view his own completion.
try { try {
if (!userId || userId == currentUserId) { if (!userId || userId == currentUserId) {
// Viewing own completion. Get the course to check if it has completion criteria. // 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. // If the site is returning the completionhascriteria then the user can view his own completion.
// We already checked the value in isPluginViewEnabledForCourse. // We already checked the value in isPluginViewEnabledForCourse.
@ -226,7 +226,7 @@ export class AddonCourseCompletionProvider {
return true; return true;
} catch (error) { } catch (error) {
if (CoreUtils.instance.isWebServiceError(error)) { if (CoreUtils.isWebServiceError(error)) {
// The WS returned an error, plugin is not enabled. // The WS returned an error, plugin is not enabled.
return false; return false;
} }
@ -252,7 +252,7 @@ export class AddonCourseCompletionProvider {
* @return Promise resolved on success. * @return Promise resolved on success.
*/ */
async markCourseAsSelfCompleted(courseId: number, siteId?: string): Promise<void> { async markCourseAsSelfCompleted(courseId: number, siteId?: string): Promise<void> {
const site = await CoreSites.instance.getSite(siteId); const site = await CoreSites.getSite(siteId);
const params: AddonCourseCompletionMarkCourseSelfCompletedWSParams = { const params: AddonCourseCompletionMarkCourseSelfCompletedWSParams = {
courseid: courseId, 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. * Completion status returned by core_completion_get_course_completion_status.

View File

@ -27,7 +27,7 @@ import { AddonFilterActivityNamesHandler } from './services/handlers/activitynam
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
deps: [], deps: [],
useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterActivityNamesHandler.instance), useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterActivityNamesHandler.instance),
}, },
], ],
}) })

View File

@ -43,4 +43,4 @@ export class AddonFilterActivityNamesHandlerService extends CoreFilterDefaultHan
} }
export class AddonFilterActivityNamesHandler extends makeSingleton(AddonFilterActivityNamesHandlerService) {} export const AddonFilterActivityNamesHandler = makeSingleton(AddonFilterActivityNamesHandlerService);

View File

@ -27,7 +27,7 @@ import { AddonFilterAlgebraHandler } from './services/handlers/algebra';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
deps: [], deps: [],
useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterAlgebraHandler.instance), useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterAlgebraHandler.instance),
}, },
], ],
}) })

View File

@ -43,4 +43,4 @@ export class AddonFilterAlgebraHandlerService extends CoreFilterDefaultHandler {
} }
export class AddonFilterAlgebraHandler extends makeSingleton(AddonFilterAlgebraHandlerService) {} export const AddonFilterAlgebraHandler = makeSingleton(AddonFilterAlgebraHandlerService);

View File

@ -27,7 +27,7 @@ import { AddonFilterCensorHandler } from './services/handlers/censor';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
deps: [], deps: [],
useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterCensorHandler.instance), useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterCensorHandler.instance),
}, },
], ],
}) })

View File

@ -43,4 +43,4 @@ export class AddonFilterCensorHandlerService extends CoreFilterDefaultHandler {
} }
export class AddonFilterCensorHandler extends makeSingleton(AddonFilterCensorHandlerService) {} export const AddonFilterCensorHandler = makeSingleton(AddonFilterCensorHandlerService);

View File

@ -27,7 +27,7 @@ import { AddonFilterDataHandler } from './services/handlers/data';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
deps: [], deps: [],
useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterDataHandler.instance), useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterDataHandler.instance),
}, },
], ],
}) })

View File

@ -43,4 +43,4 @@ export class AddonFilterDataHandlerService extends CoreFilterDefaultHandler {
} }
export class AddonFilterDataHandler extends makeSingleton(AddonFilterDataHandlerService) {} export const AddonFilterDataHandler = makeSingleton(AddonFilterDataHandlerService);

View File

@ -27,7 +27,7 @@ import { AddonFilterDisplayH5PHandler } from './services/handlers/displayh5p';
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
multi: true, multi: true,
deps: [], deps: [],
useFactory: () => () => CoreFilterDelegate.instance.registerHandler(AddonFilterDisplayH5PHandler.instance), useFactory: () => () => CoreFilterDelegate.registerHandler(AddonFilterDisplayH5PHandler.instance),
}, },
], ],
}) })

View File

@ -109,4 +109,4 @@ export class AddonFilterDisplayH5PHandlerService extends CoreFilterDefaultHandle
} }
export class AddonFilterDisplayH5PHandler extends makeSingleton(AddonFilterDisplayH5PHandlerService) {} export const AddonFilterDisplayH5PHandler = makeSingleton(AddonFilterDisplayH5PHandlerService);

Some files were not shown because too many files have changed in this diff Show More