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 { ngOnInit(): void {
this.courseId = CoreNavigator.getRouteNumberParam('courseId') || this.courseId; // Use 0 for site badges. 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.badgeHash = CoreNavigator.getRouteParam('badgeHash') || '';
this.fetchIssuedBadge().finally(() => { this.fetchIssuedBadge().finally(() => {

View File

@ -69,12 +69,12 @@ export class AddonBlockTimelineComponent extends CoreBlockBaseComponent implemen
* Component being initialized. * Component being initialized.
*/ */
async ngOnInit(): Promise<void> { 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.switchFilter(this.filter);
this.sort = await this.currentSite!.getLocalSiteConfig('AddonBlockTimelineSort', this.sort); this.sort = await this.currentSite.getLocalSiteConfig('AddonBlockTimelineSort', this.sort);
super.ngOnInit(); super.ngOnInit();
} }

View File

@ -96,7 +96,7 @@ export class AddonCalendarEditEventPage implements OnInit, OnDestroy, CanLeave {
protected fb: FormBuilder, protected fb: FormBuilder,
@Optional() protected svComponent: CoreSplitViewComponent, @Optional() protected svComponent: CoreSplitViewComponent,
) { ) {
this.currentSite = CoreSites.getCurrentSite()!; this.currentSite = CoreSites.getRequiredCurrentSite();
this.errors = { this.errors = {
required: Translate.instant('core.required'), 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. * @return Promise resolved with true if enabled, resolved with false otherwise.
*/ */
async isEnabledForUser(user: CoreUserProfile): Promise<boolean> { async isEnabledForUser(user: CoreUserProfile): Promise<boolean> {
const currentSite = CoreSites.getCurrentSite()!; const currentSite = CoreSites.getRequiredCurrentSite();
// From 3.7 you can send messages to yourself. // From 3.7 you can send messages to yourself.
return user.id != CoreSites.getCurrentSiteUserId() || currentSite.isVersionGreaterEqualThan('3.7'); return user.id != CoreSites.getCurrentSiteUserId() || currentSite.isVersionGreaterEqualThan('3.7');

View File

@ -134,7 +134,7 @@ export class AddonModBookProvider {
if (!CoreFile.isAvailable()) { if (!CoreFile.isAvailable()) {
// We return the live URL. // We return the live URL.
return CoreSites.getCurrentSite()!.checkAndFixPluginfileURL(indexUrl); return CoreSites.getRequiredCurrentSite().checkAndFixPluginfileURL(indexUrl);
} }
const siteId = CoreSites.getCurrentSiteId(); const siteId = CoreSites.getCurrentSiteId();

View File

@ -225,7 +225,7 @@ export class AddonModDataHelperProvider {
let render = ''; let render = '';
if (action == AddonModDataAction.MOREURL) { if (action == AddonModDataAction.MOREURL) {
// Render more url directly because it can be part of an HTML attribute. // 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') { } else if (action == 'approvalstatus') {
render = Translate.instant('addon.mod_data.' + (entry.approved ? 'approved' : 'notapproved')); render = Translate.instant('addon.mod_data.' + (entry.approved ? 'approved' : 'notapproved'));
} else { } else {

View File

@ -77,7 +77,7 @@ export class AddonModFeedbackFormPage implements OnInit, OnDestroy, CanLeave {
completedOffline = false; completedOffline = false;
constructor() { constructor() {
this.currentSite = CoreSites.getCurrentSite()!; this.currentSite = CoreSites.getRequiredCurrentSite();
// Refresh online status when changes. // Refresh online status when changes.
this.onlineObserver = Network.onChange().subscribe(() => { this.onlineObserver = Network.onChange().subscribe(() => {

View File

@ -58,7 +58,7 @@ export class AddonModForumPostOptionsMenuComponent implements OnInit, OnDestroy
}); });
if (this.post.id > 0) { 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.url = site.createSiteUrl('/mod/forum/discuss.php', { d: this.post.discussionid.toString() }, 'p' + this.post.id);
this.offlinePost = false; this.offlinePost = false;
} else { } else {

View File

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

View File

@ -96,7 +96,7 @@ export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActiv
) { ) {
super('AddonModH5PActivityIndexComponent', content, courseContentsPage); super('AddonModH5PActivityIndexComponent', content, courseContentsPage);
this.site = CoreSites.getCurrentSite()!; this.site = CoreSites.getRequiredCurrentSite();
this.siteCanDownload = this.site.canDownloadFiles() && !CoreH5P.isOfflineDisabledInSite(); this.siteCanDownload = this.site.canDownloadFiles() && !CoreH5P.isOfflineDisabledInSite();
// Listen for messages from the iframe. // 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. // Error getting directory, there was an error downloading or we're in browser. Return online URL.
if (CoreApp.isOnline() && mainFile.fileurl) { if (CoreApp.isOnline() && mainFile.fileurl) {
// This URL is going to be injected in an iframe, we need this to make it work. // 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; throw e;

View File

@ -730,7 +730,7 @@ export class AddonModScormOfflineProvider {
} }
const scoUserData = scoData?.userdata || {}; const scoUserData = scoData?.userdata || {};
const db = CoreSites.getCurrentSite()!.getDb(); const db = CoreSites.getRequiredCurrentSite().getDb();
let lessonStatusInserted = false; let lessonStatusInserted = false;
if (forceCompleted) { if (forceCompleted) {

View File

@ -664,7 +664,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp
content = content.trim(); content = content.trim();
if (content.length > 0) { 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); content = content.replace(/href="edit\.php/g, 'href="' + editUrl);
} }

View File

@ -15,10 +15,7 @@
import { CoreConstants } from '@/core/constants'; import { CoreConstants } from '@/core/constants';
import { Injectable, Type } from '@angular/core'; import { Injectable, Type } from '@angular/core';
import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler'; import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler';
import { CoreCourse, CoreCourseAnyModuleData } from '@features/course/services/course'; import { CoreCourseModuleHandler } from '@features/course/services/module-delegate';
import { CoreCourseModule } from '@features/course/services/course-helper';
import { CoreCourseModuleHandler, CoreCourseModuleHandlerData } from '@features/course/services/module-delegate';
import { CoreNavigationOptions, CoreNavigator } from '@services/navigator';
import { makeSingleton } from '@singletons'; import { makeSingleton } from '@singletons';
import { AddonModWikiIndexComponent } from '../../components/index'; import { AddonModWikiIndexComponent } from '../../components/index';
@ -47,26 +44,6 @@ export class AddonModWikiModuleHandlerService extends CoreModuleHandlerBase impl
[CoreConstants.FEATURE_COMMENT]: true, [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 * @inheritdoc
*/ */

View File

@ -22,6 +22,10 @@ import { CanLeaveGuard } from '@guards/can-leave';
import { AddonModWikiEditPage } from './pages/edit/edit'; import { AddonModWikiEditPage } from './pages/edit/edit';
const routes: Routes = [ const routes: Routes = [
{
path: ':courseId/:cmId',
redirectTo: ':courseId/:cmId/page/root',
},
{ {
path: ':courseId/:cmId/page/:hash', path: ':courseId/:cmId/page/:hash',
component: AddonModWikiIndexPage, component: AddonModWikiIndexPage,

View File

@ -78,17 +78,17 @@ export type CoreCourseModulePrefetchInfo = {
/** /**
* Downloaded size. * Downloaded size.
*/ */
size?: number; size: number;
/** /**
* Downloadable size in a readable format. * Downloadable size in a readable format.
*/ */
sizeReadable?: string; sizeReadable: string;
/** /**
* Module status. * Module status.
*/ */
status?: string; status: string;
/** /**
* Icon's name of the module status. * Icon's name of the module status.
@ -98,12 +98,12 @@ export type CoreCourseModulePrefetchInfo = {
/** /**
* Time when the module was last downloaded. * Time when the module was last downloaded.
*/ */
downloadTime?: number; downloadTime: number;
/** /**
* Download time in a readable format. * Download time in a readable format.
*/ */
downloadTimeReadable?: string; downloadTimeReadable: string;
}; };
/** /**
@ -539,18 +539,14 @@ export class CoreCourseHelperProvider {
total: true, total: true,
}; };
if (!section && !sections) {
throw new CoreError('Either section or list of sections needs to be supplied.');
}
// Calculate the size of the download. // Calculate the size of the download.
if (section && section.id != CoreCourseProvider.ALL_SECTIONS_ID) { if (section && section.id != CoreCourseProvider.ALL_SECTIONS_ID) {
sizeSum = await CoreCourseModulePrefetchDelegate.getDownloadSize(section.modules, courseId); sizeSum = await CoreCourseModulePrefetchDelegate.getDownloadSize(section.modules, courseId);
// Check if the section has embedded files in the description. // Check if the section has embedded files in the description.
hasEmbeddedFiles = CoreFilepool.extractDownloadableFilesFromHtml(section.summary).length > 0; hasEmbeddedFiles = CoreFilepool.extractDownloadableFilesFromHtml(section.summary).length > 0;
} else { } else if (sections) {
await Promise.all(sections!.map(async (section) => { await Promise.all(sections.map(async (section) => {
if (section.id == CoreCourseProvider.ALL_SECTIONS_ID) { if (section.id == CoreCourseProvider.ALL_SECTIONS_ID) {
return; return;
} }
@ -565,6 +561,8 @@ export class CoreCourseHelperProvider {
hasEmbeddedFiles = true; hasEmbeddedFiles = true;
} }
})); }));
} else {
throw new CoreError('Either section or list of sections needs to be supplied.');
} }
if (hasEmbeddedFiles) { if (hasEmbeddedFiles) {
@ -1057,7 +1055,7 @@ export class CoreCourseHelperProvider {
const moduleInfo = await this.getModulePrefetchInfo(module, courseId, invalidateCache, component); 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.prefetchStatusIcon = moduleInfo.statusIcon;
instance.prefetchStatus = moduleInfo.status; instance.prefetchStatus = moduleInfo.status;
@ -1443,7 +1441,7 @@ export class CoreCourseHelperProvider {
invalidateCache?: boolean, invalidateCache?: boolean,
component?: string, component?: string,
): Promise<CoreCourseModulePrefetchInfo> { ): Promise<CoreCourseModulePrefetchInfo> {
const moduleInfo: CoreCourseModulePrefetchInfo = {};
const siteId = CoreSites.getCurrentSiteId(); const siteId = CoreSites.getCurrentSiteId();
if (invalidateCache) { if (invalidateCache) {
@ -1459,45 +1457,59 @@ export class CoreCourseHelperProvider {
]); ]);
// Treat stored size. // Treat stored size.
moduleInfo.size = results[0]; const size = results[0];
moduleInfo.sizeReadable = CoreTextUtils.bytesToSize(results[0], 2); const sizeReadable = CoreTextUtils.bytesToSize(results[0], 2);
// Treat module status. // Treat module status.
moduleInfo.status = results[1]; const status = results[1];
let statusIcon: string | undefined;
switch (results[1]) { switch (results[1]) {
case CoreConstants.NOT_DOWNLOADED: case CoreConstants.NOT_DOWNLOADED:
moduleInfo.statusIcon = CoreConstants.ICON_NOT_DOWNLOADED; statusIcon = CoreConstants.ICON_NOT_DOWNLOADED;
break; break;
case CoreConstants.DOWNLOADING: case CoreConstants.DOWNLOADING:
moduleInfo.statusIcon = CoreConstants.ICON_DOWNLOADING; statusIcon = CoreConstants.ICON_DOWNLOADING;
break; break;
case CoreConstants.OUTDATED: case CoreConstants.OUTDATED:
moduleInfo.statusIcon = CoreConstants.ICON_OUTDATED; statusIcon = CoreConstants.ICON_OUTDATED;
break; break;
case CoreConstants.DOWNLOADED: case CoreConstants.DOWNLOADED:
break; break;
default: default:
moduleInfo.statusIcon = ''; statusIcon = '';
break; break;
} }
// Treat download time. // Treat download time.
if (!results[2] || !results[2].downloadTime || !CoreFileHelper.isStateDownloaded(results[2].status || '')) { if (!results[2] || !results[2].downloadTime || !CoreFileHelper.isStateDownloaded(results[2].status || '')) {
// Not downloaded. // Not downloaded.
moduleInfo.downloadTime = 0; return {
size,
return moduleInfo; sizeReadable,
status,
statusIcon,
downloadTime: 0,
downloadTimeReadable: '',
};
} }
const now = CoreTimeUtils.timestamp(); const now = CoreTimeUtils.timestamp();
moduleInfo.downloadTime = results[2].downloadTime; const downloadTime = results[2].downloadTime;
let downloadTimeReadable = '';
if (now - results[2].downloadTime < 7 * 86400) { if (now - results[2].downloadTime < 7 * 86400) {
moduleInfo.downloadTimeReadable = moment(results[2].downloadTime * 1000).fromNow(); downloadTimeReadable = moment(results[2].downloadTime * 1000).fromNow();
} else { } 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[], courseMenuHandlers: CoreCourseOptionsMenuHandlerToDisplay[],
siteId?: string, siteId?: string,
): Promise<void> { ): 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. // There's already a download ongoing for this course, return the promise.
return this.courseDwnPromises[siteId][course.id]; return this.courseDwnPromises[requiredSiteId][course.id];
} else if (!this.courseDwnPromises[siteId]) { } else if (!this.courseDwnPromises[requiredSiteId]) {
this.courseDwnPromises[siteId] = {}; this.courseDwnPromises[requiredSiteId] = {};
} }
// First of all, mark the course as being downloaded. // 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, course.id,
CoreConstants.DOWNLOADING, CoreConstants.DOWNLOADING,
siteId, requiredSiteId,
).then(async () => { ).then(async () => {
const promises: Promise<unknown>[] = []; const promises: Promise<unknown>[] = [];
@ -1740,17 +1752,17 @@ export class CoreCourseHelperProvider {
await CoreUtils.allPromises(promises); await CoreUtils.allPromises(promises);
// Download success, mark the course as downloaded. // 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) => { }).catch(async (error) => {
// Error, restore previous status. // Error, restore previous status.
await CoreCourse.setCoursePreviousStatus(course.id, siteId); await CoreCourse.setCoursePreviousStatus(course.id, requiredSiteId);
throw error; throw error;
}).finally(() => { }).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.preventDefault();
e.stopPropagation(); 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')) { if (data.errorcode && (data.errorcode == 'enablewsdescription' || data.errorcode == 'requirecorrectaccess')) {
throw new CoreSiteError({ throw new CoreSiteError({
errorcode: data.errorcode, 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. * @return Current site.
*/ */
getCurrentSite(): CoreSite | undefined { getRequiredCurrentSite(): CoreSite {
if (!this.currentSite) {
throw new CoreError('You aren\'t authenticated in any site.');
}
return this.currentSite; return this.currentSite;
} }
@ -1487,7 +1500,9 @@ export class CoreSitesProvider {
return Promise.resolve(); return Promise.resolve();
} }
if (this.siteSchemasMigration[site.id]) { const siteId = site.id;
if (this.siteSchemasMigration[site.id] !== undefined) {
return this.siteSchemasMigration[site.id]; return this.siteSchemasMigration[site.id];
} }
@ -1500,7 +1515,7 @@ export class CoreSitesProvider {
this.siteSchemasMigration[site.id] = promise; this.siteSchemasMigration[site.id] = promise;
return promise.finally(() => { return promise.finally(() => {
delete this.siteSchemasMigration[site.id!]; delete this.siteSchemasMigration[siteId];
}); });
} }