From 0d3123d2af20a3da8d2156e16dceef27cf2475f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Thu, 9 Sep 2021 13:37:51 +0200 Subject: [PATCH] MOBILE-3833 sites: Add required current site function to solve warnings --- .../pages/issued-badge/issued-badge.page.ts | 2 +- .../timeline/components/timeline/timeline.ts | 6 +- .../pages/edit-event/edit-event.page.ts | 2 +- .../services/handlers/user-send-message.ts | 2 +- src/addons/mod/book/services/book.ts | 2 +- src/addons/mod/data/services/data-helper.ts | 2 +- src/addons/mod/feedback/pages/form/form.ts | 2 +- .../post-options-menu/post-options-menu.ts | 2 +- .../forum/pages/discussion/discussion.page.ts | 4 +- .../mod/h5pactivity/components/index/index.ts | 2 +- .../mod/resource/services/resource-helper.ts | 2 +- .../mod/scorm/services/scorm-offline.ts | 2 +- src/addons/mod/wiki/components/index/index.ts | 2 +- .../mod/wiki/services/handlers/module.ts | 25 +----- src/addons/mod/wiki/wiki-lazy.module.ts | 4 + .../features/course/services/course-helper.ts | 88 +++++++++++-------- .../services/handlers/default-module.ts | 2 +- src/core/services/sites.ts | 25 ++++-- 18 files changed, 92 insertions(+), 84 deletions(-) diff --git a/src/addons/badges/pages/issued-badge/issued-badge.page.ts b/src/addons/badges/pages/issued-badge/issued-badge.page.ts index 038dcc365..959ac2dac 100644 --- a/src/addons/badges/pages/issued-badge/issued-badge.page.ts +++ b/src/addons/badges/pages/issued-badge/issued-badge.page.ts @@ -52,7 +52,7 @@ export class AddonBadgesIssuedBadgePage implements OnInit { */ ngOnInit(): void { this.courseId = CoreNavigator.getRouteNumberParam('courseId') || this.courseId; // Use 0 for site badges. - this.userId = CoreNavigator.getRouteNumberParam('userId') || CoreSites.getCurrentSite()!.getUserId(); + this.userId = CoreNavigator.getRouteNumberParam('userId') || CoreSites.getRequiredCurrentSite().getUserId(); this.badgeHash = CoreNavigator.getRouteParam('badgeHash') || ''; this.fetchIssuedBadge().finally(() => { diff --git a/src/addons/block/timeline/components/timeline/timeline.ts b/src/addons/block/timeline/components/timeline/timeline.ts index 9c5547050..29f2e1487 100644 --- a/src/addons/block/timeline/components/timeline/timeline.ts +++ b/src/addons/block/timeline/components/timeline/timeline.ts @@ -69,12 +69,12 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen * Component being initialized. */ async ngOnInit(): Promise { - this.currentSite = CoreSites.getCurrentSite(); + this.currentSite = CoreSites.getRequiredCurrentSite(); - this.filter = await this.currentSite!.getLocalSiteConfig('AddonBlockTimelineFilter', this.filter); + this.filter = await this.currentSite.getLocalSiteConfig('AddonBlockTimelineFilter', this.filter); this.switchFilter(this.filter); - this.sort = await this.currentSite!.getLocalSiteConfig('AddonBlockTimelineSort', this.sort); + this.sort = await this.currentSite.getLocalSiteConfig('AddonBlockTimelineSort', this.sort); super.ngOnInit(); } diff --git a/src/addons/calendar/pages/edit-event/edit-event.page.ts b/src/addons/calendar/pages/edit-event/edit-event.page.ts index fa21d737d..fee73d0aa 100644 --- a/src/addons/calendar/pages/edit-event/edit-event.page.ts +++ b/src/addons/calendar/pages/edit-event/edit-event.page.ts @@ -96,7 +96,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy, CanLeave { protected fb: FormBuilder, @Optional() protected svComponent: CoreSplitViewComponent, ) { - this.currentSite = CoreSites.getCurrentSite()!; + this.currentSite = CoreSites.getRequiredCurrentSite(); this.errors = { required: Translate.instant('core.required'), }; diff --git a/src/addons/messages/services/handlers/user-send-message.ts b/src/addons/messages/services/handlers/user-send-message.ts index 548d69d51..6afaa6080 100644 --- a/src/addons/messages/services/handlers/user-send-message.ts +++ b/src/addons/messages/services/handlers/user-send-message.ts @@ -54,7 +54,7 @@ export class AddonMessagesSendMessageUserHandlerService implements CoreUserProfi * @return Promise resolved with true if enabled, resolved with false otherwise. */ async isEnabledForUser(user: CoreUserProfile): Promise { - const currentSite = CoreSites.getCurrentSite()!; + const currentSite = CoreSites.getRequiredCurrentSite(); // From 3.7 you can send messages to yourself. return user.id != CoreSites.getCurrentSiteUserId() || currentSite.isVersionGreaterEqualThan('3.7'); diff --git a/src/addons/mod/book/services/book.ts b/src/addons/mod/book/services/book.ts index 7abf1dead..edf9c5800 100644 --- a/src/addons/mod/book/services/book.ts +++ b/src/addons/mod/book/services/book.ts @@ -134,7 +134,7 @@ export class AddonModBookProvider { if (!CoreFile.isAvailable()) { // We return the live URL. - return CoreSites.getCurrentSite()!.checkAndFixPluginfileURL(indexUrl); + return CoreSites.getRequiredCurrentSite().checkAndFixPluginfileURL(indexUrl); } const siteId = CoreSites.getCurrentSiteId(); diff --git a/src/addons/mod/data/services/data-helper.ts b/src/addons/mod/data/services/data-helper.ts index c0a0cc74f..869f2be38 100644 --- a/src/addons/mod/data/services/data-helper.ts +++ b/src/addons/mod/data/services/data-helper.ts @@ -225,7 +225,7 @@ export class AddonModDataHelperProvider { let render = ''; if (action == AddonModDataAction.MOREURL) { // Render more url directly because it can be part of an HTML attribute. - render = CoreSites.getCurrentSite()!.getURL() + '/mod/data/view.php?d={{database.id}}&rid=' + entry.id; + render = CoreSites.getRequiredCurrentSite().getURL() + '/mod/data/view.php?d={{database.id}}&rid=' + entry.id; } else if (action == 'approvalstatus') { render = Translate.instant('addon.mod_data.' + (entry.approved ? 'approved' : 'notapproved')); } else { diff --git a/src/addons/mod/feedback/pages/form/form.ts b/src/addons/mod/feedback/pages/form/form.ts index 8d8612304..d88967c29 100644 --- a/src/addons/mod/feedback/pages/form/form.ts +++ b/src/addons/mod/feedback/pages/form/form.ts @@ -77,7 +77,7 @@ export class AddonModFeedbackFormPage implements OnInit, OnDestroy, CanLeave { completedOffline = false; constructor() { - this.currentSite = CoreSites.getCurrentSite()!; + this.currentSite = CoreSites.getRequiredCurrentSite(); // Refresh online status when changes. this.onlineObserver = Network.onChange().subscribe(() => { diff --git a/src/addons/mod/forum/components/post-options-menu/post-options-menu.ts b/src/addons/mod/forum/components/post-options-menu/post-options-menu.ts index 8c7a51b87..fd1662e5a 100644 --- a/src/addons/mod/forum/components/post-options-menu/post-options-menu.ts +++ b/src/addons/mod/forum/components/post-options-menu/post-options-menu.ts @@ -58,7 +58,7 @@ export class AddonModForumPostOptionsMenuComponent implements OnInit, OnDestroy }); if (this.post.id > 0) { - const site = CoreSites.getCurrentSite()!; + const site = CoreSites.getRequiredCurrentSite(); this.url = site.createSiteUrl('/mod/forum/discuss.php', { d: this.post.discussionid.toString() }, 'p' + this.post.id); this.offlinePost = false; } else { diff --git a/src/addons/mod/forum/pages/discussion/discussion.page.ts b/src/addons/mod/forum/pages/discussion/discussion.page.ts index 44452fe37..34522f5b6 100644 --- a/src/addons/mod/forum/pages/discussion/discussion.page.ts +++ b/src/addons/mod/forum/pages/discussion/discussion.page.ts @@ -298,7 +298,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes */ protected async getUserSort(): Promise { try { - const value = await CoreSites.getCurrentSite()!.getLocalSiteConfig('AddonModForumDiscussionSort'); + const value = await CoreSites.getRequiredCurrentSite().getLocalSiteConfig('AddonModForumDiscussionSort'); return value; } catch (error) { @@ -656,7 +656,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes changeSort(type: SortType): Promise { this.discussionLoaded = false; this.sort = type; - CoreSites.getCurrentSite()!.setLocalSiteConfig('AddonModForumDiscussionSort', this.sort); + CoreSites.getRequiredCurrentSite().setLocalSiteConfig('AddonModForumDiscussionSort', this.sort); this.content.scrollToTop(); return this.fetchPosts(); diff --git a/src/addons/mod/h5pactivity/components/index/index.ts b/src/addons/mod/h5pactivity/components/index/index.ts index 37989271f..d7bd10f69 100644 --- a/src/addons/mod/h5pactivity/components/index/index.ts +++ b/src/addons/mod/h5pactivity/components/index/index.ts @@ -96,7 +96,7 @@ export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActiv ) { super('AddonModH5PActivityIndexComponent', content, courseContentsPage); - this.site = CoreSites.getCurrentSite()!; + this.site = CoreSites.getRequiredCurrentSite(); this.siteCanDownload = this.site.canDownloadFiles() && !CoreH5P.isOfflineDisabledInSite(); // Listen for messages from the iframe. diff --git a/src/addons/mod/resource/services/resource-helper.ts b/src/addons/mod/resource/services/resource-helper.ts index b942f7e36..4cb2ccad1 100644 --- a/src/addons/mod/resource/services/resource-helper.ts +++ b/src/addons/mod/resource/services/resource-helper.ts @@ -83,7 +83,7 @@ export class AddonModResourceHelperProvider { // Error getting directory, there was an error downloading or we're in browser. Return online URL. if (CoreApp.isOnline() && mainFile.fileurl) { // This URL is going to be injected in an iframe, we need this to make it work. - return CoreSites.getCurrentSite()!.checkAndFixPluginfileURL(mainFile.fileurl); + return CoreSites.getRequiredCurrentSite().checkAndFixPluginfileURL(mainFile.fileurl); } throw e; diff --git a/src/addons/mod/scorm/services/scorm-offline.ts b/src/addons/mod/scorm/services/scorm-offline.ts index 58b3f349d..2971656e9 100644 --- a/src/addons/mod/scorm/services/scorm-offline.ts +++ b/src/addons/mod/scorm/services/scorm-offline.ts @@ -730,7 +730,7 @@ export class AddonModScormOfflineProvider { } const scoUserData = scoData?.userdata || {}; - const db = CoreSites.getCurrentSite()!.getDb(); + const db = CoreSites.getRequiredCurrentSite().getDb(); let lessonStatusInserted = false; if (forceCompleted) { diff --git a/src/addons/mod/wiki/components/index/index.ts b/src/addons/mod/wiki/components/index/index.ts index e0a5f3da2..8bbd2a3a8 100644 --- a/src/addons/mod/wiki/components/index/index.ts +++ b/src/addons/mod/wiki/components/index/index.ts @@ -664,7 +664,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp content = content.trim(); if (content.length > 0) { - const editUrl = CoreTextUtils.concatenatePaths(CoreSites.getCurrentSite()!.getURL(), '/mod/wiki/edit.php'); + const editUrl = CoreTextUtils.concatenatePaths(CoreSites.getRequiredCurrentSite().getURL(), '/mod/wiki/edit.php'); content = content.replace(/href="edit\.php/g, 'href="' + editUrl); } diff --git a/src/addons/mod/wiki/services/handlers/module.ts b/src/addons/mod/wiki/services/handlers/module.ts index 0bdd46414..33b5af3aa 100644 --- a/src/addons/mod/wiki/services/handlers/module.ts +++ b/src/addons/mod/wiki/services/handlers/module.ts @@ -15,10 +15,7 @@ import { CoreConstants } from '@/core/constants'; import { Injectable, Type } from '@angular/core'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; -import { CoreCourse, CoreCourseAnyModuleData } from '@features/course/services/course'; -import { CoreCourseModule } from '@features/course/services/course-helper'; -import { CoreCourseModuleHandler, CoreCourseModuleHandlerData } from '@features/course/services/module-delegate'; -import { CoreNavigationOptions, CoreNavigator } from '@services/navigator'; +import { CoreCourseModuleHandler } from '@features/course/services/module-delegate'; import { makeSingleton } from '@singletons'; import { AddonModWikiIndexComponent } from '../../components/index'; @@ -47,26 +44,6 @@ export class AddonModWikiModuleHandlerService extends CoreModuleHandlerBase impl [CoreConstants.FEATURE_COMMENT]: true, }; - /** - * @inheritdoc - */ - getData(module: CoreCourseAnyModuleData): CoreCourseModuleHandlerData { - return { - icon: CoreCourse.getModuleIconSrc(this.modName, 'modicon' in module ? module.modicon : undefined), - title: module.name, - class: 'addon-mod_wiki-handler', - showDownloadButton: true, - action: (event: Event, module: CoreCourseModule, courseId: number, options?: CoreNavigationOptions) => { - options = options || {}; - options.params = options.params || {}; - Object.assign(options.params, { module }); - const routeParams = `/${courseId}/${module.id}/page/root`; - - CoreNavigator.navigateToSitePath(AddonModWikiModuleHandlerService.PAGE_NAME + routeParams, options); - }, - }; - } - /** * @inheritdoc */ diff --git a/src/addons/mod/wiki/wiki-lazy.module.ts b/src/addons/mod/wiki/wiki-lazy.module.ts index 37015b8f4..3c7225328 100644 --- a/src/addons/mod/wiki/wiki-lazy.module.ts +++ b/src/addons/mod/wiki/wiki-lazy.module.ts @@ -22,6 +22,10 @@ import { CanLeaveGuard } from '@guards/can-leave'; import { AddonModWikiEditPage } from './pages/edit/edit'; const routes: Routes = [ + { + path: ':courseId/:cmId', + redirectTo: ':courseId/:cmId/page/root', + }, { path: ':courseId/:cmId/page/:hash', component: AddonModWikiIndexPage, diff --git a/src/core/features/course/services/course-helper.ts b/src/core/features/course/services/course-helper.ts index 725381272..9a8d1ffc4 100644 --- a/src/core/features/course/services/course-helper.ts +++ b/src/core/features/course/services/course-helper.ts @@ -78,17 +78,17 @@ export type CoreCourseModulePrefetchInfo = { /** * Downloaded size. */ - size?: number; + size: number; /** * Downloadable size in a readable format. */ - sizeReadable?: string; + sizeReadable: string; /** * Module status. */ - status?: string; + status: string; /** * Icon's name of the module status. @@ -98,12 +98,12 @@ export type CoreCourseModulePrefetchInfo = { /** * Time when the module was last downloaded. */ - downloadTime?: number; + downloadTime: number; /** * Download time in a readable format. */ - downloadTimeReadable?: string; + downloadTimeReadable: string; }; /** @@ -539,18 +539,14 @@ export class CoreCourseHelperProvider { total: true, }; - if (!section && !sections) { - throw new CoreError('Either section or list of sections needs to be supplied.'); - } - // Calculate the size of the download. if (section && section.id != CoreCourseProvider.ALL_SECTIONS_ID) { sizeSum = await CoreCourseModulePrefetchDelegate.getDownloadSize(section.modules, courseId); // Check if the section has embedded files in the description. hasEmbeddedFiles = CoreFilepool.extractDownloadableFilesFromHtml(section.summary).length > 0; - } else { - await Promise.all(sections!.map(async (section) => { + } else if (sections) { + await Promise.all(sections.map(async (section) => { if (section.id == CoreCourseProvider.ALL_SECTIONS_ID) { return; } @@ -565,6 +561,8 @@ export class CoreCourseHelperProvider { hasEmbeddedFiles = true; } })); + } else { + throw new CoreError('Either section or list of sections needs to be supplied.'); } if (hasEmbeddedFiles) { @@ -1057,7 +1055,7 @@ export class CoreCourseHelperProvider { const moduleInfo = await this.getModulePrefetchInfo(module, courseId, invalidateCache, component); - instance.size = moduleInfo.size && moduleInfo.size > 0 ? moduleInfo.sizeReadable! : ''; + instance.size = moduleInfo.sizeReadable; instance.prefetchStatusIcon = moduleInfo.statusIcon; instance.prefetchStatus = moduleInfo.status; @@ -1443,7 +1441,7 @@ export class CoreCourseHelperProvider { invalidateCache?: boolean, component?: string, ): Promise { - const moduleInfo: CoreCourseModulePrefetchInfo = {}; + const siteId = CoreSites.getCurrentSiteId(); if (invalidateCache) { @@ -1459,45 +1457,59 @@ export class CoreCourseHelperProvider { ]); // Treat stored size. - moduleInfo.size = results[0]; - moduleInfo.sizeReadable = CoreTextUtils.bytesToSize(results[0], 2); + const size = results[0]; + const sizeReadable = CoreTextUtils.bytesToSize(results[0], 2); // Treat module status. - moduleInfo.status = results[1]; + const status = results[1]; + let statusIcon: string | undefined; switch (results[1]) { case CoreConstants.NOT_DOWNLOADED: - moduleInfo.statusIcon = CoreConstants.ICON_NOT_DOWNLOADED; + statusIcon = CoreConstants.ICON_NOT_DOWNLOADED; break; case CoreConstants.DOWNLOADING: - moduleInfo.statusIcon = CoreConstants.ICON_DOWNLOADING; + statusIcon = CoreConstants.ICON_DOWNLOADING; break; case CoreConstants.OUTDATED: - moduleInfo.statusIcon = CoreConstants.ICON_OUTDATED; + statusIcon = CoreConstants.ICON_OUTDATED; break; case CoreConstants.DOWNLOADED: break; default: - moduleInfo.statusIcon = ''; + statusIcon = ''; break; } // Treat download time. if (!results[2] || !results[2].downloadTime || !CoreFileHelper.isStateDownloaded(results[2].status || '')) { // Not downloaded. - moduleInfo.downloadTime = 0; - - return moduleInfo; + return { + size, + sizeReadable, + status, + statusIcon, + downloadTime: 0, + downloadTimeReadable: '', + }; } const now = CoreTimeUtils.timestamp(); - moduleInfo.downloadTime = results[2].downloadTime; + const downloadTime = results[2].downloadTime; + let downloadTimeReadable = ''; if (now - results[2].downloadTime < 7 * 86400) { - moduleInfo.downloadTimeReadable = moment(results[2].downloadTime * 1000).fromNow(); + downloadTimeReadable = moment(results[2].downloadTime * 1000).fromNow(); } else { - moduleInfo.downloadTimeReadable = moment(results[2].downloadTime * 1000).calendar(); + downloadTimeReadable = moment(results[2].downloadTime * 1000).calendar(); } - return moduleInfo; + return { + size, + sizeReadable, + status, + statusIcon, + downloadTime, + downloadTimeReadable, + }; } /** @@ -1690,20 +1702,20 @@ export class CoreCourseHelperProvider { courseMenuHandlers: CoreCourseOptionsMenuHandlerToDisplay[], siteId?: string, ): Promise { - siteId = siteId || CoreSites.getCurrentSiteId(); + const requiredSiteId = siteId || CoreSites.getRequiredCurrentSite().getId(); - if (this.courseDwnPromises[siteId] && this.courseDwnPromises[siteId][course.id]) { + if (this.courseDwnPromises[requiredSiteId] && this.courseDwnPromises[requiredSiteId][course.id] !== undefined) { // There's already a download ongoing for this course, return the promise. - return this.courseDwnPromises[siteId][course.id]; - } else if (!this.courseDwnPromises[siteId]) { - this.courseDwnPromises[siteId] = {}; + return this.courseDwnPromises[requiredSiteId][course.id]; + } else if (!this.courseDwnPromises[requiredSiteId]) { + this.courseDwnPromises[requiredSiteId] = {}; } // First of all, mark the course as being downloaded. - this.courseDwnPromises[siteId][course.id] = CoreCourse.setCourseStatus( + this.courseDwnPromises[requiredSiteId][course.id] = CoreCourse.setCourseStatus( course.id, CoreConstants.DOWNLOADING, - siteId, + requiredSiteId, ).then(async () => { const promises: Promise[] = []; @@ -1740,17 +1752,17 @@ export class CoreCourseHelperProvider { await CoreUtils.allPromises(promises); // Download success, mark the course as downloaded. - return CoreCourse.setCourseStatus(course.id, CoreConstants.DOWNLOADED, siteId); + return CoreCourse.setCourseStatus(course.id, CoreConstants.DOWNLOADED, requiredSiteId); }).catch(async (error) => { // Error, restore previous status. - await CoreCourse.setCoursePreviousStatus(course.id, siteId); + await CoreCourse.setCoursePreviousStatus(course.id, requiredSiteId); throw error; }).finally(() => { - delete this.courseDwnPromises[siteId!][course.id]; + delete this.courseDwnPromises[requiredSiteId][course.id]; }); - return this.courseDwnPromises[siteId][course.id]; + return this.courseDwnPromises[requiredSiteId][course.id]; } /** diff --git a/src/core/features/course/services/handlers/default-module.ts b/src/core/features/course/services/handlers/default-module.ts index cda24c8a9..75dfd0586 100644 --- a/src/core/features/course/services/handlers/default-module.ts +++ b/src/core/features/course/services/handlers/default-module.ts @@ -70,7 +70,7 @@ export class CoreCourseModuleDefaultHandler implements CoreCourseModuleHandler { e.preventDefault(); e.stopPropagation(); - CoreSites.requireCurrentSite().openInBrowserWithAutoLoginIfSameSite(url); + CoreSites.getRequiredCurrentSite().openInBrowserWithAutoLoginIfSameSite(url); }, }]; } diff --git a/src/core/services/sites.ts b/src/core/services/sites.ts index 85de9ea31..38a35cd28 100644 --- a/src/core/services/sites.ts +++ b/src/core/services/sites.ts @@ -305,7 +305,7 @@ export class CoreSitesProvider { if (data.errorcode && (data.errorcode == 'enablewsdescription' || data.errorcode == 'requirecorrectaccess')) { throw new CoreSiteError({ errorcode: data.errorcode, - message: data.error!, + message: data.error ?? '', }); } @@ -816,11 +816,24 @@ export class CoreSitesProvider { } /** - * Get current site. + * Get current site or undefined if none. + * + * @return Current site or undefined if none. + */ + getCurrentSite(): CoreSite | undefined { + return this.currentSite; + } + + /** + * Get current site or fail if none. * * @return Current site. */ - getCurrentSite(): CoreSite | undefined { + getRequiredCurrentSite(): CoreSite { + if (!this.currentSite) { + throw new CoreError('You aren\'t authenticated in any site.'); + } + return this.currentSite; } @@ -1487,7 +1500,9 @@ export class CoreSitesProvider { return Promise.resolve(); } - if (this.siteSchemasMigration[site.id]) { + const siteId = site.id; + + if (this.siteSchemasMigration[site.id] !== undefined) { return this.siteSchemasMigration[site.id]; } @@ -1500,7 +1515,7 @@ export class CoreSitesProvider { this.siteSchemasMigration[site.id] = promise; return promise.finally(() => { - delete this.siteSchemasMigration[site.id!]; + delete this.siteSchemasMigration[siteId]; }); }