Skip to content

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

wip

daniel31x1300c33d48f0b7
diff --git a/components/LinkDetails.tsx b/components/LinkDetails.tsx
index 4acf799a..982fbb7a 100644
--- a/components/LinkDetails.tsx
+++ b/components/LinkDetails.tsx
@@ -13,11 +13,7 @@ import getPublicUserData from "@/lib/client/getPublicUserData";
import { useTranslation } from "next-i18next";
import { BeatLoader } from "react-spinners";
import { useUser } from "@/hooks/store/user";
-import {
- useGetLink,
- useUpdateLink,
- useUpdatePreview,
-} from "@/hooks/store/links";
+import { useGetLink, useUpdateLink, useUpdateFile } from "@/hooks/store/links";
import LinkIcon from "./LinkViews/LinkComponents/LinkIcon";
import CopyButton from "./CopyButton";
import { useRouter } from "next/router";
@@ -140,7 +136,7 @@ export default function LinkDetails({
const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
const updateLink = useUpdateLink();
- const updatePreview = useUpdatePreview();
+ const updateFile = useUpdateFile();
const submit = async (e?: any) => {
e?.preventDefault();
@@ -235,10 +231,11 @@ export default function LinkDetails({
const load = toast.loading(t("updating"));
- await updatePreview.mutateAsync(
+ await updateFile.mutateAsync(
{
linkId: link.id as number,
file,
+ isPreview: true,
},
{
onSettled: (data, error) => {
@@ -248,7 +245,10 @@ export default function LinkDetails({
toast.error(error.message);
} else {
toast.success(t("updated"));
- setLink({ updatedAt: data.updatedAt, ...link });
+ setLink({
+ updatedAt: data.response.updatedAt,
+ ...link,
+ });
}
},
}
diff --git a/components/ModalContent/NewRssSubscriptionModal.tsx b/components/ModalContent/NewRssSubscriptionModal.tsx
index c81b6a64..b959ef3e 100644
--- a/components/ModalContent/NewRssSubscriptionModal.tsx
+++ b/components/ModalContent/NewRssSubscriptionModal.tsx
@@ -25,7 +25,11 @@ export default function NewRssSubscriptionModal({ onClose }: Props) {
const submit = async () => {
if (submitLoader) return;
- if (!form.name || !form.url || (!form.collectionId && !form.collectionName)) {
+ if (
+ !form.name ||
+ !form.url ||
+ (!form.collectionId && !form.collectionName)
+ ) {
return toast.error(t("fill_all_fields"));
}
@@ -95,7 +99,7 @@ export default function NewRssSubscriptionModal({ onClose }: Props) {
className="btn btn-accent dark:border-violet-400 text-white"
onClick={submit}
>
- {t("create_token")}
+ {t("create_rss_subscription")}
</button>
</div>
</>
diff --git a/components/Preservation.tsx b/components/Preservation.tsx
index 759007ff..b710409b 100644
--- a/components/Preservation.tsx
+++ b/components/Preservation.tsx
@@ -82,7 +82,7 @@ export default function Preservation() {
case ArchivedFormat.readability:
return (
<div className="overflow-auto w-full h-full">
- <ReadableView link={link} />
+ <ReadableView link={link} isExpanded={isExpanded} />
</div>
);
diff --git a/components/ReadableView.tsx b/components/ReadableView.tsx
index c528da2b..a4ccd58b 100644
--- a/components/ReadableView.tsx
+++ b/components/ReadableView.tsx
@@ -15,6 +15,7 @@ import unescapeString from "@/lib/client/unescapeString";
import usePermissions from "@/hooks/usePermissions";
import showdown from "showdown";
import TurndownService from "turndown";
+import { useUpdateFile } from "@/hooks/store/links";
const turndownService = new TurndownService({
headingStyle: "atx",
@@ -43,9 +44,10 @@ const converter = new showdown.Converter({
type Props = {
link: LinkIncludingShortenedCollectionAndTags;
+ isExpanded: boolean;
};
-export default function ReadableView({ link }: Props) {
+export default function ReadableView({ link, isExpanded }: Props) {
const { t } = useTranslation();
const [linkContent, setLinkContent] = useState("");
@@ -89,6 +91,8 @@ export default function ReadableView({ link }: Props) {
setIsEditing(false);
};
+ const updateFile = useUpdateFile();
+
const saveChanges = () => {
const updatedHTML = DOMPurify.sanitize(converter.makeHtml(editedMarkdown));
@@ -98,41 +102,46 @@ export default function ReadableView({ link }: Props) {
setIsEditing(false);
- // If you want to persist it somewhere:
- // await fetch('/api/saveHtml', {
- // method: 'PUT',
- // body: JSON.stringify({ html: updatedHTML }),
- // headers: { 'Content-Type': 'application/json' },
- // });
+ updateFile.mutate({
+ linkId: link.id as number,
+ file: new File([updatedHTML], "updatedContent.txt", {
+ type: "text/plain",
+ }),
+ });
};
return (
<div className="flex flex-col gap-3 items-start p-3">
- <div className="flex gap-3 items-start">
- <div className="flex flex-col w-full gap-1">
- <p className="md:text-4xl text-2xl">
- {unescapeString(link?.name || link?.description || link?.url || "")}
- </p>
- {link?.url && (
- <Link
- href={link?.url || ""}
- title={link?.url}
- target="_blank"
- className="hover:opacity-60 duration-100 break-all text-sm flex items-center gap-1 text-neutral w-fit"
- >
- <i className="bi-link-45deg" />
- {isValidUrl(link?.url || "") && new URL(link?.url as string).host}
- </Link>
- )}
+ {!isEditing && (
+ <div className="flex gap-3 items-start">
+ <div className="flex flex-col w-full gap-1">
+ <p className="md:text-4xl text-2xl">
+ {unescapeString(
+ link?.name || link?.description || link?.url || ""
+ )}
+ </p>
+ {link?.url && (
+ <Link
+ href={link?.url || ""}
+ title={link?.url}
+ target="_blank"
+ className="hover:opacity-60 duration-100 break-all text-sm flex items-center gap-1 text-neutral w-fit"
+ >
+ <i className="bi-link-45deg" />
+ {isValidUrl(link?.url || "") &&
+ new URL(link?.url as string).host}
+ </Link>
+ )}
+ </div>
</div>
- </div>
+ )}
<div className="text-sm text-neutral flex justify-between w-full gap-2">
<LinkDate link={link} />
{!isPublicRoute && (permissions === true || permissions?.canUpdate) && (
<>
- {!isEditing ? (
+ {!isEditing && linkContent ? (
<button
className="flex items-center gap-2 btn btn-sm"
onClick={startEditing}
@@ -140,8 +149,13 @@ export default function ReadableView({ link }: Props) {
<i className="bi-pencil" />
{t("edit")}
</button>
- ) : (
- <div className="flex items-center gap-2">
+ ) : linkContent ? (
+ <div
+ className={clsx(
+ "flex items-center gap-2",
+ isExpanded && "mr-10"
+ )}
+ >
<button
className="flex items-center gap-2 btn btn-sm"
onClick={cancelEditing}
@@ -155,7 +169,7 @@ export default function ReadableView({ link }: Props) {
<i className="bi-check2 text-xl" />
</button>
</div>
- )}
+ ) : null}
</>
)}
</div>
@@ -165,7 +179,12 @@ export default function ReadableView({ link }: Props) {
{linkContent ? (
isEditing ? (
<textarea
- className="h-[50vh] w-full rounded-md p-3 border-neutral-content bg-base-200 focus:border-primary border-solid border outline-none duration-100"
+ className={clsx(
+ "w-full rounded-md p-3 border-neutral-content bg-base-200 focus:border-primary border-solid border outline-none duration-100 resize-none",
+ isExpanded
+ ? "h-[calc(100vh-4.5rem)]"
+ : "h-[calc(100vh-8.5rem)]"
+ )}
value={editedMarkdown}
onChange={(e) => setEditedMarkdown(e.target.value)}
/>
diff --git a/hooks/store/links.tsx b/hooks/store/links.tsx
index aa8c52b3..88a51691 100644
--- a/hooks/store/links.tsx
+++ b/hooks/store/links.tsx
@@ -14,6 +14,8 @@ import {
import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
import { PostLinkSchemaType } from "@/lib/shared/schemaValidation";
+import getFormatFromContentType from "@/lib/shared/getFormatFromContentType";
+import getLinkTypeFromFormat from "@/lib/shared/getLinkTypeFromFormat";
const useLinks = (params: LinkRequestQuery = {}) => {
const router = useRouter();
@@ -345,21 +347,8 @@ const useUploadFile = () => {
return useMutation({
mutationFn: async ({ link, file }: any) => {
- let fileType: ArchivedFormat | null = null;
- let linkType: "url" | "image" | "pdf" | null = null;
-
- if (file?.type === "image/jpg" || file.type === "image/jpeg") {
- fileType = ArchivedFormat.jpeg;
- linkType = "image";
- } else if (file.type === "image/png") {
- fileType = ArchivedFormat.png;
- linkType = "image";
- } else if (file.type === "application/pdf") {
- fileType = ArchivedFormat.pdf;
- linkType = "pdf";
- } else {
- return { ok: false, data: "Invalid file type." };
- }
+ let format = getFormatFromContentType(file?.type);
+ let linkType = getLinkTypeFromFormat(format);
const response = await fetch("/api/v1/links", {
body: JSON.stringify({
@@ -382,7 +371,7 @@ const useUploadFile = () => {
file && formBody.append("file", file);
await fetch(
- `/api/v1/archives/${(data as any).response.id}?format=${fileType}`,
+ `/api/v1/archives/${(data as any).response.id}?format=${format}`,
{
body: formBody,
method: "POST",
@@ -416,23 +405,37 @@ const useUploadFile = () => {
});
};
-const useUpdatePreview = () => {
+const useUpdateFile = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ linkId, file }: { linkId: number; file: File }) => {
+ mutationFn: async ({
+ linkId,
+ file,
+ isPreview,
+ }: {
+ linkId: number;
+ file: File;
+ isPreview?: boolean;
+ }) => {
const formBody = new FormData();
+ let format = getFormatFromContentType(file?.type);
+
+ if (isPreview) format = ArchivedFormat.jpeg;
+
if (!linkId || !file)
throw new Error("Error generating preview: Invalid parameters");
formBody.append("file", file);
const res = await fetch(
- `/api/v1/archives/${linkId}?format=` + ArchivedFormat.jpeg,
+ `/api/v1/archives/${linkId}?format=` +
+ format +
+ (isPreview ? "&preview=true" : ""),
{
body: formBody,
- method: "PUT",
+ method: "POST",
}
);
@@ -561,5 +564,5 @@ export {
useGetLink,
useBulkEditLinks,
resetInfiniteQueryPagination,
- useUpdatePreview,
+ useUpdateFile,
};
diff --git a/lib/api/generatePreview.ts b/lib/api/generatePreview.ts
index 1c6ca94f..c864fb53 100644
--- a/lib/api/generatePreview.ts
+++ b/lib/api/generatePreview.ts
@@ -20,7 +20,7 @@ const generatePreview = async (
const processedBuffer = await image.getBufferAsync(Jimp.MIME_JPEG);
if (
- Buffer.byteLength(processedBuffer) >
+ Buffer.byteLength(processedBuffer as any) >
1024 * 1024 * Number(process.env.PREVIEW_MAX_BUFFER || 0.1)
) {
console.log("Error generating preview: Buffer size exceeded");
diff --git a/lib/api/isDemoMode.ts b/lib/api/isDemoMode.ts
new file mode 100644
index 00000000..08aa1bb2
--- /dev/null
+++ b/lib/api/isDemoMode.ts
@@ -0,0 +1,3 @@
+export default function isDemoMode() {
+ return process.env.NEXT_PUBLIC_DEMO === "true";
+}
diff --git a/lib/api/preservationScheme/handleReadablility.ts b/lib/api/preservationScheme/handleReadablility.ts
index e274fc26..0960fa76 100644
--- a/lib/api/preservationScheme/handleReadablility.ts
+++ b/lib/api/preservationScheme/handleReadablility.ts
@@ -5,7 +5,11 @@ import { prisma } from "../db";
import createFile from "../storage/createFile";
import { Link } from "@prisma/client";
-const handleReadablility = async (content: string, link: Link) => {
+const handleReadablility = async (
+ content: string,
+ link: Link,
+ keepContent?: boolean
+) => {
const window = new JSDOM("").window;
const purify = DOMPurify(window);
const cleanedUpContent = purify.sanitize(content);
@@ -23,6 +27,10 @@ const handleReadablility = async (content: string, link: Link) => {
})
)?.collectionId;
+ if (article && keepContent) {
+ article.content = cleanedUpContent;
+ }
+
const data = JSON.stringify(article);
if (
diff --git a/lib/shared/getFormatFromContentType.ts b/lib/shared/getFormatFromContentType.ts
new file mode 100644
index 00000000..2e5babd2
--- /dev/null
+++ b/lib/shared/getFormatFromContentType.ts
@@ -0,0 +1,21 @@
+import { ArchivedFormat } from "@/types/global";
+
+const getFormatFromContentType = (contentType: string): ArchivedFormat => {
+ switch (contentType) {
+ case "image/jpg":
+ case "image/jpeg":
+ return ArchivedFormat.jpeg;
+ case "image/png":
+ return ArchivedFormat.png;
+ case "application/pdf":
+ return ArchivedFormat.pdf;
+ case "text/html":
+ return ArchivedFormat.monolith;
+ case "text/plain":
+ return ArchivedFormat.readability;
+ default:
+ throw new Error("Invalid file type.");
+ }
+};
+
+export default getFormatFromContentType;
diff --git a/lib/shared/getLinkTypeFromFormat.ts b/lib/shared/getLinkTypeFromFormat.ts
new file mode 100644
index 00000000..b6cdcd9d
--- /dev/null
+++ b/lib/shared/getLinkTypeFromFormat.ts
@@ -0,0 +1,21 @@
+import { ArchivedFormat } from "@/types/global";
+
+const getLinkTypeFromFormat = (
+ format: ArchivedFormat
+): "image" | "pdf" | "readable" | "monolith" => {
+ switch (format) {
+ case ArchivedFormat.jpeg:
+ case ArchivedFormat.png:
+ return "image";
+ case ArchivedFormat.pdf:
+ return "pdf";
+ case ArchivedFormat.readability:
+ return "readable";
+ case ArchivedFormat.monolith:
+ return "monolith";
+ default:
+ throw new Error("Invalid file type.");
+ }
+};
+
+export default getLinkTypeFromFormat;
diff --git a/lib/shared/getSuffixFromFormat.ts b/lib/shared/getSuffixFromFormat.ts
new file mode 100644
index 00000000..5e007a18
--- /dev/null
+++ b/lib/shared/getSuffixFromFormat.ts
@@ -0,0 +1,18 @@
+import { ArchivedFormat } from "@/types/global";
+
+export default function getSuffixFromFormat(format: number): string | null {
+ switch (format) {
+ case ArchivedFormat.png:
+ return ".png";
+ case ArchivedFormat.jpeg:
+ return ".jpeg";
+ case ArchivedFormat.pdf:
+ return ".pdf";
+ case ArchivedFormat.readability:
+ return "_readability.json";
+ case ArchivedFormat.monolith:
+ return ".html";
+ default:
+ return null;
+ }
+}
diff --git a/lib/shared/schemaValidation.ts b/lib/shared/schemaValidation.ts
index 8475505d..d549c9f5 100644
--- a/lib/shared/schemaValidation.ts
+++ b/lib/shared/schemaValidation.ts
@@ -156,6 +156,7 @@ const ACCEPTED_TYPES = [
"image/jpg",
"image/png",
"application/pdf",
+ "text/plain",
];
const NEXT_PUBLIC_MAX_FILE_BUFFER = Number(
process.env.NEXT_PUBLIC_MAX_FILE_BUFFER || 10
diff --git a/pages/api/v1/archives/[linkId].ts b/pages/api/v1/archives/[linkId].ts
index 03fa1a16..435ee3be 100644
--- a/pages/api/v1/archives/[linkId].ts
+++ b/pages/api/v1/archives/[linkId].ts
@@ -1,18 +1,23 @@
import type { NextApiRequest, NextApiResponse } from "next";
+import formidable from "formidable";
+import fs from "fs";
import readFile from "@/lib/api/storage/readFile";
-import { prisma } from "@/lib/api/db";
-import { ArchivedFormat } from "@/types/global";
+import createFile from "@/lib/api/storage/createFile";
+import createFolder from "@/lib/api/storage/createFolder";
+import generatePreview from "@/lib/api/generatePreview";
+import verifyToken from "@/lib/api/verifyToken";
import verifyUser from "@/lib/api/verifyUser";
import getPermission from "@/lib/api/getPermission";
+import { prisma } from "@/lib/api/db";
import { UsersAndCollections } from "@prisma/client";
-import formidable from "formidable";
-import createFile from "@/lib/api/storage/createFile";
-import fs from "fs";
-import verifyToken from "@/lib/api/verifyToken";
-import generatePreview from "@/lib/api/generatePreview";
-import createFolder from "@/lib/api/storage/createFolder";
import { UploadFileSchema } from "@/lib/shared/schemaValidation";
+import isDemoMode from "@/lib/api/isDemoMode";
+import getSuffixFromFormat from "@/lib/shared/getSuffixFromFormat";
import DOMPurify from "dompurify";
+import { formatAvailable } from "@/lib/shared/formatStats";
+import { ArchivedFormat } from "@/types/global";
+import getLinkTypeFromFormat from "@/lib/shared/getLinkTypeFromFormat";
+import handleReadablility from "@/lib/api/preservationScheme/handleReadablility";
export const config = {
api: {
@@ -20,295 +25,306 @@ export const config = {
},
};
-export default async function Index(req: NextApiRequest, res: NextApiResponse) {
- const linkId = Number(req.query.linkId);
- const format = Number(req.query.format);
- const isPreview = Boolean(req.query.preview);
+/** ------------------ */
+/** Helper Functions */
+/** ------------------ */
+
+// Check whether user can create in the given collection
+function userHasCreatePermission(
+ collectionPermissions: any,
+ userId: number
+): boolean {
+ if (!collectionPermissions) return false;
+ const memberHasAccess = collectionPermissions.members.some(
+ (e: UsersAndCollections) => e.userId === userId && e.canCreate
+ );
+ return collectionPermissions.ownerId === userId || Boolean(memberHasAccess);
+}
- let suffix: string;
+// Ensure user does not exceed maximum link limit
+async function verifyLinkLimit(userId: number) {
+ const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER || 30000);
+ const userLinkCount = await prisma.link.count({
+ where: {
+ collection: {
+ ownerId: userId,
+ },
+ },
+ });
+ if (userLinkCount > MAX_LINKS_PER_USER) {
+ throw new Error(
+ `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`
+ );
+ }
+}
- if (format === ArchivedFormat.png) suffix = ".png";
- else if (format === ArchivedFormat.jpeg) suffix = ".jpeg";
- else if (format === ArchivedFormat.pdf) suffix = ".pdf";
- else if (format === ArchivedFormat.readability) suffix = "_readability.json";
- else if (format === ArchivedFormat.monolith) suffix = ".html";
+// Common validation for file size and type
+function validateFile(
+ file: formidable.File,
+ maxMB: number,
+ allowedTypes: string[]
+) {
+ if (!file || !allowedTypes.includes(file.mimetype || "")) {
+ throw new Error(
+ `Sorry, we couldn't process your file. Please ensure it's in [${allowedTypes.join(
+ ", "
+ )}] format and doesn't exceed ${maxMB}MB.`
+ );
+ }
- //@ts-ignore
- if (!linkId || !suffix)
- return res.status(401).json({ response: "Invalid parameters." });
+ const fileBuffer = fs.readFileSync(file.filepath);
+ if (Buffer.byteLength(fileBuffer as any) > 1024 * 1024 * maxMB) {
+ throw new Error(
+ `Sorry, we couldn't process your file. Please ensure it doesn't exceed ${maxMB}MB.`
+ );
+ }
- if (req.method === "GET") {
- const token = await verifyToken({ req });
- const userId = typeof token === "string" ? undefined : token?.id;
+ return fileBuffer;
+}
- const collectionIsAccessible = await prisma.collection.findFirst({
- where: {
- links: {
- some: {
- id: linkId,
- },
+// Retrieve collection if accessible (for both GET and file uploads/updates)
+async function getAccessibleCollection(
+ linkId: number,
+ userId: number | undefined
+) {
+ return prisma.collection.findFirst({
+ where: {
+ links: {
+ some: {
+ id: linkId,
},
- OR: [
- { ownerId: userId || -1 },
- { members: { some: { userId: userId || -1 } } },
- { isPublic: true },
- ],
},
- });
+ OR: [
+ { ownerId: userId || -1 },
+ { members: { some: { userId: userId || -1 } } },
+ { isPublic: true },
+ ],
+ },
+ });
+}
- if (!collectionIsAccessible)
- return res
- .status(401)
- .json({ response: "You don't have access to this collection." });
+/** ------------------ */
+/** Route Handlers */
+/** ------------------ */
- if (isPreview) {
- const { file, contentType, status } = await readFile(
- `archives/preview/${collectionIsAccessible.id}/${linkId}.jpeg`
- );
+async function handleGet(req: NextApiRequest, res: NextApiResponse) {
+ const linkId = Number(req.query.linkId);
+ const format = Number(req.query.format);
+ const isPreview = Boolean(req.query.preview);
- res.setHeader("Content-Type", contentType).status(status as number);
+ const suffix = getSuffixFromFormat(format);
+ if (!linkId || !suffix) {
+ return res.status(401).json({ response: "Invalid parameters." });
+ }
- return res.send(file);
- } else {
- const { file, contentType, status } = await readFile(
- `archives/${collectionIsAccessible.id}/${linkId + suffix}`
- );
+ // Verify token => If present, get user ID
+ const token = await verifyToken({ req });
+ const userId = typeof token === "string" ? undefined : token?.id;
- res.setHeader("Content-Type", contentType).status(status as number);
+ // Check if user can access the collection
+ const collection = await getAccessibleCollection(linkId, userId);
+ if (!collection) {
+ return res
+ .status(401)
+ .json({ response: "You don't have access to this collection." });
+ }
- return res.send(file);
- }
- } else if (req.method === "POST") {
- if (process.env.NEXT_PUBLIC_DEMO === "true")
- return res.status(400).json({
- response:
- "This action is disabled because this is a read-only demo of Linkwarden.",
- });
+ // Decide the file path
+ const filePath = isPreview
+ ? `archives/preview/${collection.id}/${linkId}.jpeg`
+ : `archives/${collection.id}/${linkId + suffix}`;
- const user = await verifyUser({ req, res });
- if (!user) return;
+ const { file, contentType, status } = await readFile(filePath);
+ res.setHeader("Content-Type", contentType).status(status as number);
+ return res.send(file);
+}
- const collectionPermissions = await getPermission({
- userId: user.id,
- linkId,
+async function handlePost(req: NextApiRequest, res: NextApiResponse) {
+ if (isDemoMode()) {
+ return res.status(400).json({
+ response:
+ "This action is disabled because this is a read-only demo of Linkwarden.",
});
+ }
- if (!collectionPermissions)
- return res.status(400).json({
- response: "Collection is not accessible.",
- });
+ const linkId = Number(req.query.linkId);
+ const format = Number(req.query.format);
+ const suffix = getSuffixFromFormat(format);
+ const isPreview = Boolean(req.query.preview);
- const memberHasAccess = collectionPermissions.members.some(
- (e: UsersAndCollections) => e.userId === user.id && e.canCreate
- );
+ if (!linkId || !suffix) {
+ return res.status(401).json({ response: "Invalid parameters." });
+ }
- if (!(collectionPermissions.ownerId === user.id || memberHasAccess))
- return res.status(400).json({
- response: "Collection is not accessible.",
- });
+ // Verify user and collection permissions
+ const user = await verifyUser({ req, res });
+ if (!user) return; // verifyUser already handles the response on failure
+
+ const collectionPermissions = await getPermission({
+ userId: user.id,
+ linkId,
+ });
+ if (
+ !userHasCreatePermission(collectionPermissions, user.id) ||
+ !collectionPermissions
+ ) {
+ return res.status(400).json({ response: "Collection is not accessible." });
+ }
- const MAX_LINKS_PER_USER = Number(process.env.MAX_LINKS_PER_USER || 30000);
+ const link = await prisma.link.findUnique({
+ where: {
+ id: linkId,
+ },
+ });
- const numberOfLinksTheUserHas = await prisma.link.count({
- where: {
- collection: {
- ownerId: user.id,
- },
- },
- });
+ if (!link) {
+ return res.status(400).json({ response: "Link not found." });
+ }
- if (numberOfLinksTheUserHas > MAX_LINKS_PER_USER)
- return res.status(400).json({
- response: `Each collection owner can only have a maximum of ${MAX_LINKS_PER_USER} Links.`,
- });
+ // Ensure if the png already exists, the user is not trying to upload a jpeg (and vice versa)
+ if (
+ (((link.image?.endsWith("jpeg") || link.image?.endsWith("png")) &&
+ format === ArchivedFormat.png) ||
+ (link.image?.endsWith("png") && format === ArchivedFormat.jpeg)) &&
+ !isPreview
+ ) {
+ return res
+ .status(400)
+ .json({ response: "PNG or JPEG file already exists." });
+ }
- const NEXT_PUBLIC_MAX_FILE_BUFFER = Number(
- process.env.NEXT_PUBLIC_MAX_FILE_BUFFER || 10
- );
+ try {
+ await verifyLinkLimit(user.id);
+ } catch (err: any) {
+ return res.status(400).json({ response: err.message });
+ }
- const form = formidable({
- maxFields: 1,
- maxFiles: 1,
- maxFileSize: NEXT_PUBLIC_MAX_FILE_BUFFER * 1024 * 1024,
- });
+ const NEXT_PUBLIC_MAX_FILE_BUFFER = Number(
+ process.env.NEXT_PUBLIC_MAX_FILE_BUFFER || 10
+ );
+
+ const form = formidable({
+ maxFields: 1,
+ maxFiles: 1,
+ maxFileSize: NEXT_PUBLIC_MAX_FILE_BUFFER * 1024 * 1024,
+ });
+
+ form.parse(req, async (err, fields, files) => {
+ try {
+ if (err || !files.file || !files.file[0]) {
+ throw new Error(
+ `Sorry, we couldn't process your file. Please ensure it doesn't exceed ${NEXT_PUBLIC_MAX_FILE_BUFFER}MB.`
+ );
+ }
- form.parse(req, async (err, fields, files) => {
+ // Validate input against Zod schema
+ const dataValidation = UploadFileSchema.safeParse({
+ id: linkId,
+ format,
+ file: files.file,
+ });
+ if (!dataValidation.success) {
+ const issue = dataValidation.error.issues[0];
+ throw new Error(`Error: ${issue.message} [${issue.path.join(", ")}]`);
+ }
+
+ // Check file type and size
const allowedMIMETypes = [
"application/pdf",
"image/png",
"image/jpg",
"image/jpeg",
+ "text/plain",
];
+ const fileBuffer = validateFile(
+ files.file[0],
+ NEXT_PUBLIC_MAX_FILE_BUFFER,
+ allowedMIMETypes
+ );
- const dataValidation = UploadFileSchema.safeParse({
- id: Number(req.query.linkId),
- format: Number(req.query.format),
- file: files.file,
+ // Confirm the link still exists
+ const linkStillExists = await prisma.link.findUnique({
+ where: { id: linkId },
});
-
- if (!dataValidation.success) {
- return res.status(400).json({
- response: `Error: ${
- dataValidation.error.issues[0].message
- } [${dataValidation.error.issues[0].path.join(", ")}]`,
- });
+ if (!linkStillExists) {
+ throw new Error("Link not found.");
}
- if (
- err ||
- !files.file ||
- !files.file[0] ||
- !allowedMIMETypes.includes(files.file[0].mimetype || "")
- ) {
- // Handle parsing error
- return res.status(400).json({
- response: `Sorry, we couldn't process your file. Please ensure it's a PDF, PNG, or JPG format and doesn't exceed ${NEXT_PUBLIC_MAX_FILE_BUFFER}MB.`,
- });
- } else {
- const fileBuffer = fs.readFileSync(files.file[0].filepath);
-
- if (
- Buffer.byteLength(fileBuffer) >
- 1024 * 1024 * Number(NEXT_PUBLIC_MAX_FILE_BUFFER)
- )
- return res.status(400).json({
- response: `Sorry, we couldn't process your file. Please ensure it's a PDF, PNG, or JPG format and doesn't exceed ${NEXT_PUBLIC_MAX_FILE_BUFFER}MB.`,
- });
-
- const linkStillExists = await prisma.link.findUnique({
- where: { id: linkId },
- });
+ // Generate a preview if it's an image
+ const { mimetype } = files.file[0];
+ const isPDF = mimetype?.includes("pdf");
+ const isImage = mimetype?.includes("image");
+ const isReadable = mimetype?.includes("text");
- const { mimetype } = files.file[0];
- const isPDF = mimetype?.includes("pdf");
- const isImage = mimetype?.includes("image");
-
- if (linkStillExists && isImage) {
- const collectionId = collectionPermissions.id;
- createFolder({
- filePath: `archives/preview/${collectionId}`,
- });
-
- generatePreview(fileBuffer, collectionId, linkId);
- }
-
- if (linkStillExists) {
- await createFile({
- filePath: `archives/${collectionPermissions.id}/${linkId + suffix}`,
- data: fileBuffer,
- });
-
- await prisma.link.update({
- where: { id: linkId },
- data: {
- preview: isPDF ? "unavailable" : undefined,
- image: isImage
- ? `archives/${collectionPermissions.id}/${linkId + suffix}`
- : null,
- pdf: isPDF
- ? `archives/${collectionPermissions.id}/${linkId + suffix}`
- : null,
- lastPreserved: new Date().toISOString(),
- },
- });
- }
+ if (isReadable) {
+ await handleReadablility(fileBuffer.toString(), link, true);
fs.unlinkSync(files.file[0].filepath);
- }
- return res.status(200).json({
- response: files,
- });
- });
- }
- // To update the link preview
- else if (req.method === "PUT") {
- if (process.env.NEXT_PUBLIC_DEMO === "true")
- return res.status(400).json({
- response:
- "This action is disabled because this is a read-only demo of Linkwarden.",
- });
-
- const user = await verifyUser({ req, res });
- if (!user) return;
-
- const collectionPermissions = await getPermission({
- userId: user.id,
- linkId,
- });
+ return res.status(200).json({ response: files });
+ }
- if (!collectionPermissions)
- return res.status(400).json({
- response: "Collection is not accessible.",
- });
+ if (isImage) {
+ const collectionId = collectionPermissions.id;
+ createFolder({ filePath: `archives/preview/${collectionId}` });
+ await generatePreview(fileBuffer, collectionId, linkId);
+ }
- const memberHasAccess = collectionPermissions.members.some(
- (e: UsersAndCollections) => e.userId === user.id && e.canCreate
- );
+ if (!isPreview) {
+ // Store the file
+ await createFile({
+ filePath: `archives/${collectionPermissions.id}/${linkId + suffix}`,
+ data: fileBuffer,
+ });
+ }
- if (!(collectionPermissions.ownerId === user.id || memberHasAccess))
- return res.status(400).json({
- response: "Collection is not accessible.",
+ // Update link in DB
+ const updateLink = await prisma.link.update({
+ where: { id: linkId },
+ data: {
+ preview: isPDF ? "unavailable" : undefined,
+ image:
+ isImage && !isPreview
+ ? `archives/${collectionPermissions.id}/${linkId + suffix}`
+ : undefined,
+ pdf: isPDF
+ ? `archives/${collectionPermissions.id}/${linkId + suffix}`
+ : undefined,
+ contentEdited: isReadable ? new Date().toISOString() : undefined,
+ lastPreserved: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ },
});
- const NEXT_PUBLIC_MAX_FILE_BUFFER = Number(
- process.env.NEXT_PUBLIC_MAX_FILE_BUFFER || 10
- );
-
- const form = formidable({
- maxFields: 1,
- maxFiles: 1,
- maxFileSize: NEXT_PUBLIC_MAX_FILE_BUFFER * 1024 * 1024,
- });
+ // Clean up temporary file
+ fs.unlinkSync(files.file[0].filepath);
- form.parse(req, async (err, fields, files) => {
- const allowedMIMETypes = ["image/png", "image/jpg", "image/jpeg"];
-
- if (
- err ||
- !files.file ||
- !files.file[0] ||
- !allowedMIMETypes.includes(files.file[0].mimetype || "")
- ) {
- // Handle parsing error
- return res.status(400).json({
- response: `Sorry, we couldn't process your file. Please ensure it's a PDF, PNG, or JPG format and doesn't exceed ${NEXT_PUBLIC_MAX_FILE_BUFFER}MB.`,
- });
- } else {
- const fileBuffer = fs.readFileSync(files.file[0].filepath);
-
- if (
- Buffer.byteLength(fileBuffer) >
- 1024 * 1024 * Number(NEXT_PUBLIC_MAX_FILE_BUFFER)
- )
- return res.status(400).json({
- response: `Sorry, we couldn't process your file. Please ensure it's a PNG, or JPG format and doesn't exceed ${NEXT_PUBLIC_MAX_FILE_BUFFER}MB.`,
- });
-
- const linkStillExists = await prisma.link.update({
- where: { id: linkId },
- data: {
- updatedAt: new Date(),
- },
- });
-
- if (linkStillExists) {
- const collectionId = collectionPermissions.id;
- createFolder({
- filePath: `archives/preview/${collectionId}`,
- });
-
- await generatePreview(fileBuffer, collectionId, linkId);
- }
+ return res.status(200).json({ response: updateLink });
+ } catch (error: any) {
+ return res.status(400).json({ response: error.message });
+ }
+ });
+}
- fs.unlinkSync(files.file[0].filepath);
+/** ------------------ */
+/** Main API Handler */
+/** ------------------ */
- if (linkStillExists)
- return res.status(200).json({
- response: linkStillExists,
- });
- else return res.status(400).json({ response: "Link not found." });
- }
- });
+export default async function Index(req: NextApiRequest, res: NextApiResponse) {
+ const method = req.method;
+
+ try {
+ switch (method) {
+ case "GET":
+ await handleGet(req, res);
+ break;
+ case "POST":
+ await handlePost(req, res);
+ break;
+ default:
+ return res.status(405).json({ response: "Method not allowed" });
+ }
+ } catch (error: any) {
+ return res.status(400).json({ response: error.message });
}
}
diff --git a/prisma/migrations/20250116100419_add_field_to_link_model/migration.sql b/prisma/migrations/20250116100419_add_field_to_link_model/migration.sql
new file mode 100644
index 00000000..6c28e6b0
--- /dev/null
+++ b/prisma/migrations/20250116100419_add_field_to_link_model/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "Link" ADD COLUMN "contentEdited" TIMESTAMP(3);
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 499c28cf..3754eb8f 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -166,6 +166,7 @@ model Link {
pdf String?
readable String?
monolith String?
+ contentEdited DateTime?
aiTagged Boolean @default(false)
lastPreserved DateTime?
importDate DateTime?
diff --git a/types/global.ts b/types/global.ts
index 976551f8..1bb87811 100644
--- a/types/global.ts
+++ b/types/global.ts
@@ -73,12 +73,12 @@ export enum ViewMode {
}
export enum Sort {
- DateNewestFirst,
- DateOldestFirst,
- NameAZ,
- NameZA,
- DescriptionAZ,
- DescriptionZA,
+ DateNewestFirst = 0,
+ DateOldestFirst = 1,
+ NameAZ = 2,
+ NameZA = 3,
+ DescriptionAZ = 4,
+ DescriptionZA = 5,
}
export type Order = { [key: string]: "asc" | "desc" };
@@ -117,15 +117,15 @@ export type MigrationRequest = {
};
export enum MigrationFormat {
- linkwarden,
- htmlFile,
- wallabag,
- omnivore,
+ linkwarden = 0,
+ htmlFile = 1,
+ wallabag = 2,
+ omnivore = 3,
}
export enum Plan {
- monthly,
- yearly,
+ monthly = 0,
+ yearly = 1,
}
export type DeleteUserBody = {
@@ -137,24 +137,24 @@ export type DeleteUserBody = {
};
export enum ArchivedFormat {
- png,
- jpeg,
- pdf,
- readability,
- monolith,
+ png = 0,
+ jpeg = 1,
+ pdf = 2,
+ readability = 3,
+ monolith = 4,
}
export enum LinkType {
- url,
- pdf,
- image,
- monolith,
+ url = 0,
+ pdf = 1,
+ image = 2,
+ monolith = 3,
}
export enum TokenExpiry {
- sevenDays,
- oneMonth,
- twoMonths,
- threeMonths,
- never,
+ sevenDays = 0,
+ oneMonth = 1,
+ twoMonths = 2,
+ threeMonths = 3,
+ never = 4,
}