MOBILE-3833 sites: Add required current site function to solve warnings

main
Pau Ferrer Ocaña 2021-09-09 13:37:51 +02:00
parent d5d8962766
commit 0d3123d2af
18 changed files with 92 additions and 84 deletions

View File

@ -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(() => {

View File

@ -69,12 +69,12 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen
* Component being initialized.
*/
async ngOnInit(): Promise<void> {
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();
}

View File

@ -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'),
};

View File

@ -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<boolean> {
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');

View File

@ -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();

View File

@ -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 {

View File

@ -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(() => {

View File

@ -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 {

View File

@ -298,7 +298,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes
*/
protected async getUserSort(): Promise<SortType> {
try {
const value = await CoreSites.getCurrentSite()!.getLocalSiteConfig<SortType>('AddonModForumDiscussionSort');
const value = await CoreSites.getRequiredCurrentSite().getLocalSiteConfig<SortType>('AddonModForumDiscussionSort');
return value;
} catch (error) {
@ -656,7 +656,7 @@ export class AddonModForumDiscussionPage implements OnInit, AfterViewInit, OnDes
changeSort(type: SortType): Promise<void> {
this.discussionLoaded = false;
this.sort = type;
CoreSites.getCurrentSite()!.setLocalSiteConfig('AddonModForumDiscussionSort', this.sort);
CoreSites.getRequiredCurrentSite().setLocalSiteConfig('AddonModForumDiscussionSort', this.sort);
this.content.scrollToTop();
return this.fetchPosts();

View File

@ -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.

View File

@ -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;

View File

@ -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) {

View File

@ -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);
}

View File

@ -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
*/

View File

@ -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,

View File

@ -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<CoreCourseModulePrefetchInfo> {
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<void> {
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<unknown>[] = [];
@ -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];
}
/**

View File

@ -70,7 +70,7 @@ export class CoreCourseModuleDefaultHandler implements CoreCourseModuleHandler {
e.preventDefault();
e.stopPropagation();
CoreSites.requireCurrentSite().openInBrowserWithAutoLoginIfSameSite(url);
CoreSites.getRequiredCurrentSite().openInBrowserWithAutoLoginIfSameSite(url);
},
}];
}

View File

@ -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];
});
}