MOBILE-4596 wiki: Decouple handlers and components

main
Noel De Martin 2024-07-23 15:39:12 +02:00
parent 9943784c30
commit c491b613c8
13 changed files with 751 additions and 478 deletions

View File

@ -50,8 +50,7 @@ import {
AddonModWikiSyncWikiResult,
AddonModWikiSyncWikiSubwiki,
} from '../../services/wiki-sync';
import { AddonModWikiMapModalComponent, AddonModWikiMapModalReturn } from '../map/map';
import { AddonModWikiSubwikiPickerComponent } from '../subwiki-picker/subwiki-picker';
import { AddonModWikiMapModalReturn } from '../map/map';
import {
ADDON_MOD_WIKI_AUTO_SYNCED,
ADDON_MOD_WIKI_COMPONENT,
@ -665,6 +664,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp
*/
async openMap(): Promise<void> {
// Create the toc modal.
const { AddonModWikiMapModalComponent } = await import('../map/map');
const modalData = await CoreDomUtils.openSideModal<AddonModWikiMapModalReturn>({
component: AddonModWikiMapModalComponent,
componentProps: {
@ -883,6 +883,7 @@ export class AddonModWikiIndexComponent extends CoreCourseModuleMainActivityComp
* @param event Event.
*/
async showSubwikiPicker(event: MouseEvent): Promise<void> {
const { AddonModWikiSubwikiPickerComponent } = await import('../subwiki-picker/subwiki-picker');
const subwiki = await CoreDomUtils.openPopover<AddonModWikiSubwiki>({
component: AddonModWikiSubwikiPickerComponent,
componentProps: {

View File

@ -21,3 +21,9 @@ export const ADDON_MOD_WIKI_MANUAL_SYNCED = 'addon_mod_wiki_manual_synced';
export const ADDON_MOD_WIKI_PAGE_CREATED_EVENT = 'addon_mod_wiki_page_created';
export const ADDON_MOD_WIKI_RENEW_LOCK_TIME = 30000; // Milliseconds.
export const ADDON_MOD_WIKI_FEATURE_NAME = 'CoreCourseModuleDelegate_AddonModWiki';
export const ADDON_MOD_WIKI_PREFETCH_NAME = 'AddonModWiki';
export const ADDON_MOD_WIKI_PREFETCH_MODNAME = 'wiki';
export const ADDON_MOD_WIKI_PREFETCH_COMPONENT = ADDON_MOD_WIKI_COMPONENT;

View File

@ -0,0 +1,142 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CoreCourse } from '@features/course/services/course';
import { CoreNavigator } from '@services/navigator';
import { CoreSitesReadingStrategy } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { makeSingleton } from '@singletons';
import { AddonModWiki } from '../wiki';
import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants';
import { AddonModWikiCreateLinkHandlerService } from '@addons/mod/wiki/services/handlers/create-link';
/**
* Handler to treat links to create a wiki page.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiCreateLinkHandlerLazyService extends AddonModWikiCreateLinkHandlerService {
/**
* Check if the current view is a wiki page of the same wiki.
*
* @param route Activated route if current route is wiki index page, null otherwise.
* @param subwikiId Subwiki ID to check.
* @param siteId Site ID.
* @returns Promise resolved with boolean: whether current view belongs to the same wiki.
*/
protected async currentStateIsSameWiki(route: ActivatedRoute | null, subwikiId: number, siteId: string): Promise<boolean> {
if (!route) {
// Current view isn't wiki index.
return false;
}
const params = CoreNavigator.getRouteParams(route);
const queryParams = CoreNavigator.getRouteQueryParams(route);
if (queryParams.subwikiId == subwikiId) {
// Same subwiki, so it's same wiki.
return true;
}
const options = {
cmId: params.cmId,
readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE,
siteId,
};
if (queryParams.pageId) {
// Get the page contents to check the subwiki.
try {
const page = await AddonModWiki.getPageContents(queryParams.pageId, options);
return page.subwikiid == subwikiId;
} catch {
// Not found, check next case.
}
}
try {
// Get the wiki.
const wiki = await AddonModWiki.getWiki(params.courseId, params.cmId, options);
// Check if the subwiki belongs to this wiki.
return await AddonModWiki.wikiHasSubwiki(wiki.id, subwikiId, options);
} catch {
// Not found, return false.
return false;
}
}
/**
* @inheritdoc
*/
async handleAction(siteId: string, courseId: number, params: Record<string, string>): Promise<void> {
const modal = await CoreDomUtils.showModalLoading();
const { AddonModWikiIndexPage } = await import('../../pages/index');
try {
const route = CoreNavigator.getCurrentRoute({ pageComponent: AddonModWikiIndexPage });
if (!route) {
// Current view isn't wiki index.
return;
}
const subwikiId = parseInt(params.swid, 10);
const wikiId = parseInt(params.wid, 10);
let path = ADDON_MOD_WIKI_PAGE_NAME;
// Check if the link is inside the same wiki.
const isSameWiki = await this.currentStateIsSameWiki(route, subwikiId, siteId);
if (isSameWiki) {
// User is seeing the wiki, we can get the module from the wiki params.
const routeParams = CoreNavigator.getRouteParams(route);
path = path + `/${routeParams.courseId}/${routeParams.cmId}/edit`;
} else if (wikiId) {
// The URL specifies which wiki it belongs to. Get the module.
const module = await CoreCourse.getModuleBasicInfoByInstance(
wikiId,
'wiki',
{ siteId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
path = path + `/${module.course}/${module.id}/edit`;
} else {
// Cannot get module ID.
path = path + `/${courseId || 0}/0/edit`;
}
// Open the page.
CoreNavigator.navigateToSitePath(
path,
{
params: {
pageTitle: params.title,
subwikiId: subwikiId,
},
siteId,
},
);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_wiki.errorloadingpage', true);
} finally {
modal.dismiss();
}
}
}
export const AddonModWikiCreateLinkHandler = makeSingleton(AddonModWikiCreateLinkHandlerLazyService);

View File

@ -12,80 +12,18 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { asyncInstance } from '@/core/utils/async-instance';
import { ADDON_MOD_WIKI_FEATURE_NAME } from '@addons/mod/wiki/constants';
import { CoreContentLinksHandlerBase } from '@features/contentlinks/classes/base-handler';
import { CoreContentLinksAction } from '@features/contentlinks/services/contentlinks-delegate';
import { CoreCourse } from '@features/course/services/course';
import { CoreNavigator } from '@services/navigator';
import { CoreSitesReadingStrategy } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { makeSingleton } from '@singletons';
import { AddonModWikiIndexPage } from '../../pages/index';
import { AddonModWiki } from '../wiki';
import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants';
import { CoreContentLinksAction, CoreContentLinksHandler } from '@features/contentlinks/services/contentlinks-delegate';
import type { AddonModWikiCreateLinkHandlerLazyService } from '@addons/mod/wiki/services/handlers/create-link-lazy';
/**
* Handler to treat links to create a wiki page.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiCreateLinkHandlerService extends CoreContentLinksHandlerBase {
name = 'AddonModWikiCreateLinkHandler';
featureName = 'CoreCourseModuleDelegate_AddonModWiki';
featureName = ADDON_MOD_WIKI_FEATURE_NAME;
pattern = /\/mod\/wiki\/create\.php.*([&?]swid=\d+)/;
/**
* Check if the current view is a wiki page of the same wiki.
*
* @param route Activated route if current route is wiki index page, null otherwise.
* @param subwikiId Subwiki ID to check.
* @param siteId Site ID.
* @returns Promise resolved with boolean: whether current view belongs to the same wiki.
*/
protected async currentStateIsSameWiki(route: ActivatedRoute | null, subwikiId: number, siteId: string): Promise<boolean> {
if (!route) {
// Current view isn't wiki index.
return false;
}
const params = CoreNavigator.getRouteParams(route);
const queryParams = CoreNavigator.getRouteQueryParams(route);
if (queryParams.subwikiId == subwikiId) {
// Same subwiki, so it's same wiki.
return true;
}
const options = {
cmId: params.cmId,
readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE,
siteId,
};
if (queryParams.pageId) {
// Get the page contents to check the subwiki.
try {
const page = await AddonModWiki.getPageContents(queryParams.pageId, options);
return page.subwikiid == subwikiId;
} catch {
// Not found, check next case.
}
}
try {
// Get the wiki.
const wiki = await AddonModWiki.getWiki(params.courseId, params.cmId, options);
// Check if the subwiki belongs to this wiki.
return await AddonModWiki.wikiHasSubwiki(wiki.id, subwikiId, options);
} catch {
// Not found, return false.
return false;
}
}
/**
* @inheritdoc
*/
@ -94,65 +32,45 @@ export class AddonModWikiCreateLinkHandlerService extends CoreContentLinksHandle
url: string,
params: Record<string, string>,
courseId?: number,
): CoreContentLinksAction[] | Promise<CoreContentLinksAction[]> {
): CoreContentLinksAction[] {
courseId = Number(courseId || params.courseid || params.cid);
return [{
action: async (siteId: string) => {
const modal = await CoreDomUtils.showModalLoading();
try {
const route = CoreNavigator.getCurrentRoute({ pageComponent: AddonModWikiIndexPage });
if (!route) {
// Current view isn't wiki index.
return;
}
const subwikiId = parseInt(params.swid, 10);
const wikiId = parseInt(params.wid, 10);
let path = ADDON_MOD_WIKI_PAGE_NAME;
// Check if the link is inside the same wiki.
const isSameWiki = await this.currentStateIsSameWiki(route, subwikiId, siteId);
if (isSameWiki) {
// User is seeing the wiki, we can get the module from the wiki params.
const routeParams = CoreNavigator.getRouteParams(route);
path = path + `/${routeParams.courseId}/${routeParams.cmId}/edit`;
} else if (wikiId) {
// The URL specifies which wiki it belongs to. Get the module.
const module = await CoreCourse.getModuleBasicInfoByInstance(
wikiId,
'wiki',
{ siteId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
path = path + `/${module.course}/${module.id}/edit`;
} else {
// Cannot get module ID.
path = path + `/${courseId || 0}/0/edit`;
}
// Open the page.
CoreNavigator.navigateToSitePath(
path,
{
params: {
pageTitle: params.title,
subwikiId: subwikiId,
},
siteId,
},
);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_wiki.errorloadingpage', true);
} finally {
modal.dismiss();
}
},
action: (siteId) => this.handleAction(siteId, courseId, params),
}];
}
/**
* Handle link action.
*
* @param siteId Site id.
* @param courseId Course id.
* @param params Params.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async handleAction(siteId: string, courseId: number | undefined, params: Record<string, string>): Promise<void> {
// Stub to override.
}
}
export const AddonModWikiCreateLinkHandler = makeSingleton(AddonModWikiCreateLinkHandlerService);
/**
* Get create link handler instance.
*
* @returns Link handler.
*/
export function getCreateLinkHandlerInstance(): CoreContentLinksHandler {
const lazyHandler = asyncInstance<
AddonModWikiCreateLinkHandlerLazyService,
AddonModWikiCreateLinkHandlerService
>(async () => {
const { AddonModWikiCreateLinkHandler } = await import('./create-link-lazy');
return AddonModWikiCreateLinkHandler.instance;
});
lazyHandler.setEagerInstance(new AddonModWikiCreateLinkHandlerService());
lazyHandler.setLazyOverrides(['handleAction']);
return lazyHandler;
}

View File

@ -0,0 +1,72 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { CoreCourse } from '@features/course/services/course';
import { CoreNavigator } from '@services/navigator';
import { CoreSitesReadingStrategy } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { makeSingleton } from '@singletons';
import { AddonModWiki } from '../wiki';
import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants';
import { AddonModWikiEditLinkHandlerService } from '@addons/mod/wiki/services/handlers/edit-link';
/**
* Handler to treat links to edit a wiki page.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiEditLinkHandlerLazyService extends AddonModWikiEditLinkHandlerService {
/**
* @inheritdoc
*/
async handleAction(siteId: string, params: Record<string, string>): Promise<void> {
const modal = await CoreDomUtils.showModalLoading();
try {
const pageId = Number(params.pageid);
const pageContents = await AddonModWiki.getPageContents(pageId, { siteId });
const module = await CoreCourse.getModuleBasicInfoByInstance(
pageContents.wikiid,
'wiki',
{ siteId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
let section = '';
if (params.section !== undefined) {
section = params.section.replace(/\+/g, ' ');
}
await CoreNavigator.navigateToSitePath(
`${ADDON_MOD_WIKI_PAGE_NAME}/${module.course}/${module.id}/edit`,
{
params: {
section: section,
pageId: pageId,
},
siteId,
},
);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_wiki.errorloadingpage', true);
} finally {
modal.dismiss();
}
}
}
export const AddonModWikiEditLinkHandler = makeSingleton(AddonModWikiEditLinkHandlerLazyService);

View File

@ -12,75 +12,57 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { asyncInstance } from '@/core/utils/async-instance';
import { ADDON_MOD_WIKI_FEATURE_NAME } from '@addons/mod/wiki/constants';
import { CoreContentLinksHandlerBase } from '@features/contentlinks/classes/base-handler';
import { CoreContentLinksAction } from '@features/contentlinks/services/contentlinks-delegate';
import { CoreCourse } from '@features/course/services/course';
import { CoreNavigator } from '@services/navigator';
import { CoreSitesReadingStrategy } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { makeSingleton } from '@singletons';
import { AddonModWiki } from '../wiki';
import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants';
import { CoreContentLinksAction, CoreContentLinksHandler } from '@features/contentlinks/services/contentlinks-delegate';
import type { AddonModWikiEditLinkHandlerLazyService } from '@addons/mod/wiki/services/handlers/edit-link-lazy';
/**
* Handler to treat links to edit a wiki page.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiEditLinkHandlerService extends CoreContentLinksHandlerBase {
name = 'AddonModWikiEditLinkHandler';
featureName = 'CoreCourseModuleDelegate_AddonModWiki';
featureName = ADDON_MOD_WIKI_FEATURE_NAME;
pattern = /\/mod\/wiki\/edit\.php.*([&?]pageid=\d+)/;
/**
* @inheritdoc
*/
getActions(
siteIds: string[],
url: string,
params: Record<string, string>,
): CoreContentLinksAction[] | Promise<CoreContentLinksAction[]> {
getActions(siteIds: string[], url: string, params: Record<string, string>): CoreContentLinksAction[] {
return [{
action: async (siteId: string) => {
const modal = await CoreDomUtils.showModalLoading();
try {
const pageId = Number(params.pageid);
const pageContents = await AddonModWiki.getPageContents(pageId, { siteId });
const module = await CoreCourse.getModuleBasicInfoByInstance(
pageContents.wikiid,
'wiki',
{ siteId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
let section = '';
if (params.section !== undefined) {
section = params.section.replace(/\+/g, ' ');
}
await CoreNavigator.navigateToSitePath(
`${ADDON_MOD_WIKI_PAGE_NAME}/${module.course}/${module.id}/edit`,
{
params: {
section: section,
pageId: pageId,
},
siteId,
},
);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_wiki.errorloadingpage', true);
} finally {
modal.dismiss();
}
},
action: (siteId) => this.handleAction(siteId, params),
}];
}
/**
* Handle link action.
*
* @param siteId Site id.
* @param params Params.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async handleAction(siteId: string, params: Record<string, string>): Promise<void> {
// Stub to override.
}
}
export const AddonModWikiEditLinkHandler = makeSingleton(AddonModWikiEditLinkHandlerService);
/**
* Get edit link handler instance.
*
* @returns Link handler.
*/
export function getEditLinkHandlerInstance(): CoreContentLinksHandler {
const lazyHandler = asyncInstance<
AddonModWikiEditLinkHandlerLazyService,
AddonModWikiEditLinkHandlerService
>(async () => {
const { AddonModWikiEditLinkHandler } = await import('./edit-link-lazy');
return AddonModWikiEditLinkHandler.instance;
});
lazyHandler.setEagerInstance(new AddonModWikiEditLinkHandlerService());
lazyHandler.setLazyOverrides(['handleAction']);
return lazyHandler;
}

View File

@ -0,0 +1,97 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { CoreCourse } from '@features/course/services/course';
import { CoreNavigator } from '@services/navigator';
import { CoreSitesReadingStrategy } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { makeSingleton } from '@singletons';
import { Md5 } from 'ts-md5';
import { AddonModWiki } from '../wiki';
import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants';
import { AddonModWikiPageOrMapLinkHandlerService } from '@addons/mod/wiki/services/handlers/page-or-map-link';
/**
* Handler to treat links to a wiki page or the wiki map.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiPageOrMapLinkHandlerLazyService extends AddonModWikiPageOrMapLinkHandlerService {
/**
* @inheritdoc
*/
async handleAction(url: string, siteId: string, params: Record<string, string>): Promise<void> {
const modal = await CoreDomUtils.showModalLoading();
const pageId = parseInt(params.pageid, 10);
const action = url.indexOf('mod/wiki/map.php') != -1 ? 'map' : 'page';
try {
// Get the page data to obtain wikiId, subwikiId, etc.
const page = await AddonModWiki.getPageContents(pageId, { siteId });
const module = await CoreCourse.getModuleBasicInfoByInstance(
page.wikiid,
'wiki',
{ siteId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
const hash = Md5.hashAsciiStr(JSON.stringify({
pageId: page.id,
pageTitle: page.title,
subwikiId: page.subwikiid,
action: action,
timestamp: Date.now(),
}));
await CoreNavigator.navigateToSitePath(
`${ADDON_MOD_WIKI_PAGE_NAME}/${module.course}/${module.id}/page/${hash}`,
{
params: {
module,
pageId: page.id,
pageTitle: page.title,
subwikiId: page.subwikiid,
action: action,
},
siteId,
},
);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_wiki.errorloadingpage', true);
} finally {
modal.dismiss();
}
}
/**
* @inheritdoc
*/
async isEnabled(siteId: string, url: string, params: Record<string, string>): Promise<boolean> {
const isMap = url.indexOf('mod/wiki/map.php') != -1;
if (params.id && !isMap) {
// ID param is more prioritary than pageid in index page, it's a index URL.
return false;
} else if (isMap && params.option !== undefined && params.option != '5') {
// Map link but the option isn't "Page list", not supported.
return false;
}
return true;
}
}
export const AddonModWikiPageOrMapLinkHandler = makeSingleton(AddonModWikiPageOrMapLinkHandlerLazyService);

View File

@ -12,100 +12,58 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { asyncInstance } from '@/core/utils/async-instance';
import { ADDON_MOD_WIKI_FEATURE_NAME } from '@addons/mod/wiki/constants';
import { CoreContentLinksHandlerBase } from '@features/contentlinks/classes/base-handler';
import { CoreContentLinksAction } from '@features/contentlinks/services/contentlinks-delegate';
import { CoreCourse } from '@features/course/services/course';
import { CoreNavigator } from '@services/navigator';
import { CoreSitesReadingStrategy } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { makeSingleton } from '@singletons';
import { Md5 } from 'ts-md5';
import { AddonModWiki } from '../wiki';
import { ADDON_MOD_WIKI_PAGE_NAME } from '../../constants';
import { CoreContentLinksAction, CoreContentLinksHandler } from '@features/contentlinks/services/contentlinks-delegate';
import type { AddonModWikiPageOrMapLinkHandlerLazyService } from '@addons/mod/wiki/services/handlers/page-or-map-link-lazy';
/**
* Handler to treat links to a wiki page or the wiki map.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiPageOrMapLinkHandlerService extends CoreContentLinksHandlerBase {
name = 'AddonModWikiPageOrMapLinkHandler';
featureName = 'CoreCourseModuleDelegate_AddonModWiki';
featureName = ADDON_MOD_WIKI_FEATURE_NAME;
pattern = /\/mod\/wiki\/(view|map)\.php.*([&?]pageid=\d+)/;
/**
* @inheritdoc
*/
getActions(
siteIds: string[],
url: string,
params: Record<string, string>,
): CoreContentLinksAction[] | Promise<CoreContentLinksAction[]> {
getActions(siteIds: string[], url: string, params: Record<string, string>): CoreContentLinksAction[] {
return [{
action: async (siteId: string) => {
const modal = await CoreDomUtils.showModalLoading();
const pageId = parseInt(params.pageid, 10);
const action = url.indexOf('mod/wiki/map.php') != -1 ? 'map' : 'page';
try {
// Get the page data to obtain wikiId, subwikiId, etc.
const page = await AddonModWiki.getPageContents(pageId, { siteId });
const module = await CoreCourse.getModuleBasicInfoByInstance(
page.wikiid,
'wiki',
{ siteId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
const hash = Md5.hashAsciiStr(JSON.stringify({
pageId: page.id,
pageTitle: page.title,
subwikiId: page.subwikiid,
action: action,
timestamp: Date.now(),
}));
await CoreNavigator.navigateToSitePath(
`${ADDON_MOD_WIKI_PAGE_NAME}/${module.course}/${module.id}/page/${hash}`,
{
params: {
module,
pageId: page.id,
pageTitle: page.title,
subwikiId: page.subwikiid,
action: action,
},
siteId,
},
);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_wiki.errorloadingpage', true);
} finally {
modal.dismiss();
}
},
action: (siteId) => this.handleAction(url, siteId, params),
}];
}
/**
* @inheritdoc
* Handle link action.
*
* @param url Url.
* @param siteId Site id.
* @param params Params.
*/
async isEnabled(siteId: string, url: string, params: Record<string, string>): Promise<boolean> {
const isMap = url.indexOf('mod/wiki/map.php') != -1;
if (params.id && !isMap) {
// ID param is more prioritary than pageid in index page, it's a index URL.
return false;
} else if (isMap && params.option !== undefined && params.option != '5') {
// Map link but the option isn't "Page list", not supported.
return false;
}
return true;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async handleAction(url: string, siteId: string, params: Record<string, string>): Promise<void> {
// Stub to override.
}
}
export const AddonModWikiPageOrMapLinkHandler = makeSingleton(AddonModWikiPageOrMapLinkHandlerService);
/**
* Get page or map link handler instance.
*
* @returns Link handler.
*/
export function getPageOrMapLinkHandlerInstance(): CoreContentLinksHandler {
const lazyHandler = asyncInstance<
AddonModWikiPageOrMapLinkHandlerLazyService,
AddonModWikiPageOrMapLinkHandlerService
>(async () => {
const { AddonModWikiPageOrMapLinkHandler } = await import('./page-or-map-link-lazy');
return AddonModWikiPageOrMapLinkHandler.instance;
});
lazyHandler.setEagerInstance(new AddonModWikiPageOrMapLinkHandlerService());
lazyHandler.setLazyOverrides(['isEnabled', 'handleAction']);
return lazyHandler;
}

View File

@ -0,0 +1,205 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { CoreCourse, CoreCourseAnyModuleData } from '@features/course/services/course';
import { CoreFilepool } from '@services/filepool';
import { CoreGroups } from '@services/groups';
import { CoreFileSizeSum, CorePluginFileDelegate } from '@services/plugin-file-delegate';
import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites';
import { CoreUtils } from '@services/utils/utils';
import { CoreWSFile } from '@services/ws';
import { makeSingleton } from '@singletons';
import { AddonModWiki, AddonModWikiSubwikiPage } from '../wiki';
import { AddonModWikiSync, AddonModWikiSyncWikiResult } from '../wiki-sync';
import { AddonModWikiPrefetchHandlerService } from '@addons/mod/wiki/services/handlers/prefetch';
/**
* Handler to prefetch wikis.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiPrefetchHandlerLazyService extends AddonModWikiPrefetchHandlerService {
/**
* Returns a list of pages that can be downloaded.
*
* @param module The module object returned by WS.
* @param courseId The course ID.
* @param options Other options.
* @returns List of pages.
*/
protected async getAllPages(
module: CoreCourseAnyModuleData,
courseId: number,
options: CoreSitesCommonWSOptions = {},
): Promise<AddonModWikiSubwikiPage[]> {
options.siteId = options.siteId || CoreSites.getCurrentSiteId();
try {
const wiki = await AddonModWiki.getWiki(courseId, module.id, options);
return await AddonModWiki.getWikiPageList(wiki, options);
} catch {
// Wiki not found, return empty list.
return [];
}
}
/**
* @inheritdoc
*/
async getDownloadSize(module: CoreCourseAnyModuleData, courseId: number, single?: boolean): Promise<CoreFileSizeSum> {
const promises: Promise<CoreFileSizeSum>[] = [];
const siteId = CoreSites.getCurrentSiteId();
promises.push(this.getFiles(module, courseId, single, siteId).then((files) =>
CorePluginFileDelegate.getFilesDownloadSize(files)));
promises.push(this.getAllPages(module, courseId, {
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
}).then((pages) => {
let size = 0;
pages.forEach((page) => {
if (page.contentsize) {
size = size + page.contentsize;
}
});
return { size: size, total: true };
}));
const sizes = await Promise.all(promises);
return {
size: sizes[0].size + sizes[1].size,
total: sizes[0].total && sizes[1].total,
};
}
/**
* @inheritdoc
*/
async getFiles(
module: CoreCourseAnyModuleData,
courseId: number,
single?: boolean,
siteId?: string,
): Promise<CoreWSFile[]> {
siteId = siteId || CoreSites.getCurrentSiteId();
try {
const wiki = await AddonModWiki.getWiki(courseId, module.id, { siteId });
const introFiles = this.getIntroFilesFromInstance(module, wiki);
const files = await AddonModWiki.getWikiFileList(wiki, { siteId });
return introFiles.concat(files);
} catch {
// Wiki not found, return empty list.
return [];
}
}
/**
* @inheritdoc
*/
invalidateContent(moduleId: number, courseId: number): Promise<void> {
return AddonModWiki.invalidateContent(moduleId, courseId);
}
/**
* @inheritdoc
*/
async prefetch(module: CoreCourseAnyModuleData, courseId: number, single?: boolean): Promise<void> {
// Get the download time of the package before starting the download (otherwise we'd always get current time).
const siteId = CoreSites.getCurrentSiteId();
const data = await CoreUtils.ignoreErrors(CoreFilepool.getPackageData(siteId, this.component, module.id));
const downloadTime = data?.downloadTime || 0;
return this.prefetchPackage(
module,
courseId,
(siteId) => this.prefetchWiki(module, courseId, !!single, downloadTime, siteId),
siteId,
);
}
/**
* Prefetch a wiki.
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @param single True if we're downloading a single module, false if we're downloading a whole section.
* @param downloadTime The previous download time, 0 if no previous download.
* @param siteId Site ID.
* @returns Promise resolved when done.
*/
protected async prefetchWiki(
module: CoreCourseAnyModuleData,
courseId: number,
single: boolean,
downloadTime: number,
siteId: string,
): Promise<void> {
const userId = CoreSites.getCurrentSiteUserId();
const commonOptions = {
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
};
const modOptions = {
cmId: module.id,
...commonOptions, // Include all common options.
};
// Get the list of pages.
const pages = await this.getAllPages(module, courseId, commonOptions);
const promises: Promise<unknown>[] = [];
pages.forEach((page) => {
// Fetch page contents if it needs to be fetched.
if (page.timemodified > downloadTime) {
promises.push(AddonModWiki.getPageContents(page.id, modOptions));
}
});
// Fetch group data.
promises.push(CoreGroups.getActivityGroupInfo(module.id, false, userId, siteId));
// Fetch info to provide wiki links.
promises.push(AddonModWiki.getWiki(courseId, module.id, { siteId }).then((wiki) =>
CoreCourse.getModuleBasicInfoByInstance(wiki.id, 'wiki', { siteId })));
// Get related page files and fetch them.
promises.push(this.getFiles(module, courseId, single, siteId).then((files) =>
CoreFilepool.addFilesToQueue(siteId, files, this.component, module.id)));
await Promise.all(promises);
}
/**
* @inheritdoc
*/
sync(module: CoreCourseAnyModuleData, courseId: number, siteId?: string): Promise<AddonModWikiSyncWikiResult> {
return AddonModWikiSync.syncWiki(module.instance, module.course, module.id, siteId);
}
}
export const AddonModWikiPrefetchHandler = makeSingleton(AddonModWikiPrefetchHandlerLazyService);

View File

@ -12,200 +12,48 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { asyncInstance } from '@/core/utils/async-instance';
import {
ADDON_MOD_WIKI_PREFETCH_COMPONENT,
ADDON_MOD_WIKI_PREFETCH_MODNAME,
ADDON_MOD_WIKI_PREFETCH_NAME,
} from '@addons/mod/wiki/constants';
import { CoreCourseActivityPrefetchHandlerBase } from '@features/course/classes/activity-prefetch-handler';
import { CoreCourse, CoreCourseAnyModuleData } from '@features/course/services/course';
import { CoreFilepool } from '@services/filepool';
import { CoreGroups } from '@services/groups';
import { CoreFileSizeSum, CorePluginFileDelegate } from '@services/plugin-file-delegate';
import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites';
import { CoreUtils } from '@services/utils/utils';
import { CoreWSFile } from '@services/ws';
import { makeSingleton } from '@singletons';
import { AddonModWiki, AddonModWikiSubwikiPage } from '../wiki';
import { AddonModWikiSync, AddonModWikiSyncWikiResult } from '../wiki-sync';
import { ADDON_MOD_WIKI_COMPONENT } from '../../constants';
import { CoreCourseModulePrefetchHandler } from '@features/course/services/module-prefetch-delegate';
import type { AddonModWikiPrefetchHandlerLazyService } from '@addons/mod/wiki/services/handlers/prefetch-lazy';
/**
* Handler to prefetch wikis.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiPrefetchHandlerService extends CoreCourseActivityPrefetchHandlerBase {
name = 'AddonModWiki';
modName = 'wiki';
component = ADDON_MOD_WIKI_COMPONENT;
name = ADDON_MOD_WIKI_PREFETCH_NAME;
modName = ADDON_MOD_WIKI_PREFETCH_MODNAME;
component = ADDON_MOD_WIKI_PREFETCH_COMPONENT;
updatesNames = /^.*files$|^pages$/;
/**
* Returns a list of pages that can be downloaded.
*
* @param module The module object returned by WS.
* @param courseId The course ID.
* @param options Other options.
* @returns List of pages.
*/
protected async getAllPages(
module: CoreCourseAnyModuleData,
courseId: number,
options: CoreSitesCommonWSOptions = {},
): Promise<AddonModWikiSubwikiPage[]> {
options.siteId = options.siteId || CoreSites.getCurrentSiteId();
try {
const wiki = await AddonModWiki.getWiki(courseId, module.id, options);
return await AddonModWiki.getWikiPageList(wiki, options);
} catch {
// Wiki not found, return empty list.
return [];
}
}
/**
* @inheritdoc
*/
async getDownloadSize(module: CoreCourseAnyModuleData, courseId: number, single?: boolean): Promise<CoreFileSizeSum> {
const promises: Promise<CoreFileSizeSum>[] = [];
const siteId = CoreSites.getCurrentSiteId();
promises.push(this.getFiles(module, courseId, single, siteId).then((files) =>
CorePluginFileDelegate.getFilesDownloadSize(files)));
promises.push(this.getAllPages(module, courseId, {
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
}).then((pages) => {
let size = 0;
pages.forEach((page) => {
if (page.contentsize) {
size = size + page.contentsize;
}
});
return { size: size, total: true };
}));
const sizes = await Promise.all(promises);
return {
size: sizes[0].size + sizes[1].size,
total: sizes[0].total && sizes[1].total,
};
}
/**
* @inheritdoc
*/
async getFiles(
module: CoreCourseAnyModuleData,
courseId: number,
single?: boolean,
siteId?: string,
): Promise<CoreWSFile[]> {
siteId = siteId || CoreSites.getCurrentSiteId();
try {
const wiki = await AddonModWiki.getWiki(courseId, module.id, { siteId });
const introFiles = this.getIntroFilesFromInstance(module, wiki);
const files = await AddonModWiki.getWikiFileList(wiki, { siteId });
return introFiles.concat(files);
} catch {
// Wiki not found, return empty list.
return [];
}
}
/**
* @inheritdoc
*/
invalidateContent(moduleId: number, courseId: number): Promise<void> {
return AddonModWiki.invalidateContent(moduleId, courseId);
}
/**
* @inheritdoc
*/
async prefetch(module: CoreCourseAnyModuleData, courseId: number, single?: boolean): Promise<void> {
// Get the download time of the package before starting the download (otherwise we'd always get current time).
const siteId = CoreSites.getCurrentSiteId();
const data = await CoreUtils.ignoreErrors(CoreFilepool.getPackageData(siteId, this.component, module.id));
const downloadTime = data?.downloadTime || 0;
return this.prefetchPackage(
module,
courseId,
(siteId) => this.prefetchWiki(module, courseId, !!single, downloadTime, siteId),
siteId,
);
}
/**
* Prefetch a wiki.
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @param single True if we're downloading a single module, false if we're downloading a whole section.
* @param downloadTime The previous download time, 0 if no previous download.
* @param siteId Site ID.
* @returns Promise resolved when done.
*/
protected async prefetchWiki(
module: CoreCourseAnyModuleData,
courseId: number,
single: boolean,
downloadTime: number,
siteId: string,
): Promise<void> {
const userId = CoreSites.getCurrentSiteUserId();
const commonOptions = {
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
};
const modOptions = {
cmId: module.id,
...commonOptions, // Include all common options.
};
// Get the list of pages.
const pages = await this.getAllPages(module, courseId, commonOptions);
const promises: Promise<unknown>[] = [];
pages.forEach((page) => {
// Fetch page contents if it needs to be fetched.
if (page.timemodified > downloadTime) {
promises.push(AddonModWiki.getPageContents(page.id, modOptions));
}
});
// Fetch group data.
promises.push(CoreGroups.getActivityGroupInfo(module.id, false, userId, siteId));
// Fetch info to provide wiki links.
promises.push(AddonModWiki.getWiki(courseId, module.id, { siteId }).then((wiki) =>
CoreCourse.getModuleBasicInfoByInstance(wiki.id, 'wiki', { siteId })));
// Get related page files and fetch them.
promises.push(this.getFiles(module, courseId, single, siteId).then((files) =>
CoreFilepool.addFilesToQueue(siteId, files, this.component, module.id)));
await Promise.all(promises);
}
/**
* @inheritdoc
*/
sync(module: CoreCourseAnyModuleData, courseId: number, siteId?: string): Promise<AddonModWikiSyncWikiResult> {
return AddonModWikiSync.syncWiki(module.instance, module.course, module.id, siteId);
}
}
export const AddonModWikiPrefetchHandler = makeSingleton(AddonModWikiPrefetchHandlerService);
/**
* Get prefetch handler instance.
*
* @returns Prefetch handler.
*/
export function getPrefetchHandlerInstance(): CoreCourseModulePrefetchHandler {
const lazyHandler = asyncInstance<
AddonModWikiPrefetchHandlerLazyService,
AddonModWikiPrefetchHandlerService
>(async () => {
const { AddonModWikiPrefetchHandler } = await import('./prefetch-lazy');
return AddonModWikiPrefetchHandler.instance;
});
lazyHandler.setEagerInstance(new AddonModWikiPrefetchHandlerService());
lazyHandler.setLazyMethods(['sync']);
lazyHandler.setLazyOverrides([
'getFiles',
'getDownloadSize',
'invalidateContent',
'prefetch',
]);
return lazyHandler;
}

View File

@ -0,0 +1,43 @@
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { CoreCronHandler } from '@services/cron';
import { makeSingleton } from '@singletons';
import { AddonModWikiSync } from '../wiki-sync';
import { AddonModWikiSyncCronHandlerService } from '@addons/mod/wiki/services/handlers/sync-cron';
/**
* Synchronization cron handler.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiSyncCronHandlerLazyService extends AddonModWikiSyncCronHandlerService implements CoreCronHandler {
/**
* @inheritdoc
*/
execute(siteId?: string, force?: boolean): Promise<void> {
return AddonModWikiSync.syncAllWikis(siteId, force);
}
/**
* @inheritdoc
*/
getInterval(): number {
return AddonModWikiSync.syncInterval;
}
}
export const AddonModWikiSyncCronHandler = makeSingleton(AddonModWikiSyncCronHandlerLazyService);

View File

@ -12,33 +12,33 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { asyncInstance } from '@/core/utils/async-instance';
import { CoreCronHandler } from '@services/cron';
import { makeSingleton } from '@singletons';
import { AddonModWikiSync } from '../wiki-sync';
import type { AddonModWikiSyncCronHandlerLazyService } from '@addons/mod/wiki/services/handlers/sync-cron-lazy';
/**
* Synchronization cron handler.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiSyncCronHandlerService implements CoreCronHandler {
export class AddonModWikiSyncCronHandlerService {
name = 'AddonModWikiSyncCronHandler';
/**
* @inheritdoc
*/
execute(siteId?: string, force?: boolean): Promise<void> {
return AddonModWikiSync.syncAllWikis(siteId, force);
}
/**
* @inheritdoc
*/
getInterval(): number {
return AddonModWikiSync.syncInterval;
}
}
export const AddonModWikiSyncCronHandler = makeSingleton(AddonModWikiSyncCronHandlerService);
/**
* Get cron handler instance.
*
* @returns Cron handler.
*/
export function getCronHandlerInstance(): CoreCronHandler {
const lazyHandler = asyncInstance<
AddonModWikiSyncCronHandlerLazyService,
AddonModWikiSyncCronHandlerService
>(async () => {
const { AddonModWikiSyncCronHandler } = await import('./sync-cron-lazy');
return AddonModWikiSyncCronHandler.instance;
});
lazyHandler.setEagerInstance(new AddonModWikiSyncCronHandlerService());
lazyHandler.setLazyMethods(['execute', 'getInterval']);
return lazyHandler;
}

View File

@ -23,14 +23,14 @@ import { CoreTagAreaDelegate } from '@features/tag/services/tag-area-delegate';
import { CoreCronDelegate } from '@services/cron';
import { CORE_SITE_SCHEMAS } from '@services/sites';
import { OFFLINE_SITE_SCHEMA } from './services/database/wiki';
import { AddonModWikiCreateLinkHandler } from './services/handlers/create-link';
import { AddonModWikiEditLinkHandler } from './services/handlers/edit-link';
import { getCreateLinkHandlerInstance } from './services/handlers/create-link';
import { getEditLinkHandlerInstance } from './services/handlers/edit-link';
import { AddonModWikiIndexLinkHandler } from './services/handlers/index-link';
import { AddonModWikiListLinkHandler } from './services/handlers/list-link';
import { AddonModWikiModuleHandler } from './services/handlers/module';
import { AddonModWikiPageOrMapLinkHandler } from './services/handlers/page-or-map-link';
import { AddonModWikiPrefetchHandler } from './services/handlers/prefetch';
import { AddonModWikiSyncCronHandler } from './services/handlers/sync-cron';
import { getPageOrMapLinkHandlerInstance } from './services/handlers/page-or-map-link';
import { getPrefetchHandlerInstance } from './services/handlers/prefetch';
import { getCronHandlerInstance } from './services/handlers/sync-cron';
import { AddonModWikiTagAreaHandler } from './services/handlers/tag-area';
import { ADDON_MOD_WIKI_COMPONENT, ADDON_MOD_WIKI_PAGE_NAME } from './constants';
@ -55,14 +55,15 @@ const routes: Routes = [
provide: APP_INITIALIZER,
multi: true,
useValue: () => {
CoreContentLinksDelegate.registerHandler(getCreateLinkHandlerInstance());
CoreContentLinksDelegate.registerHandler(getEditLinkHandlerInstance());
CoreContentLinksDelegate.registerHandler(getPageOrMapLinkHandlerInstance());
CoreCourseModulePrefetchDelegate.registerHandler(getPrefetchHandlerInstance());
CoreCronDelegate.register(getCronHandlerInstance());
CoreCourseModuleDelegate.registerHandler(AddonModWikiModuleHandler.instance);
CoreCourseModulePrefetchDelegate.registerHandler(AddonModWikiPrefetchHandler.instance);
CoreCronDelegate.register(AddonModWikiSyncCronHandler.instance);
CoreContentLinksDelegate.registerHandler(AddonModWikiIndexLinkHandler.instance);
CoreContentLinksDelegate.registerHandler(AddonModWikiListLinkHandler.instance);
CoreContentLinksDelegate.registerHandler(AddonModWikiCreateLinkHandler.instance);
CoreContentLinksDelegate.registerHandler(AddonModWikiEditLinkHandler.instance);
CoreContentLinksDelegate.registerHandler(AddonModWikiPageOrMapLinkHandler.instance);
CoreTagAreaDelegate.registerHandler(AddonModWikiTagAreaHandler.instance);
CoreCourseHelper.registerModuleReminderClick(ADDON_MOD_WIKI_COMPONENT);