Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

Finish delete/update preservations

Isaacd17fed9c8552
diff --git a/components/ConfirmationModal.tsx b/components/ConfirmationModal.tsx
new file mode 100644
index 00000000..e4f692a6
--- /dev/null
+++ b/components/ConfirmationModal.tsx
@@ -0,0 +1,123 @@
+import React, { MouseEventHandler, ReactNode, useEffect } from "react";
+import ClickAwayHandler from "@/components/ClickAwayHandler";
+import { Drawer } from "vaul";
+import clsx from "clsx";
+import useWindowDimensions from "@/hooks/useWindowDimensions";
+import Button from "./ui/Button";
+import { useTranslation } from "react-i18next";
+
+type Props = {
+ toggleModal: Function;
+ children: ReactNode;
+ title: string;
+ onConfirmed: Function;
+ className?: string;
+ dismissible?: boolean;
+};
+
+export default function ConfirmationModal({
+ toggleModal,
+ className,
+ title,
+ onConfirmed,
+ children,
+ dismissible = true,
+}: Props) {
+ const { t } = useTranslation();
+ const [drawerIsOpen, setDrawerIsOpen] = React.useState(true);
+ const { width } = useWindowDimensions();
+
+ useEffect(() => {
+ if (width >= 640) {
+ document.body.style.overflow = "hidden";
+ document.body.style.position = "relative";
+ return () => {
+ document.body.style.overflow = "auto";
+ document.body.style.position = "";
+ };
+ }
+ }, []);
+
+ if (width < 640) {
+ return (
+ <Drawer.Root
+ open={drawerIsOpen}
+ onClose={() => dismissible && setDrawerIsOpen(false)}
+ onAnimationEnd={(isOpen) => !isOpen && toggleModal()}
+ dismissible={dismissible}
+ >
+ <Drawer.Portal>
+ <Drawer.Overlay className="fixed inset-0 bg-black/40" />
+ <Drawer.Content className="flex flex-col rounded-t-2xl h-[90%] mt-24 fixed bottom-0 left-0 right-0 z-30 outline-none">
+ <div
+ className="p-4 bg-base-100 rounded-t-2xl flex-1 border-neutral-content border-t overflow-y-auto"
+ data-testid="mobile-modal-container"
+ >
+ <div
+ className="mx-auto w-12 h-1.5 flex-shrink-0 rounded-full bg-neutral mb-5"
+ data-testid="mobile-modal-slider"
+ />
+ <p className="text-xl font-thin">{title}</p>
+ <div className="divider mb-3 mt-1"></div>
+ {children}
+ <div className="w-full flex items-center justify-end gap-2 mt-3">
+ <Button intent="ghost" className="hover:bg-base-200" onClick={() => toggleModal()}>
+ {t("cancel")}
+ </Button>
+ <Button intent="destructive" onClick={async () => {
+ await onConfirmed();
+ toggleModal();
+ }}>
+ {t("confirm")}
+ </Button>
+ </div>
+ </div>
+ </Drawer.Content>
+ </Drawer.Portal>
+ </Drawer.Root>
+ );
+ } else {
+ return (
+ <div
+ className="overflow-y-auto pt-2 sm:py-2 fixed top-0 bottom-0 right-0 left-0 bg-black bg-opacity-10 backdrop-blur-sm flex justify-center items-center fade-in z-40"
+ data-testid="modal-outer"
+ >
+ <ClickAwayHandler
+ onClickOutside={() => dismissible && toggleModal()}
+ className={clsx("w-full mt-auto sm:m-auto sm:w-11/12 sm:max-w-2xl", className)}
+ >
+ <div
+ className={"slide-up mt-auto sm:m-auto relative border-neutral-content rounded-t-2xl sm:rounded-2xl border-t sm:border shadow-2xl bg-base-100 overflow-y-auto sm:overflow-y-visible p-5"}
+ data-testid="modal-container"
+ >
+ {dismissible && (
+ <div
+ onClick={toggleModal as MouseEventHandler<HTMLDivElement>}
+ className="absolute top-4 right-3 btn btn-sm outline-none btn-circle btn-ghost z-10"
+ >
+ <i
+ className="bi-x text-neutral text-2xl"
+ data-testid="close-modal-button"
+ ></i>
+ </div>
+ )}
+ <p className="text-xl font-thin">{title}</p>
+ <div className="divider mb-3 mt-1"></div>
+ {children}
+ <div className="w-full flex items-center justify-end gap-2 mt-3">
+ <Button intent="ghost" className="hover:bg-base-200" onClick={() => toggleModal()}>
+ {t("cancel")}
+ </Button>
+ <Button intent="destructive" onClick={async () => {
+ await onConfirmed();
+ toggleModal();
+ }}>
+ {t("confirm")}
+ </Button>
+ </div>
+ </div>
+ </ClickAwayHandler>
+ </div>
+ );
+ }
+}
diff --git a/components/ModalContent/NewRssSubscriptionModal.tsx b/components/ModalContent/NewRssSubscriptionModal.tsx
index b959ef3e..934c53cc 100644
--- a/components/ModalContent/NewRssSubscriptionModal.tsx
+++ b/components/ModalContent/NewRssSubscriptionModal.tsx
@@ -56,7 +56,6 @@ export default function NewRssSubscriptionModal({ onClose }: Props) {
<Modal toggleModal={onClose}>
<>
<p className="text-xl font-thin">{t("create_rss_subscription")}</p>
-
<div className="divider mb-3 mt-1"></div>
<div className="flex sm:flex-row flex-col gap-3 items-center">
<div className="w-full">
diff --git a/hooks/store/worker.tsx b/hooks/store/worker.tsx
deleted file mode 100644
index 2af08060..00000000
--- a/hooks/store/worker.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { LinkArchiveActionSchemaType } from "@/lib/shared/schemaValidation";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-
-// Try to remove this and do it in the page component
-const useDeleteAllPreserved = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async (action: LinkArchiveActionSchemaType) => {
- const response = await fetch("/api/v1/links/archive", {
- body: JSON.stringify({ action }),
- method: "DELETE",
- });
-
- const data = await response.json();
- if (!response.ok) throw new Error(data.response);
-
- return data.response;
- },
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ["links"] });
- },
- });
-}
-
-export { useDeleteAllPreserved };
diff --git a/lib/api/manageLinkFiles.ts b/lib/api/manageLinkFiles.ts
index 74987726..e68f5478 100644
--- a/lib/api/manageLinkFiles.ts
+++ b/lib/api/manageLinkFiles.ts
@@ -30,6 +30,31 @@ const removeFiles = async (linkId: number, collectionId: number) => {
});
};
+const removePreservationFiles = async (linkId: number, collectionId: number) => {
+ // PDF
+ await removeFile({
+ filePath: `archives/${collectionId}/${linkId}.pdf`,
+ });
+ // Images
+ await removeFile({
+ filePath: `archives/${collectionId}/${linkId}.png`,
+ });
+ await removeFile({
+ filePath: `archives/${collectionId}/${linkId}.jpeg`,
+ });
+ await removeFile({
+ filePath: `archives/${collectionId}/${linkId}.jpg`,
+ });
+ // HTML
+ await removeFile({
+ filePath: `archives/${collectionId}/${linkId}.html`,
+ });
+ // Readability
+ await removeFile({
+ filePath: `archives/${collectionId}/${linkId}_readability.json`,
+ });
+};
+
const moveFiles = async (linkId: number, from: number, to: number) => {
await moveFile(
`archives/${from}/${linkId}.pdf`,
@@ -67,4 +92,4 @@ const moveFiles = async (linkId: number, from: number, to: number) => {
);
};
-export { removeFiles, moveFiles };
+export { removeFiles, removePreservationFiles, moveFiles };
diff --git a/pages/api/v1/links/archive/index.ts b/pages/api/v1/links/archive/index.ts
index 77a9baa4..16782110 100644
--- a/pages/api/v1/links/archive/index.ts
+++ b/pages/api/v1/links/archive/index.ts
@@ -2,7 +2,9 @@ import type { NextApiRequest, NextApiResponse } from "next";
import verifyUser from "@/lib/api/verifyUser";
import { prisma } from "@/lib/api/db";
import { LinkArchiveActionSchema } from "@/lib/shared/schemaValidation";
-import { removeFiles } from "@/lib/api/manageLinkFiles";
+import { removePreservationFiles } from "@/lib/api/manageLinkFiles";
+import { isArchivalTag } from "@/hooks/useArchivalTags";
+import { ArchivalSettings } from "@/lib/api/archiveHandler";
export default async function links(req: NextApiRequest, res: NextApiResponse) {
const user = await verifyUser({ req, res });
@@ -24,24 +26,23 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
}
const { action } = dataValidation.data;
+ let count = 0;
if (action === "allAndIgnore") {
const allLinks = await prisma.link.findMany();
for (const link of allLinks) {
- await removeFiles(link.id, link.collectionId)
+ await removePreservationFiles(link.id, link.collectionId);
await prisma.link.update({
- where: {
- id: link.id,
- },
+ where: { id: link.id },
data: {
image: "unavailable",
pdf: "unavailable",
readable: "unavailable",
monolith: "unavailable",
preview: "unavailable",
- }
- })
+ },
+ });
}
return res.status(200).json({ response: "Success." });
@@ -49,22 +50,21 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
const allLinks = await prisma.link.findMany();
for (const link of allLinks) {
- await removeFiles(link.id, link.collectionId)
+ await removePreservationFiles(link.id, link.collectionId);
await prisma.link.update({
- where: {
- id: link.id,
- },
+ where: { id: link.id },
data: {
image: null,
pdf: null,
readable: null,
monolith: null,
preview: null,
- }
- })
+ },
+ });
+ count++;
}
- return res.status(200).json({ response: "Success." });
+ return res.status(200).json({ count });
} else if (action === "allBroken") {
const brokenArchives = await prisma.link.findMany({
where: {
@@ -84,25 +84,50 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
archiveAsPDF: true,
archiveAsReadable: true,
archiveAsWaybackMachine: true,
- }
+ },
},
- tags: {
- select: {
- archiveAsScreenshot: true,
- archiveAsMonolith: true,
- archiveAsPDF: true,
- archiveAsReadable: true,
- archiveAsWaybackMachine: true,
- }
- }
- }
+ tags: true,
+ },
});
- // Need to check tags & user options for archival formats
- // and then if the link is missing the same excluded formats
- // then we can ignore it
+ for (const link of brokenArchives) {
+ const archivalTags = link.tags.filter(isArchivalTag);
- return res.status(200).json({ response: "Success." });
+ const shouldArchive: Omit<ArchivalSettings, "aiTag" | "archiveAsWaybackMachine"> = archivalTags.length > 0
+ ? {
+ archiveAsScreenshot: archivalTags.some(tag => tag.archiveAsScreenshot),
+ archiveAsMonolith: archivalTags.some(tag => tag.archiveAsMonolith),
+ archiveAsPDF: archivalTags.some(tag => tag.archiveAsPDF),
+ archiveAsReadable: archivalTags.some(tag => tag.archiveAsReadable),
+ }
+ : {
+ archiveAsScreenshot: link.createdBy?.archiveAsScreenshot || false,
+ archiveAsMonolith: link.createdBy?.archiveAsMonolith || false,
+ archiveAsPDF: link.createdBy?.archiveAsPDF || false,
+ archiveAsReadable: link.createdBy?.archiveAsReadable || false,
+ };
+
+ const needsReprocessing =
+ (link.image === "unavailable" && shouldArchive.archiveAsScreenshot) ||
+ (link.monolith === "unavailable" && shouldArchive.archiveAsMonolith) ||
+ (link.pdf === "unavailable" && shouldArchive.archiveAsPDF) ||
+ (link.readable === "unavailable" && shouldArchive.archiveAsReadable);
+
+ if (needsReprocessing) {
+ await prisma.link.update({
+ where: { id: link.id },
+ data: {
+ image: shouldArchive.archiveAsScreenshot && link.image === "unavailable" ? null : link.image,
+ pdf: shouldArchive.archiveAsPDF && link.pdf === "unavailable" ? null : link.pdf,
+ readable: shouldArchive.archiveAsReadable && link.readable === "unavailable" ? null : link.readable,
+ monolith: shouldArchive.archiveAsMonolith && link.monolith === "unavailable" ? null : link.monolith,
+ },
+ });
+ count++;
+ }
+ }
+
+ return res.status(200).json({ count });
}
}
}
diff --git a/pages/settings/preference.tsx b/pages/settings/preference.tsx
index f0658bc3..fa14e8b9 100644
--- a/pages/settings/preference.tsx
+++ b/pages/settings/preference.tsx
@@ -384,7 +384,12 @@ export default function Preference() {
}
/>
</div>
- <p>{t("tag_settings")}</p>
+ <div className="w-full flex items-center justify-between">
+ <p>{t("archival_tag_settings")}</p>
+ <div className="tooltip tooltip-top" data-tip={t("archival_tag_info")}>
+ <i className="bi-info-lg text-lg leading-none"></i>
+ </div>
+ </div>
<div className="p-3">
<ArchivalTagSelection onChange={addTags} options={options} />
<div className="flex flex-col gap-2">
diff --git a/pages/settings/worker.tsx b/pages/settings/worker.tsx
index cd2d9a74..3cf43244 100644
--- a/pages/settings/worker.tsx
+++ b/pages/settings/worker.tsx
@@ -1,9 +1,78 @@
import SettingsLayout from "@/layouts/SettingsLayout";
import { useTranslation } from "next-i18next";
import getServerSideProps from "@/lib/client/getServerSideProps";
+import { useEffect, useState } from "react";
+import ConfirmationModal from "@/components/ConfirmationModal";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { LinkArchiveActionSchemaType } from "@/lib/shared/schemaValidation";
+import toast from "react-hot-toast";
+
+const useArchiveAction = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (action: LinkArchiveActionSchemaType) => {
+ const response = await fetch("/api/v1/links/archive", {
+ body: JSON.stringify({ action: action }),
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.response);
+
+ return data;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["links"] });
+ },
+ });
+}
export default function Worker() {
const { t } = useTranslation();
+ const archiveAction = useArchiveAction();
+ const [showModal, setShowModal] = useState(false);
+ const [submitLoader, setSubmitLoader] = useState(false);
+ const [action, setAction] = useState<LinkArchiveActionSchemaType | undefined>();
+
+ useEffect(() => {
+ if (showModal === false) {
+ setAction(undefined);
+ }
+ }, [showModal]);
+
+ const submit = async (action: LinkArchiveActionSchemaType) => {
+ if (!action || submitLoader) return;
+ setSubmitLoader(true);
+
+ const load = toast.loading(t("deleting"));
+
+ await archiveAction.mutateAsync(action, {
+ onSettled: (data, error) => {
+ setSubmitLoader(false);
+ toast.dismiss(load);
+
+ if (error) {
+ toast.error(error.message);
+ } else {
+ if (action === "allAndIgnore") {
+ toast.success(t("deleted"));
+ } else {
+ if (data.count === 0) {
+ toast.success(t("no_broken_preservations"));
+ } else if (data.count === 1) {
+ toast.success(t("successfully_represerved_link"));
+ } else {
+ toast.success(t("successfully_represerved_links", { count: data.count }));
+ }
+ }
+ }
+ },
+ });
+ };
return (
<SettingsLayout>
@@ -17,6 +86,7 @@ export default function Worker() {
<div className="flex flex-col sm:flex-row sm:items-center gap-3">
<span>{t("regenerate_broken_preservations")}</span>
<button
+ onClick={() => submit("allBroken")}
className={`btn btn-sm ml-auto btn-accent dark:border-violet-400 text-white tracking-wider w-fit flex items-center gap-2`}
>
{t("confirm")}
@@ -26,6 +96,10 @@ export default function Worker() {
<span>{t("delete_all_preservations")}</span>
<button
className={`btn btn-sm ml-auto btn-accent dark:border-violet-400 text-white tracking-wider w-fit flex items-center gap-2`}
+ onClick={() => {
+ setAction("allAndIgnore");
+ setShowModal(true);
+ }}
>
{t("confirm")}
</button>
@@ -34,12 +108,26 @@ export default function Worker() {
<span>{t("delete_all_preservations_and_regenerate")}</span>
<button
className={`btn btn-sm ml-auto btn-accent dark:border-violet-400 text-white tracking-wider w-fit flex items-center gap-2`}
+ onClick={() => {
+ setAction("allAndRePreserve");
+ setShowModal(true);
+ }}
>
{t("confirm")}
</button>
</div>
</div>
-
+ {showModal && action && (
+ <ConfirmationModal title={action === "allAndIgnore" ? t("delete_all_preservations") : t("delete_all_preservations_and_regenerate")} onConfirmed={() => submit(action)} toggleModal={setShowModal}>
+ <p>{t("delete_all_preservation_warning")}</p>
+ <div role="alert" className="alert alert-warning mt-3">
+ <i className="bi-exclamation-triangle text-xl" />
+ <span>
+ <b>{t("warning")}:</b> {t("irreversible_action_warning")}
+ </span>
+ </div>
+ </ConfirmationModal>
+ )}
</SettingsLayout>
);
}
diff --git a/public/locales/en/common.json b/public/locales/en/common.json
index c4d76f37..1e9bc1db 100644
--- a/public/locales/en/common.json
+++ b/public/locales/en/common.json
@@ -465,10 +465,16 @@
"new_note": "New Note",
"add_a_title_placeholder": "Add a title...",
"write_notes_here_placeholder": "Write some notes here...",
- "tag_settings": "Tag archival and processing settings:",
+ "archival_tag_settings": "Tag archival settings:",
+ "archival_tag_info": "Applying archival tags to a link will override the global archival settings.",
"ai_tagging": "AI Tagging",
"worker": "Worker",
- "regenerate_broken_preservations": "Regenerate all broken/missing preservations.",
+ "regenerate_broken_preservations": "Regenerate all broken or missing preservations.",
"delete_all_preservations": "Delete preservation for all webpages.",
- "delete_all_preservations_and_regenerate": "Delete preservation for all webpages and re-preserve."
+ "delete_all_preservations_and_regenerate": "Delete preservation for all webpages and re-preserve.",
+ "delete_all_preservation_warning": "This action will delete all existing preservations.",
+ "no_broken_preservations": "No broken preservations.",
+ "successfully_represerved_link": "Successfully re-preserved 1 link.",
+ "successfully_represerved_links": "Successfully re-preserved {{count}} links.",
+ "cancel": "Cancel"
}
\ No newline at end of file