Skip to content

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

Start bulk refreshing preserved formats

Isaacb337045ab29a
diff --git a/apps/web/components/LinkListOptions.tsx b/apps/web/components/LinkListOptions.tsx
index bd2138f0..7e2b590a 100644
--- a/apps/web/components/LinkListOptions.tsx
+++ b/apps/web/components/LinkListOptions.tsx
@@ -8,7 +8,7 @@ import useCollectivePermissions from "@/hooks/useCollectivePermissions";
import { useRouter } from "next/router";
import useLinkStore from "@/store/links";
import { Sort, ViewMode } from "@linkwarden/types";
-import { useBulkDeleteLinks, useLinks } from "@linkwarden/router/links";
+import { useArchiveAction, useBulkDeleteLinks, useLinks } from "@linkwarden/router/links";
import toast from "react-hot-toast";
type Props = {
@@ -35,6 +35,7 @@ const LinkListOptions = ({
const { selectedLinks, setSelectedLinks } = useLinkStore();
const deleteLinksById = useBulkDeleteLinks();
+ const refreshPreservations = useArchiveAction();
const { links } = useLinks();
@@ -79,6 +80,24 @@ const LinkListOptions = ({
);
};
+ const bulkRefreshPreservations = async () => {
+ const load = toast.loading(t("sending_request"));
+
+ await refreshPreservations.mutateAsync({
+ linkIds: selectedLinks.map((link) => link.id as number),
+ }, {
+ onSettled: (data, error) => {
+ toast.dismiss(load);
+ if (error) {
+ toast.error(error.message);
+ } else {
+ setSelectedLinks([]);
+ toast.success(t("links_being_archived"));
+ }
+ },
+ })
+ }
+
return (
<>
<div className="flex justify-between items-center">
@@ -96,11 +115,10 @@ const LinkListOptions = ({
setEditMode(!editMode);
setSelectedLinks([]);
}}
- className={`btn btn-square btn-sm btn-ghost ${
- editMode
- ? "bg-primary/20 hover:bg-primary/20"
- : "hover:bg-neutral/20"
- }`}
+ className={`btn btn-square btn-sm btn-ghost ${editMode
+ ? "bg-primary/20 hover:bg-primary/20"
+ : "hover:bg-neutral/20"
+ }`}
>
<i className="bi-pencil-fill text-neutral text-xl"></i>
</div>
@@ -139,6 +157,13 @@ const LinkListOptions = ({
)}
</div>
<div className="flex gap-3">
+ <button
+ disabled={selectedLinks.length === 0}
+ className="btn btn-sm btn-ghost text-white"
+ onClick={() => bulkRefreshPreservations()}
+ >
+ <i className="bi-arrow-clockwise text-sm" />
+ </button>
<button
onClick={() => setBulkEditLinksModal(true)}
className="btn btn-sm btn-accent text-white w-fit ml-auto"
diff --git a/apps/web/pages/api/v1/links/archive/index.ts b/apps/web/pages/api/v1/links/archive/index.ts
index 70479de4..4f7b1d69 100644
--- a/apps/web/pages/api/v1/links/archive/index.ts
+++ b/apps/web/pages/api/v1/links/archive/index.ts
@@ -6,6 +6,53 @@ import { removeFiles, removePreservationFiles } from "@linkwarden/filesystem";
import { ArchivalSettings } from "@linkwarden/types";
import { isArchivalTag } from "@linkwarden/lib";
+async function checkBulkLinkPermissions(userId: number, linkIds: number[]) {
+ const collections = await prisma.collection.findMany({
+ where: {
+ OR: [
+ { ownerId: userId },
+ {
+ members: {
+ some: {
+ userId: userId,
+ canDelete: true
+ }
+ }
+ }
+ ],
+ links: {
+ some: {
+ id: { in: linkIds }
+ }
+ }
+ },
+ select: {
+ id: true,
+ links: {
+ where: {
+ id: { in: linkIds }
+ },
+ select: { id: true }
+ }
+ }
+ });
+
+ const linkToCollectionMap = new Map<number, number>();
+ collections.forEach(collection => {
+ collection.links.forEach(link => {
+ linkToCollectionMap.set(link.id, collection.id);
+ });
+ });
+
+ // Check if all requested links are authorized
+ const unauthorizedLinkIds = linkIds.filter(linkId => !linkToCollectionMap.has(linkId));
+
+ return {
+ authorized: unauthorizedLinkIds.length === 0,
+ linkToCollectionMap
+ };
+}
+
export default async function links(req: NextApiRequest, res: NextApiResponse) {
const user = await verifyUser({ req, res });
if (!user) return;
@@ -20,13 +67,48 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
const dataValidation = LinkArchiveActionSchema.safeParse(req.body);
if (!dataValidation.success) {
return res.status(400).json({
- response: `Error: ${
- dataValidation.error.issues[0].message
- } [${dataValidation.error.issues[0].path.join(", ")}]`,
+ response: `Error: ${dataValidation.error.issues[0].message
+ } [${dataValidation.error.issues[0].path.join(", ")}]`,
});
}
- const { action } = dataValidation.data;
+ const { action, linkIds } = dataValidation.data;
+
+ if (linkIds) {
+ const { authorized, linkToCollectionMap } = await checkBulkLinkPermissions(user.id, linkIds);
+ if (!authorized) {
+ return res.status(401).json({
+ response: "Permission denied.",
+ });
+ }
+
+ for (const linkId of linkIds) {
+ const collectionId = linkToCollectionMap.get(linkId);
+
+ if (!collectionId) {
+ console.error(`Collection ID not found for link ${linkId}`);
+ continue;
+ }
+
+ await removeFiles(linkId, collectionId);
+ await prisma.link.update({
+ where: { id: linkId },
+ data: {
+ image: null,
+ pdf: null,
+ readable: null,
+ monolith: null,
+ preview: null,
+ lastPreserved: null,
+ indexVersion: null,
+ },
+ });
+
+ console.log("Deleted preservation link:", linkId);
+ }
+
+ return res.status(200).json({ response: "Success." })
+ }
if (action === "allAndIgnore") {
const allLinks = await prisma.link.findMany({
@@ -39,8 +121,6 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
});
for (const link of allLinks) {
- console.log("Deleted preservation link:", link.id);
-
await removePreservationFiles(link.id, link.collectionId);
await prisma.link.update({
where: { id: link.id },
@@ -52,6 +132,8 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
monolith: "unavailable",
},
});
+
+ console.log("Deleted preservation link:", link.id);
}
return res.status(200).json({ response: "Success." });
@@ -65,8 +147,6 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
},
});
for (const link of allLinks) {
- console.log("Deleted preservation link:", link.id);
-
await removeFiles(link.id, link.collectionId);
await prisma.link.update({
where: { id: link.id },
@@ -80,6 +160,8 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
indexVersion: null,
},
});
+
+ console.log("Deleted preservation link:", link.id);
}
return res.status(200).json({ response: "Success." });
@@ -121,24 +203,24 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
> =
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: 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,
- };
+ 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) ||
@@ -153,7 +235,7 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
data: {
image:
shouldArchive.archiveAsScreenshot &&
- link.image === "unavailable"
+ link.image === "unavailable"
? null
: link.image,
pdf:
@@ -162,12 +244,12 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
: link.pdf,
readable:
shouldArchive.archiveAsReadable &&
- link.readable === "unavailable"
+ link.readable === "unavailable"
? null
: link.readable,
monolith:
shouldArchive.archiveAsMonolith &&
- link.monolith === "unavailable"
+ link.monolith === "unavailable"
? null
: link.monolith,
lastPreserved: null,
diff --git a/apps/web/pages/settings/worker.tsx b/apps/web/pages/settings/worker.tsx
index 4628d15a..a12079c0 100644
--- a/apps/web/pages/settings/worker.tsx
+++ b/apps/web/pages/settings/worker.tsx
@@ -3,33 +3,9 @@ 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 "@linkwarden/lib/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"] });
- },
- });
-};
+import { useArchiveAction } from "@linkwarden/router/links";
export default function Worker() {
const { t } = useTranslation();
@@ -37,7 +13,7 @@ export default function Worker() {
const [showModal, setShowModal] = useState(false);
const [submitLoader, setSubmitLoader] = useState(false);
const [action, setAction] = useState<
- LinkArchiveActionSchemaType | undefined
+ LinkArchiveActionSchemaType["action"] | undefined
>();
useEffect(() => {
@@ -46,13 +22,13 @@ export default function Worker() {
}
}, [showModal]);
- const submit = async (action: LinkArchiveActionSchemaType) => {
+ const submit = async (action: LinkArchiveActionSchemaType['action']) => {
if (!action || submitLoader) return;
setSubmitLoader(true);
const load = toast.loading(t("deleting"));
- await archiveAction.mutateAsync(action, {
+ await archiveAction.mutateAsync({ action }, {
onSettled: (data, error) => {
setSubmitLoader(false);
toast.dismiss(load);
diff --git a/apps/web/public/locales/en/common.json b/apps/web/public/locales/en/common.json
index ad2fe4f1..9f2d5d47 100644
--- a/apps/web/public/locales/en/common.json
+++ b/apps/web/public/locales/en/common.json
@@ -474,5 +474,6 @@
"no_broken_preservations": "No broken preservations.",
"links_are_being_represerved": "Links are being re-preserved...",
"cancel": "Cancel",
- "preservation_rules": "Preservation rules:"
+ "preservation_rules": "Preservation rules:",
+ "links_being_archived": "Links are being archived..."
}
\ No newline at end of file
diff --git a/packages/lib/schemaValidation.ts b/packages/lib/schemaValidation.ts
index 6438d339..caf4477b 100644
--- a/packages/lib/schemaValidation.ts
+++ b/packages/lib/schemaValidation.ts
@@ -41,12 +41,12 @@ export const PostUserSchema = () => {
username: emailEnabled
? z.string().optional()
: z
- .string()
- .trim()
- .toLowerCase()
- .min(3)
- .max(50)
- .regex(/^[a-z0-9_-]{3,50}$/),
+ .string()
+ .trim()
+ .toLowerCase()
+ .min(3)
+ .max(50)
+ .regex(/^[a-z0-9_-]{3,50}$/),
invite: z.boolean().optional(),
});
};
@@ -253,9 +253,8 @@ export const PostHighlightSchema = z.object({
export type PostHighlightSchemaType = z.infer<typeof PostHighlightSchema>;
export const LinkArchiveActionSchema = z.object({
- action: z.enum(["allAndRePreserve", "allAndIgnore", "allBroken"]),
+ action: z.enum(["allAndRePreserve", "allAndIgnore", "allBroken"]).optional(),
+ linkIds: z.array(z.number()).optional()
});
-export type LinkArchiveActionSchemaType = z.infer<
- typeof LinkArchiveActionSchema
->["action"];
+export type LinkArchiveActionSchemaType = z.infer<typeof LinkArchiveActionSchema>;
diff --git a/packages/router/links.tsx b/packages/router/links.tsx
index 7bc903d2..ab343b67 100644
--- a/packages/router/links.tsx
+++ b/packages/router/links.tsx
@@ -11,7 +11,7 @@ import {
MobileAuth,
} from "@linkwarden/types";
import { useSession } from "next-auth/react";
-import { PostLinkSchemaType } from "@linkwarden/lib/schemaValidation";
+import { LinkArchiveActionSchemaType, PostLinkSchemaType } from "@linkwarden/lib/schemaValidation";
import getFormatFromContentType from "@linkwarden/lib/getFormatFromContentType";
import getLinkTypeFromFormat from "@linkwarden/lib/getLinkTypeFromFormat";
@@ -64,10 +64,10 @@ const useFetchLinks = (params: string, auth?: MobileAuth) => {
url,
auth?.session
? {
- headers: {
- Authorization: `Bearer ${auth.session}`,
- },
- }
+ headers: {
+ Authorization: `Bearer ${auth.session}`,
+ },
+ }
: undefined
);
const data = await response.json();
@@ -243,10 +243,10 @@ const useGetLink = (isPublicRoute?: boolean, auth?: MobileAuth) => {
path,
auth?.session
? {
- headers: {
- Authorization: `Bearer ${auth?.session}`,
- },
- }
+ headers: {
+ Authorization: `Bearer ${auth?.session}`,
+ },
+ }
: undefined
);
const data = await response.json();
@@ -446,8 +446,8 @@ const useUpdateFile = () => {
const res = await fetch(
`/api/v1/archives/${linkId}?format=` +
- format +
- (isPreview ? "&preview=true" : ""),
+ format +
+ (isPreview ? "&preview=true" : ""),
{
body: formBody,
method: "POST",
@@ -508,6 +508,34 @@ const useBulkEditLinks = () => {
});
};
+const useArchiveAction = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (payload: LinkArchiveActionSchemaType) => {
+ const response = await fetch("/api/v1/links/archive", {
+ body: JSON.stringify({
+ action: payload.action,
+ linkIds: payload.linkIds,
+ }),
+ 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"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
+ },
+ });
+};
+
const resetInfiniteQueryPagination = async (
queryClient: any,
queryKey: any
@@ -533,6 +561,7 @@ export {
useUploadFile,
useGetLink,
useBulkEditLinks,
+ useArchiveAction,
resetInfiniteQueryPagination,
useUpdateFile,
};
diff --git a/packages/router/publicTags.tsx b/packages/router/publicTags.tsx
index 53c063e8..d7936fbf 100644
--- a/packages/router/publicTags.tsx
+++ b/packages/router/publicTags.tsx
@@ -1,13 +1,10 @@
import { Tag } from "@linkwarden/prisma/client";
import { useQuery, UseQueryResult } from "@tanstack/react-query";
-import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
type TagIncludingCount = Tag & { _count: { links: number } };
const usePublicTags = (): UseQueryResult<TagIncludingCount[]> => {
- const { status } = useSession();
-
const router = useRouter();
return useQuery({
@@ -15,8 +12,8 @@ const usePublicTags = (): UseQueryResult<TagIncludingCount[]> => {
queryFn: async () => {
const response = await fetch(
"/api/v1/public/collections/tags" +
- "?collectionId=" +
- router.query.id || ""
+ "?collectionId=" +
+ router.query.id || ""
);
if (!response.ok) throw new Error("Failed to fetch tags.");