Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(resources): delete a downloaded resource from the options
Elian Doran386cdfc5ce80
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 00f5523a11..c6a9de193c 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4643,6 +4643,8 @@"installed": "Installed","partially_downloaded": "{{downloaded}} of {{size}} downloaded","space_used": "Space used",- "no_resources": "Nothing has been downloaded yet."+ "no_resources": "Nothing has been downloaded yet.",+ "delete": "Delete",+ "delete_confirmation": "Delete {{title}}? It is downloaded again the next time a feature needs it."}}diff --git a/apps/client/src/widgets/type_widgets/options/resources.spec.tsx b/apps/client/src/widgets/type_widgets/options/resources.spec.tsxindex 09d8016310..d05b8cd158 100644--- a/apps/client/src/widgets/type_widgets/options/resources.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/resources.spec.tsx@@ -6,6 +6,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({resources: [] as ResourceInfo[],requests: 0,+ confirmed: true,+ removed: [] as string[],handlers: [] as ((message: WebSocketMessage) => void)[]}));@@ -17,10 +19,17 @@ vi.mock("../../../services/server", () => ({}mocks.requests++;return { resources: mocks.resources, freeBytes: null, download: null };+ },+ remove: async (url: string) => {+ mocks.removed.push(url);}}}));+vi.mock("../../../services/dialog", () => ({+ default: { confirm: async () => mocks.confirmed }+}));+vi.mock("../../../services/ws", () => {const ws = {subscribeToMessages: (handler: (message: WebSocketMessage) => void) => {@@ -58,6 +67,8 @@ beforeEach(() => {resource({ id: "test.missing" })];mocks.requests = 0;+ mocks.confirmed = true;+ mocks.removed = [];mocks.handlers = [];host = document.body.appendChild(document.createElement("div"));});@@ -90,6 +101,25 @@ describe("ResourcesSettings", () => {.toEqual([ "2.00 GiB", "0.01 GiB", "2.00 GiB" ]);});+ it("deletes a resource once confirmed, then reads the list again", async () => {+ await open();+ const click = async () => {+ const button = host.querySelector<HTMLElement>(".resources-item .destructive-action-icon");+ expect(button).not.toBeNull();+ await act(async () => button?.click());+ };++ mocks.confirmed = false;+ await click();+ expect(mocks.removed).toEqual([]);+ expect(mocks.requests).toBe(1);++ mocks.confirmed = true;+ await click();+ expect(mocks.removed).toEqual([ "resources/test.installed" ]);+ expect(mocks.requests).toBe(2);+ });+it("shows an empty state when nothing is downloaded", async () => {mocks.resources = [ resource({ id: "test.missing" }) ];await open();diff --git a/apps/client/src/widgets/type_widgets/options/resources.tsx b/apps/client/src/widgets/type_widgets/options/resources.tsxindex 1d55d7ba49..34ed760668 100644--- a/apps/client/src/widgets/type_widgets/options/resources.tsx+++ b/apps/client/src/widgets/type_widgets/options/resources.tsx@@ -1,12 +1,14 @@import "./resources.css";import type { ResourceInfo, ResourcesStatusResponse, WebSocketMessage } from "@triliumnext/commons";-import { useEffect, useState } from "preact/hooks";+import { useCallback, useEffect, useState } from "preact/hooks";+import dialogService from "../../../services/dialog";import { t } from "../../../services/i18n";import server from "../../../services/server";import { formatSize } from "../../../services/utils";import { subscribeToMessages, unsubscribeToMessage } from "../../../services/ws";+import ActionButton from "../../react/ActionButton";import { Card, CardSection } from "../../react/Card";import DirectoryLink from "../../react/DirectoryLink";import Icon from "../../react/Icon";@@ -15,7 +17,7 @@ import OptionsPageHeader from "./components/OptionsPageHeader";/** Lists the resources installed on this device, and the ones an interrupted download left partly fetched. */export default function ResourcesSettings() {- const resources = useResources();+ const [ resources, refresh ] = useResources();return (<>@@ -27,7 +29,7 @@ export default function ResourcesSettings() {description={t("resources_options.list_description")}>{resources.length > 0 ? (- <ResourceRows resources={resources} />+ <ResourceRows resources={resources} onDeleted={refresh} />) : (<CardSection><NoItems icon="bx bx-download" text={t("resources_options.no_resources")} size="small" />@@ -42,13 +44,13 @@ export default function ResourcesSettings() {/** The resources installed or partly downloaded, fetched again whenever a download ends. */function useResources() {const [ resources, setResources ] = useState<ResourceInfo[]>();+ const refresh = useCallback(() => {+ void server.get<ResourcesStatusResponse>("resources")+ .then((status) => setResources(status.resources.filter(+ ({ downloadedSize }) => downloadedSize > 0)));+ }, []);useEffect(() => {- const refresh = () => {- void server.get<ResourcesStatusResponse>("resources")- .then((status) => setResources(status.resources.filter(- ({ downloadedSize }) => downloadedSize > 0)));- };const handler = (message: WebSocketMessage) => {if (message.type === "resource-download" && message.download.status !== "downloading") {refresh();@@ -57,19 +59,19 @@ function useResources() {refresh();subscribeToMessages(handler);return () => unsubscribeToMessage(handler);- }, []);+ }, [ refresh ]);- return resources;+ return [ resources, refresh ] as const;}/** The resources and the space they use, every size in one unit so that the column adds up. */-function ResourceRows({ resources }: { resources: ResourceInfo[] }) {+function ResourceRows({ resources, onDeleted }: { resources: ResourceInfo[]; onDeleted: () => void }) {const used = resources.reduce((total, { downloadedSize }) => total + downloadedSize, 0);const unitOf = Math.max(used, ...resources.map(({ size }) => size));return (<>{resources.map((resource) => (- <ResourceRow key={resource.id} resource={resource} unitOf={unitOf} />+ <ResourceRow key={resource.id} resource={resource} unitOf={unitOf} onDeleted={onDeleted} />))}<CardSection className="tn-card-option resources-total"><div className="tn-card-option-label">@@ -81,7 +83,21 @@ function ResourceRows({ resources }: { resources: ResourceInfo[] }) {);}-function ResourceRow({ resource, unitOf }: { resource: ResourceInfo; unitOf: number }) {+interface ResourceRowProps {+ resource: ResourceInfo;+ unitOf: number;+ onDeleted: () => void;+}++function ResourceRow({ resource, unitOf, onDeleted }: ResourceRowProps) {+ async function remove() {+ if (!await dialogService.confirm(t("resources_options.delete_confirmation", { title: resource.title }))) {+ return;+ }+ await server.remove(`resources/${encodeURIComponent(resource.id)}`);+ onDeleted();+ }+return (<CardSection className="tn-card-option resources-item"><Icon icon={resource.icon} className="resources-icon" />@@ -103,6 +119,12 @@ function ResourceRow({ resource, unitOf }: { resource: ResourceInfo; unitOf: num<span className="resources-size">{formatSize(resource.size, 2, unitOf)}</span><small className="tn-card-option-description">{getStatusText(resource)}</small></div>+ <ActionButton+ className="destructive-action-icon"+ icon="bx bx-trash"+ text={t("resources_options.delete")}+ onClick={() => void remove()}+ /></CardSection>);}diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 8f40fb6c2d..d06dfedb52 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -586,6 +586,7 @@"unknown": "There is no resource named {{id}}.","http-error": "Downloading {{name}} failed with HTTP status {{status}}.","size-mismatch": "{{name}} does not have the expected size.",- "hash-mismatch": "{{name}} does not match its expected checksum, so it was discarded."+ "hash-mismatch": "{{name}} does not match its expected checksum, so it was discarded.",+ "delete-while-downloading": "{{- title}} is being downloaded. Cancel the download before deleting it."}}diff --git a/apps/server/src/routes/api/resources.ts b/apps/server/src/routes/api/resources.tsindex 75388981d7..cd05a41807 100644--- a/apps/server/src/routes/api/resources.ts+++ b/apps/server/src/routes/api/resources.ts@@ -22,6 +22,11 @@ function cancelDownload(req: Request<{ downloadId: string }>) {resources.cancelDownload(req.params.downloadId);}+/** `DELETE /api/resources/:id`: deletes the files of the resource. */+async function deleteResource(req: Request<{ id: string }>) {+ await resources.delete(req.params.id);+}+function parseIds(ids: unknown) {const list = typeof ids === "string" ? ids.split(",") : ids;if (!Array.isArray(list) || !list.length || !list.every((id) => typeof id === "string")) {@@ -33,5 +38,6 @@ function parseIds(ids: unknown) {export default {getStatus,startDownload,- cancelDownload+ cancelDownload,+ deleteResource};diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex 8c33be5378..2a63ff4fbd 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -201,6 +201,7 @@ function register(app: express.Application) {asyncApiRoute(GET, "/api/resources", resourcesRoute.getStatus);apiRoute(PST, "/api/resources/download", resourcesRoute.startDownload);apiRoute(PST, "/api/resources/download/:downloadId/cancel", resourcesRoute.cancelDownload);+ asyncApiRoute(DEL, "/api/resources/:id", resourcesRoute.deleteResource);app.use("", router);}diff --git a/apps/server/src/services/resources.spec.ts b/apps/server/src/services/resources.spec.tsindex de6db87b14..ec674b0498 100644--- a/apps/server/src/services/resources.spec.ts+++ b/apps/server/src/services/resources.spec.ts@@ -300,6 +300,27 @@ describe("ResourceManager", () => {]);});+ it("deletes a resource's directory, but not while a download fetches it", async () => {+ manager.register(defineModel(), defineModel({ id: "test.stalled", tokensUrl: "/stall" }));+ manager.startDownload([ "test.model" ]);+ expect((await waitForEnd()).status).toBe("succeeded");+ const directory = manager.getPath("test.model") ?? "";++ await manager.delete("test.model");+ expect(fs.existsSync(directory)).toBe(false);+ expect(manager.getPath("test.model")).toBeNull();+ expect((await manager.getStatus([ "test.model" ])).resources[0].downloadedSize).toBe(0);++ const running = manager.startDownload([ "test.stalled" ]);+ await waitFor(() => stalled.length > 0);+ await expect(manager.delete("test.stalled")).rejects.toThrow();+ manager.cancelDownload(running.downloadId);+ expect((await waitForEnd()).status).toBe("canceled");+ expect((await manager.getStatus([ "test.stalled" ])).resources[0].downloadedSize).toBeGreaterThan(0);+ await manager.delete("test.stalled");+ expect((await manager.getStatus([ "test.stalled" ])).resources[0].downloadedSize).toBe(0);+ });+it("refuses invalid or unknown resources", () => {manager.register(defineModel());expect(() => manager.register(defineModel())).toThrow(/already registered/);diff --git a/apps/server/src/services/resources.ts b/apps/server/src/services/resources.tsindex 20f5373a97..fb0119337c 100644--- a/apps/server/src/services/resources.ts+++ b/apps/server/src/services/resources.ts@@ -138,6 +138,19 @@ export class ResourceManager {this.downloads.get(downloadId)?.controller.abort();}+ /**+ * Deletes the directory of the resource `id`, with the files an interrupted download kept.+ * Refuses while a download fetches the resource.+ */+ async delete(id: string) {+ const definition = this.getDefinition(id);+ if (this.findDownload([ id ])) {+ throw new ValidationError(t("resources.delete-while-downloading", { title: definition.title() }));+ }+ await fs.promises.rm(this.getDirectory(definition), { recursive: true, force: true });+ getLog().info(`Resources: deleted ${id}.`);+ }+private async runDownload(download: Download, definitions: ResourceDefinition[]) {const { progress, controller } = download;let lastReported = 0;