Skip to content

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

refactored search

daniel31x139bd821baa9ce
diff --git a/.env.sample b/.env.sample
index 6615c791..e0d7a52f 100644
--- a/.env.sample
+++ b/.env.sample
@@ -39,6 +39,8 @@ MAX_WORKERS=
DISABLE_PRESERVATION=
NEXT_PUBLIC_RSS_POLLING_INTERVAL_MINUTES=
RSS_SUBSCRIPTION_LIMIT_PER_USER=
+SLICE_TEXT_CONTENT=
+INDEX_TAKE_COUNT=
# AI Settings
NEXT_PUBLIC_OLLAMA_ENDPOINT_URL=
@@ -52,6 +54,10 @@ OPENAI_MODEL=
ANTHROPIC_API_KEY=
ANTHROPIC_MODEL=
+# MeiliSearch Settings
+MEILISEARCH_HOST=
+MEILISEARCH_KEY=
+
# AWS S3 Settings
SPACES_KEY=
SPACES_SECRET=
diff --git a/.gitignore b/.gitignore
index 21611740..196bc7bc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -54,3 +54,6 @@ certificates
/playwright-report/
/blob-report/
/playwright/.cache/
+
+# meilisearch
+data.ms
\ No newline at end of file
diff --git a/components/LinkViews/LinkComponents/LinkCard.tsx b/components/LinkViews/LinkComponents/LinkCard.tsx
index b5076c37..0170a4fd 100644
--- a/components/LinkViews/LinkComponents/LinkCard.tsx
+++ b/components/LinkViews/LinkComponents/LinkCard.tsx
@@ -66,9 +66,7 @@ export default function LinkCard({ link, columns, editMode }: Props) {
settings: { show },
} = useLocalSettingsStore();
- const {
- data: { data: links = [] },
- } = useLinks();
+ const { links } = useLinks();
const getLink = useGetLink();
useEffect(() => {
diff --git a/hooks/store/links.tsx b/hooks/store/links.tsx
index f4450a62..f6056203 100644
--- a/hooks/store/links.tsx
+++ b/hooks/store/links.tsx
@@ -1,7 +1,5 @@
import {
- InfiniteData,
useInfiniteQuery,
- UseInfiniteQueryResult,
useQueryClient,
useMutation,
} from "@tanstack/react-query";
@@ -23,17 +21,14 @@ const useLinks = (params: LinkRequestQuery = {}) => {
const queryParamsObject = {
sort: params.sort ?? Number(window.localStorage.getItem("sortBy")) ?? 0,
collectionId:
- params.collectionId ?? router.pathname === "/collections/[id]"
- ? router.query.id
- : undefined,
+ params.collectionId ??
+ (router.pathname === "/collections/[id]" ? router.query.id : undefined),
tagId:
- params.tagId ?? router.pathname === "/tags/[id]"
- ? router.query.id
- : undefined,
+ params.tagId ??
+ (router.pathname === "/tags/[id]" ? router.query.id : undefined),
pinnedOnly:
- params.pinnedOnly ?? router.pathname === "/links/pinned"
- ? true
- : undefined,
+ params.pinnedOnly ??
+ (router.pathname === "/links/pinned" ? true : undefined),
searchQueryString: params.searchQueryString,
searchByName: params.searchByName,
searchByUrl: params.searchByUrl,
@@ -47,17 +42,14 @@ const useLinks = (params: LinkRequestQuery = {}) => {
const { data, ...rest } = useFetchLinks(queryString);
const links = useMemo(() => {
- return data?.pages.reduce((acc, page) => {
- return [...acc, ...page];
- }, []);
+ return data?.pages?.flatMap((page) => page?.links ?? []) ?? [];
}, [data]);
+ const memoizedData = useMemo(() => ({ ...data, ...rest }), [data, rest]);
+
return {
links,
- data: { ...data, ...rest },
- } as {
- links: LinkIncludingShortenedCollectionAndTags[];
- data: UseInfiniteQueryResult<InfiniteData<any, unknown>, Error>;
+ data: memoizedData,
};
};
@@ -68,7 +60,7 @@ const useFetchLinks = (params: string) => {
queryKey: ["links", { params }],
queryFn: async (params) => {
const response = await fetch(
- "/api/v1/links?cursor=" +
+ "/api/v1/search?cursor=" +
params.pageParam +
((params.queryKey[1] as any).params
? "&" + (params.queryKey[1] as any).params
@@ -76,15 +68,18 @@ const useFetchLinks = (params: string) => {
);
const data = await response.json();
- return data.response;
+ return {
+ links: data.data.links as LinkIncludingShortenedCollectionAndTags[],
+ nextCursor: data.data.nextCursor as number | null,
+ };
},
initialPageParam: 0,
refetchOnWindowFocus: false,
getNextPageParam: (lastPage) => {
- if (lastPage.length === 0) {
+ if (lastPage.nextCursor === null) {
return undefined;
}
- return lastPage.at(-1).id;
+ return lastPage.nextCursor;
},
enabled: status === "authenticated",
});
@@ -129,7 +124,7 @@ const useAddLink = () => {
return data.response;
},
- onSuccess: (data) => {
+ onSuccess: (data: LinkIncludingShortenedCollectionAndTags[]) => {
queryClient.setQueryData(["dashboardData"], (oldData: any) => {
if (!oldData?.links) return undefined;
return {
@@ -141,7 +136,13 @@ const useAddLink = () => {
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
- pages: [[data, ...oldData?.pages[0]], ...oldData?.pages.slice(1)],
+ pages: [
+ {
+ links: [data, ...oldData?.pages[0].links],
+ nextCursor: oldData?.pages[0].nextCursor,
+ },
+ ...oldData?.pages.slice(1),
+ ],
pageParams: oldData?.pageParams,
};
});
@@ -173,24 +174,8 @@ const useUpdateLink = () => {
return data.response;
},
onSuccess: (data) => {
- // queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- // if (!oldData?.links) return undefined;
- // return oldData.links.map((e: any) => (e.id === data.id ? data : e));
- // });
-
- // queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- // if (!oldData) return undefined;
- // return {
- // pages: oldData.pages.map((page: any) =>
- // page.map((item: any) => (item.id === data.id ? data : item))
- // ),
- // pageParams: oldData.pageParams,
- // };
- // });
-
- queryClient.invalidateQueries({ queryKey: ["links"] }); // Temporary workaround
- queryClient.invalidateQueries({ queryKey: ["dashboardData"] }); // Temporary workaround
-
+ queryClient.invalidateQueries({ queryKey: ["links"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });
queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
@@ -224,10 +209,12 @@ const useDeleteLink = () => {
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
+
return {
- pages: oldData.pages.map((page: any) =>
- page.filter((item: any) => item.id !== data.id)
- ),
+ pages: oldData.pages.map((page: any) => ({
+ links: page.links.filter((item: any) => item.id !== data.id),
+ nextCursor: page.nextCursor,
+ })),
pageParams: oldData.pageParams,
};
});
@@ -275,9 +262,12 @@ const useGetLink = () => {
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
- pages: oldData.pages.map((page: any) =>
- page.map((item: any) => (item.id === data.id ? data : item))
- ),
+ pages: oldData.pages.map((page: any) => ({
+ links: page.links.map((item: any) =>
+ item.id === data.id ? data : item
+ ),
+ nextCursor: page.nextCursor,
+ })),
pageParams: oldData.pageParams,
};
});
@@ -287,15 +277,16 @@ const useGetLink = () => {
(oldData: any) => {
if (!oldData) return undefined;
return {
- pages: oldData.pages.map((page: any) =>
- page.map((item: any) => (item.id === data.id ? data : item))
- ),
+ pages: oldData.pages.map((page: any) => ({
+ links: page.links.map((item: any) =>
+ item.id === data.id ? data : item
+ ),
+ nextCursor: page.nextCursor,
+ })),
pageParams: oldData.pageParams,
};
}
);
-
- // queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
},
});
};
@@ -320,21 +311,18 @@ const useBulkDeleteLinks = () => {
return linkIds;
},
onSuccess: (data) => {
- queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- if (!oldData?.links) return undefined;
- return oldData.links.filter((e: any) => !data.includes(e.id));
- });
-
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
- pages: oldData.pages.map((page: any) =>
- page.filter((item: any) => !data.includes(item.id))
- ),
+ pages: oldData.pages.map((page: any) => ({
+ links: page.links.filter((item: any) => !data.includes(item.id)),
+ nextCursor: page.nextCursor,
+ })),
pageParams: oldData.pageParams,
};
});
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });
queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
@@ -393,7 +381,13 @@ const useUploadFile = () => {
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
- pages: [[data, ...oldData?.pages[0]], ...oldData?.pages.slice(1)],
+ pages: [
+ {
+ links: [data, ...oldData?.pages[0].links],
+ nextCursor: oldData?.pages[0].nextCursor,
+ },
+ ...oldData?.pages.slice(1),
+ ],
pageParams: oldData?.pageParams,
};
});
@@ -443,40 +437,12 @@ const useUpdateFile = () => {
return data;
},
- onSuccess: (data) => {
- queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- if (!oldData?.links) return undefined;
- return {
- ...oldData,
- links: oldData.links.map((e: any) =>
- e.id === data.response.id
- ? {
- ...e,
- preview: `archives/preview/${e.collectionId}/${e.id}.jpeg`,
- updatedAt: new Date().toISOString(),
- }
- : e
- ),
- };
- });
-
- queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- if (!oldData) return undefined;
- return {
- pages: oldData.pages.map((page: any) =>
- page.map((item: any) =>
- item.id === data.response.id
- ? {
- ...item,
- preview: `archives/preview/${item.collectionId}/${item.id}.jpeg`,
- updatedAt: new Date().toISOString(),
- }
- : item
- )
- ),
- pageParams: oldData.pageParams,
- };
- });
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["links"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
+ queryClient.invalidateQueries({ queryKey: ["collections"] });
+ queryClient.invalidateQueries({ queryKey: ["tags"] });
+ queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
},
});
};
@@ -511,27 +477,9 @@ const useBulkEditLinks = () => {
return data.response;
},
- onSuccess: (data, { links, newData, removePreviousTags }) => {
- // TODO: Fix these
- // queryClient.setQueryData(["dashboardData"], (oldData: any) => {
- // if (!oldData?.links) return undefined;
- // return oldData.links.map((e: any) =>
- // data.find((d: any) => d.id === e.id) ? data : e
- // );
- // });
- // queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
- // if (!oldData) return undefined;
- // return {
- // pages: oldData.pages.map((page: any) => for (item of links) {
- // page.map((item: any) => (item.id === data.id ? data : item))
- // }
- // ),
- // pageParams: oldData.pageParams,
- // };
- // });
- queryClient.invalidateQueries({ queryKey: ["links"] }); // Temporary workaround
- queryClient.invalidateQueries({ queryKey: ["dashboardData"] }); // Temporary workaround
-
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["links"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });
queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
diff --git a/lib/api/controllers/dashboard/getDashboardDataV2.ts b/lib/api/controllers/dashboard/getDashboardDataV2.ts
index 791e43bc..89d7aa6c 100644
--- a/lib/api/controllers/dashboard/getDashboardDataV2.ts
+++ b/lib/api/controllers/dashboard/getDashboardDataV2.ts
@@ -18,7 +18,7 @@ export default async function getDashboardData(
query: LinkRequestQuery,
viewRecent: boolean,
viewPinned: boolean
-): Promise<Response<any>> {
+) {
let pinnedTake = 0;
let recentTake = 0;
@@ -68,7 +68,8 @@ export default async function getDashboardData(
numberOfPinnedLinks,
},
message: "Dashboard data fetched successfully.",
- status: 200,
+ statusCode: 200,
+ success: true,
};
}
@@ -152,6 +153,7 @@ export default async function getDashboardData(
numberOfPinnedLinks,
},
message: "Dashboard data fetched successfully.",
- status: 200,
+ statusCode: 200,
+ success: true,
};
}
diff --git a/lib/api/controllers/links/bulk/deleteLinksById.ts b/lib/api/controllers/links/bulk/deleteLinksById.ts
index a9c395b3..d832f545 100644
--- a/lib/api/controllers/links/bulk/deleteLinksById.ts
+++ b/lib/api/controllers/links/bulk/deleteLinksById.ts
@@ -2,6 +2,7 @@ import { prisma } from "@/lib/api/db";
import { UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
import { removeFiles } from "@/lib/api/manageLinkFiles";
+import { meiliClient } from "@/lib/api/meilisearchClient";
export default async function deleteLinksById(
userId: number,
@@ -46,5 +47,7 @@ export default async function deleteLinksById(
if (collectionIsAccessible) removeFiles(linkId, collectionIsAccessible.id);
}
+ meiliClient?.index("links").deleteDocuments(linkIds);
+
return { response: deletedLinks, status: 200 };
}
diff --git a/lib/api/controllers/links/linkId/deleteLinkById.ts b/lib/api/controllers/links/linkId/deleteLinkById.ts
index abff6f0b..5ba48ded 100644
--- a/lib/api/controllers/links/linkId/deleteLinkById.ts
+++ b/lib/api/controllers/links/linkId/deleteLinkById.ts
@@ -2,6 +2,7 @@ import { prisma } from "@/lib/api/db";
import { Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
import { removeFiles } from "@/lib/api/manageLinkFiles";
+import { meiliClient } from "@/lib/api/meilisearchClient";
export default async function deleteLink(userId: number, linkId: number) {
if (!linkId) return { response: "Please choose a valid link.", status: 401 };
@@ -26,5 +27,7 @@ export default async function deleteLink(userId: number, linkId: number) {
removeFiles(linkId, collectionIsAccessible.id);
+ meiliClient?.index("links").deleteDocument(deleteLink.id);
+
return { response: deleteLink, status: 200 };
}
diff --git a/lib/api/controllers/links/linkId/updateLinkById.ts b/lib/api/controllers/links/linkId/updateLinkById.ts
index 0d362169..cab64add 100644
--- a/lib/api/controllers/links/linkId/updateLinkById.ts
+++ b/lib/api/controllers/links/linkId/updateLinkById.ts
@@ -7,6 +7,7 @@ import {
UpdateLinkSchema,
UpdateLinkSchemaType,
} from "@/lib/shared/schemaValidation";
+import { meiliClient } from "@/lib/api/meilisearchClient";
export default async function updateLinkById(
userId: number,
@@ -134,6 +135,7 @@ export default async function updateLinkById(
readable: oldLink?.url !== data.url ? null : undefined,
monolith: oldLink?.url !== data.url ? null : undefined,
preview: oldLink?.url !== data.url ? null : undefined,
+ indexVersion: null,
collection: {
connect: {
id: data.collection.id,
@@ -176,6 +178,8 @@ export default async function updateLinkById(
},
});
+ meiliClient?.index("links").deleteDocument(updatedLink.id);
+
if (collectionIsAccessible?.id !== data.collection.id) {
await moveFiles(linkId, collectionIsAccessible?.id, data.collection.id);
}
diff --git a/lib/api/controllers/search/searchLinks.ts b/lib/api/controllers/search/searchLinks.ts
new file mode 100644
index 00000000..295309cf
--- /dev/null
+++ b/lib/api/controllers/search/searchLinks.ts
@@ -0,0 +1,258 @@
+import { prisma } from "@/lib/api/db";
+import { LinkRequestQuery, Order, Sort } from "@/types/global";
+import { meiliClient } from "../../meilisearchClient";
+import {
+ buildMeiliFilters,
+ buildMeiliQuery,
+ parseSearchTokens,
+} from "../../searchQueryBuilder";
+
+export default async function searchLinks(
+ userId: number,
+ query: LinkRequestQuery
+) {
+ const POSTGRES_IS_ENABLED =
+ process.env.DATABASE_URL?.startsWith("postgresql");
+
+ const paginationTakeCount = Number(process.env.PAGINATION_TAKE_COUNT) || 50;
+
+ let order: Order = { id: "desc" };
+ if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };
+ else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };
+ else if (query.sort === Sort.NameAZ) order = { name: "asc" };
+ else if (query.sort === Sort.NameZA) order = { name: "desc" };
+ else if (query.sort === Sort.DescriptionAZ) order = { description: "asc" };
+ else if (query.sort === Sort.DescriptionZA) order = { description: "desc" };
+
+ const tagCondition = [];
+ if (query.tagId) {
+ tagCondition.push({
+ tags: {
+ some: { id: query.tagId },
+ },
+ });
+ }
+
+ const collectionCondition = [];
+ if (query.collectionId) {
+ collectionCondition.push({
+ collection: { id: query.collectionId },
+ });
+ }
+
+ const pinnedCondition = query.pinnedOnly
+ ? { pinnedBy: { some: { id: userId } } }
+ : {};
+
+ if (meiliClient && query.searchQueryString) {
+ const tokens = parseSearchTokens(query.searchQueryString);
+ const meiliQuery = buildMeiliQuery(tokens);
+
+ const meiliFilters = buildMeiliFilters(tokens, userId);
+
+ const limit = paginationTakeCount;
+ const offset = query.cursor || 0;
+
+ const meiliResp = await meiliClient.index("links").search(meiliQuery, {
+ filter: meiliFilters,
+ attributesToRetrieve: ["id"],
+ limit,
+ offset,
+ sort:
+ query.sort === Sort.DateNewestFirst
+ ? ["id:desc"]
+ : query.sort === Sort.DateOldestFirst
+ ? ["id:asc"]
+ : query.sort === Sort.NameAZ
+ ? ["name:asc"]
+ : query.sort === Sort.NameZA
+ ? ["name:desc"]
+ : ["id:desc"],
+ });
+
+ if (meiliResp.hits.length === 0) {
+ return {
+ data: [],
+ statusCode: 200,
+ success: true,
+ message: "Nothing found.",
+ };
+ }
+
+ const meiliIds = meiliResp.hits.map((h: any) => h.id);
+
+ const links = await prisma.link.findMany({
+ where: {
+ id: { in: meiliIds },
+ AND: [
+ {
+ collection: {
+ OR: [
+ { ownerId: userId },
+ {
+ members: {
+ some: { userId },
+ },
+ },
+ ],
+ },
+ },
+ ...collectionCondition,
+ {
+ OR: [
+ ...tagCondition,
+ {
+ ...pinnedCondition,
+ },
+ ],
+ },
+ ],
+ },
+ include: {
+ tags: true,
+ collection: true,
+ pinnedBy: {
+ where: { id: userId },
+ select: { id: true },
+ },
+ },
+ orderBy: order,
+ });
+
+ const nextCursor = meiliResp.hits.length === limit ? offset + limit : null;
+
+ return {
+ data: {
+ links,
+ nextCursor,
+ },
+ statusCode: 200,
+ success: true,
+ message: "Success",
+ };
+ }
+
+ // Fallback: No Meilisearch
+ const searchConditions = [];
+
+ if (query.searchQueryString) {
+ if (query.searchByName) {
+ searchConditions.push({
+ name: {
+ contains: query.searchQueryString,
+ mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
+ },
+ });
+ }
+
+ if (query.searchByUrl) {
+ searchConditions.push({
+ url: {
+ contains: query.searchQueryString,
+ mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
+ },
+ });
+ }
+
+ if (query.searchByDescription) {
+ searchConditions.push({
+ description: {
+ contains: query.searchQueryString,
+ mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
+ },
+ });
+ }
+
+ if (query.searchByTextContent) {
+ searchConditions.push({
+ textContent: {
+ contains: query.searchQueryString,
+ mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
+ },
+ });
+ }
+
+ if (query.searchByTags) {
+ searchConditions.push({
+ tags: {
+ some: {
+ name: {
+ contains: query.searchQueryString,
+ mode: POSTGRES_IS_ENABLED ? "insensitive" : undefined,
+ },
+ OR: [
+ { ownerId: userId },
+ {
+ links: {
+ some: {
+ collection: {
+ members: {
+ some: { userId },
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+ },
+ });
+ }
+ }
+
+ const links = await prisma.link.findMany({
+ take: paginationTakeCount,
+ skip: query.cursor ? 1 : undefined,
+ cursor: query.cursor ? { id: query.cursor } : undefined,
+ where: {
+ AND: [
+ {
+ collection: {
+ OR: [
+ { ownerId: userId },
+ {
+ members: {
+ some: { userId },
+ },
+ },
+ ],
+ },
+ },
+ ...collectionCondition,
+ {
+ OR: [
+ ...tagCondition,
+ {
+ [query.searchQueryString ? "OR" : "AND"]: [
+ pinnedCondition,
+ ...searchConditions,
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ include: {
+ tags: true,
+ collection: true,
+ pinnedBy: {
+ where: { id: userId },
+ select: { id: true },
+ },
+ },
+ orderBy: order,
+ });
+
+ return {
+ data: {
+ links,
+ nextCursor:
+ links.length === paginationTakeCount
+ ? links[links.length - 1].id
+ : null,
+ },
+ statusCode: 200,
+ success: true,
+ message: "Success",
+ };
+}
diff --git a/lib/api/getLinkBatch.ts b/lib/api/getLinkBatch.ts
new file mode 100644
index 00000000..109d0410
--- /dev/null
+++ b/lib/api/getLinkBatch.ts
@@ -0,0 +1,39 @@
+import { PrismaClient, Prisma, Link } from "@prisma/client";
+
+const prisma = new PrismaClient();
+
+/**
+ * Fetches the first and last X links from the database based on the provided conditions.
+ * @param prisma - Prisma client instance
+ * @param params - Prisma query parameters (optional)
+ * @returns A list of links
+ */
+const getLinkBatch = async <T extends Prisma.LinkFindManyArgs>(
+ params: T
+): Promise<Array<Prisma.LinkGetPayload<T>>> => {
+ const { where = {}, take = 10, orderBy, include } = params;
+
+ const oldToNew = await prisma.link.findMany({
+ where,
+ take,
+ orderBy: orderBy ?? { id: "asc" },
+ include,
+ });
+
+ const newToOld = await prisma.link.findMany({
+ where,
+ take,
+ orderBy: orderBy ?? { id: "desc" },
+ include,
+ });
+
+ const links = [...oldToNew, ...newToOld]
+ // Make sure we don't process the same link twice
+ .filter((value, index, self) => {
+ return self.findIndex((item) => item.id === value.id) === index;
+ });
+
+ return links as Array<Prisma.LinkGetPayload<T>>;
+};
+
+export default getLinkBatch;
diff --git a/lib/api/meilisearchClient.ts b/lib/api/meilisearchClient.ts
new file mode 100644
index 00000000..c8f1316f
--- /dev/null
+++ b/lib/api/meilisearchClient.ts
@@ -0,0 +1,10 @@
+import { MeiliSearch } from "meilisearch";
+
+const host = process.env.MEILISEARCH_HOST;
+
+export const meiliClient = host
+ ? new MeiliSearch({
+ host,
+ apiKey: process.env.MEILISEARCH_KEY,
+ })
+ : null;
diff --git a/lib/api/preservationScheme/handleReadability.ts b/lib/api/preservationScheme/handleReadability.ts
index 01e5830f..5d3eca73 100644
--- a/lib/api/preservationScheme/handleReadability.ts
+++ b/lib/api/preservationScheme/handleReadability.ts
@@ -19,7 +19,7 @@ const handleReadablility = async (
const articleText = article?.textContent
.replace(/ +(?= )/g, "") // strip out multiple spaces
.replace(/(\r\n|\n|\r)/gm, " ") // strip out line breaks
- .slice(0, 2047);
+ .slice(0, process.env.SLICE_TEXT_CONTENT === "true" ? 10000 : undefined); // limit to 10,000 characters if SLICE_TEXT_CONTENT is true
if (articleText && articleText !== "") {
const collectionId = (
diff --git a/lib/api/searchQueryBuilder.ts b/lib/api/searchQueryBuilder.ts
new file mode 100644
index 00000000..2f1f003e
--- /dev/null
+++ b/lib/api/searchQueryBuilder.ts
@@ -0,0 +1,93 @@
+interface Token {
+ field: string;
+ value: string;
+}
+
+export function parseSearchTokens(searchQueryString: string): Token[] {
+ // Split on whitespace
+ const rawTokens = searchQueryString.match(/\S+/g) || [];
+ const tokens: Token[] = [];
+
+ for (const token of rawTokens) {
+ if (token.startsWith("url:")) {
+ tokens.push({ field: "url", value: token.substring("url:".length) });
+ } else if (token.startsWith("name:")) {
+ tokens.push({ field: "name", value: token.substring("name:".length) });
+ } else if (token.startsWith("description:")) {
+ tokens.push({
+ field: "description",
+ value: token.substring("description:".length),
+ });
+ } else if (token.startsWith("collection:")) {
+ tokens.push({
+ field: "collection",
+ value: token.substring("collection:".length),
+ });
+ } else if (token.startsWith("pinned:")) {
+ tokens.push({
+ field: "pinned",
+ value: token.substring("pinned:".length).toLowerCase(),
+ });
+ } else if (token.startsWith("#")) {
+ tokens.push({ field: "tag", value: token.substring(1) });
+ } else {
+ // everything else -> 'general' text
+ tokens.push({ field: "general", value: token });
+ }
+ }
+
+ return tokens;
+}
+
+export function buildMeiliQuery(tokens: Token[]): string {
+ const generalValues = tokens
+ .filter((t) => t.field === "general")
+ .map((t) => t.value);
+
+ return generalValues.join(" ");
+}
+
+export function buildMeiliFilters(tokens: Token[], userId: number): string[] {
+ const filters: string[] = [
+ `(collectionOwnerId = ${userId}) OR (collectionMemberIds = ${userId})`,
+ ];
+
+ for (const { field, value } of tokens) {
+ switch (field) {
+ // case "url":
+ // filters.push(`url = "${escapeForMeilisearch(value)}"`);
+ // break;
+ // case "name":
+ // filters.push(`name = "${escapeForMeilisearch(value)}"`);
+ // break;
+ // case "description":
+ // filters.push(`description = "${escapeForMeilisearch(value)}"`);
+ // break;
+
+ // case "collection":
+ // filters.push(`collectionName = "${escapeForMeilisearch(value)}"`);
+ // break;
+
+ // case "pinned":
+ // if (value === "true") {
+ // filters.push("pinnedBy = ${userId}");
+ // } else if (value === "false") {
+ // filters.push("pinned = false");
+ // }
+ // break;
+
+ // case "tag":
+ // filters.push(`tags = "${escapeForMeilisearch(value)}"`);
+ // break;
+
+ case "general":
+ default:
+ break;
+ }
+ }
+ return filters;
+}
+
+export function escapeForMeilisearch(value: string): string {
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
+}
diff --git a/pages/api/v1/archives/[linkId].ts b/pages/api/v1/archives/[linkId].ts
index 34b1e9e7..a8e054db 100644
--- a/pages/api/v1/archives/[linkId].ts
+++ b/pages/api/v1/archives/[linkId].ts
@@ -292,7 +292,6 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
? `archives/${collectionPermissions.id}/${linkId + suffix}`
: undefined,
contentEdited: isReadable ? new Date().toISOString() : undefined,
- lastPreserved: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
});
diff --git a/pages/api/v1/search/index.ts b/pages/api/v1/search/index.ts
new file mode 100644
index 00000000..dde0bad0
--- /dev/null
+++ b/pages/api/v1/search/index.ts
@@ -0,0 +1,41 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import searchLinks from "@/lib/api/controllers/search/searchLinks";
+import { LinkRequestQuery } from "@/types/global";
+import verifyUser from "@/lib/api/verifyUser";
+
+export default async function search(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ const user = await verifyUser({ req, res });
+ if (!user) return;
+
+ if (req.method === "GET") {
+ // Convert the type of the request query to "LinkRequestQuery"
+ const convertedData: LinkRequestQuery = {
+ sort: Number(req.query.sort as string),
+ cursor: req.query.cursor ? Number(req.query.cursor as string) : undefined,
+ collectionId: req.query.collectionId
+ ? Number(req.query.collectionId as string)
+ : undefined,
+ tagId: req.query.tagId ? Number(req.query.tagId as string) : undefined,
+ pinnedOnly: req.query.pinnedOnly
+ ? req.query.pinnedOnly === "true"
+ : undefined,
+ searchQueryString: req.query.searchQueryString
+ ? (req.query.searchQueryString as string)
+ : undefined,
+ searchByName: req.query.searchByName === "true" ? true : undefined,
+ searchByUrl: req.query.searchByUrl === "true" ? true : undefined,
+ searchByDescription:
+ req.query.searchByDescription === "true" ? true : undefined,
+ searchByTextContent:
+ req.query.searchByTextContent === "true" ? true : undefined,
+ searchByTags: req.query.searchByTags === "true" ? true : undefined,
+ };
+
+ const { statusCode, ...data } = await searchLinks(user.id, convertedData);
+
+ return res.status(statusCode).json(data);
+ }
+}
diff --git a/pages/api/v2/dashboard/index.ts b/pages/api/v2/dashboard/index.ts
index 0cd5cd29..66b56746 100644
--- a/pages/api/v2/dashboard/index.ts
+++ b/pages/api/v2/dashboard/index.ts
@@ -16,18 +16,13 @@ export default async function dashboard(
cursor: req.query.cursor ? Number(req.query.cursor as string) : undefined,
};
- const data = await getDashboardDataV2(
+ const { statusCode, ...data } = await getDashboardDataV2(
user.id,
convertedData,
user.dashboardRecentLinks,
user.dashboardPinnedLinks
);
- return res.status(data.status).json({
- data: {
- links: data.data.links,
- numberOfPinnedLinks: data.data.numberOfPinnedLinks,
- },
- message: data.message,
- });
+
+ return res.status(statusCode).json(data);
}
}
diff --git a/pages/dashboard.tsx b/pages/dashboard.tsx
index f1ac53fa..8ac6800c 100644
--- a/pages/dashboard.tsx
+++ b/pages/dashboard.tsx
@@ -75,7 +75,7 @@ export default function Dashboard() {
} else {
return 100;
}
- }, []);
+ }, [account.dashboardRecentLinks, account.dashboardPinnedLinks]);
const [newLinkModal, setNewLinkModal] = useState(false);
diff --git a/prisma/migrations/20250211134725_add_field_to_links/migration.sql b/prisma/migrations/20250211134725_add_field_to_links/migration.sql
new file mode 100644
index 00000000..237ff41c
--- /dev/null
+++ b/prisma/migrations/20250211134725_add_field_to_links/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "Link" ADD COLUMN "indexed" BOOLEAN NOT NULL DEFAULT false;
diff --git a/prisma/migrations/20250215181757_add_version_to_index/migration.sql b/prisma/migrations/20250215181757_add_version_to_index/migration.sql
new file mode 100644
index 00000000..20a37fda
--- /dev/null
+++ b/prisma/migrations/20250215181757_add_version_to_index/migration.sql
@@ -0,0 +1,9 @@
+/*
+ Warnings:
+
+ - You are about to drop the column `indexed` on the `Link` table. All the data in the column will be lost.
+
+*/
+-- AlterTable
+ALTER TABLE "Link" DROP COLUMN "indexed",
+ADD COLUMN "indexVersion" TEXT;
diff --git a/prisma/migrations/20250215182023_change_field_type/migration.sql b/prisma/migrations/20250215182023_change_field_type/migration.sql
new file mode 100644
index 00000000..e0081b9c
--- /dev/null
+++ b/prisma/migrations/20250215182023_change_field_type/migration.sql
@@ -0,0 +1,9 @@
+/*
+ Warnings:
+
+ - The `indexVersion` column on the `Link` table would be dropped and recreated. This will lead to data loss if there is data in the column.
+
+*/
+-- AlterTable
+ALTER TABLE "Link" DROP COLUMN "indexVersion",
+ADD COLUMN "indexVersion" INTEGER;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 5e120181..a584592d 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -171,6 +171,7 @@ model Link {
monolith String?
contentEdited DateTime?
aiTagged Boolean @default(false)
+ indexVersion Int?
lastPreserved DateTime?
importDate DateTime?
createdAt DateTime @default(now())
diff --git a/scripts/worker.ts b/scripts/worker.ts
index 403d1542..cdc4d161 100644
--- a/scripts/worker.ts
+++ b/scripts/worker.ts
@@ -4,227 +4,281 @@ import archiveHandler from "../lib/api/archiveHandler";
import Parser from "rss-parser";
import { hasPassedLimit } from "../lib/api/verifyCapacity";
import { LinkWithCollectionOwnerAndTags } from "../types/global";
+import getLinkBatch from "../lib/api/getLinkBatch";
+import { meiliClient } from "../lib/api/meilisearchClient";
const archiveTakeCount = Number(process.env.ARCHIVE_TAKE_COUNT || "") || 5;
+const indexTakeCount = Number(process.env.INDEX_TAKE_COUNT || "") || 50;
-async function processBatch() {
- const linksOldToNew = await prisma.link.findMany({
- where: {
- url: { not: null },
- OR: [
- {
- image: null,
- },
- {
- pdf: null,
- },
- {
- readable: null,
- },
- {
- monolith: null,
- },
- {
- createdBy: {
- aiTagExistingLinks: true,
- NOT: {
- aiTaggingMethod: "DISABLED",
- },
- },
- aiTagged: false,
- },
- ],
- },
- take: archiveTakeCount,
- orderBy: { id: "asc" },
- include: {
- collection: {
- include: {
- owner: true,
- },
- },
- tags: true,
- },
- });
-
- const linksNewToOld = await prisma.link.findMany({
- where: {
- url: { not: null },
- OR: [
- {
- image: null,
- },
- {
- pdf: null,
- },
- {
- readable: null,
- },
- {
- monolith: null,
- },
- {
- createdBy: {
- aiTagExistingLinks: true,
- NOT: {
- aiTaggingMethod: "DISABLED",
- },
- },
- aiTagged: false,
- },
- ],
- },
- take: archiveTakeCount,
- orderBy: { id: "desc" },
- include: {
- collection: {
- include: {
- owner: true,
- },
- },
- tags: true,
- },
- });
-
- const archiveLink = async (link: LinkWithCollectionOwnerAndTags) => {
- try {
- console.log(
- "\x1b[34m%s\x1b[0m",
- `Processing link ${link.url} for user ${link.collection.ownerId}`
- );
-
- await archiveHandler(link);
-
- console.log(
- "\x1b[34m%s\x1b[0m",
- `Succeeded processing link ${link.url} for user ${link.collection.ownerId}.`
- );
- } catch (error) {
- console.error(
- "\x1b[34m%s\x1b[0m",
- `Error processing link ${link.url} for user ${link.collection.ownerId}:`,
- error
- );
- }
- };
-
- // Process each link in the batch concurrently
- const processingPromises = [...linksOldToNew, ...linksNewToOld]
- // Make sure we don't process the same link twice
- .filter((value, index, self) => {
- return self.findIndex((item) => item.id === value.id) === index;
- })
- .map((e) => archiveLink(e));
-
- await Promise.allSettled(processingPromises);
+function delay(sec: number) {
+ return new Promise((resolve) => setTimeout(resolve, sec * 1000));
}
-async function fetchAndProcessRSS() {
- const rssSubscriptions = await prisma.rssSubscription.findMany({});
- const parser = new Parser();
-
- await Promise.all(
- rssSubscriptions.map(async (rssSubscription) => {
- try {
- const feed = await parser.parseURL(rssSubscription.url);
-
- if (
- rssSubscription.lastBuildDate &&
- new Date(rssSubscription.lastBuildDate) < new Date(feed.lastBuildDate)
- ) {
- console.log(
- "\x1b[34m%s\x1b[0m",
- `Processing new RSS feed items for ${rssSubscription.name}`
- );
+const pollingIntervalInSeconds =
+ (Number(process.env.NEXT_PUBLIC_RSS_POLLING_INTERVAL_MINUTES) || 60) * 60; // Default to one hour if not set
- const newItems = feed.items.filter((item) => {
- const itemPubDate = item.pubDate ? new Date(item.pubDate) : null;
- return itemPubDate && itemPubDate > rssSubscription.lastBuildDate!;
- });
+async function startRSSPolling() {
+ console.log("\x1b[34m%s\x1b[0m", "Starting RSS polling...");
+ while (true) {
+ const rssSubscriptions = await prisma.rssSubscription.findMany({});
+ const parser = new Parser();
- const hasTooManyLinks = await hasPassedLimit(
- rssSubscription.ownerId,
- newItems.length
- );
+ await Promise.all(
+ rssSubscriptions.map(async (rssSubscription) => {
+ try {
+ const feed = await parser.parseURL(rssSubscription.url);
- if (hasTooManyLinks) {
+ if (
+ rssSubscription.lastBuildDate &&
+ new Date(rssSubscription.lastBuildDate) <
+ new Date(feed.lastBuildDate)
+ ) {
console.log(
"\x1b[34m%s\x1b[0m",
- `User ${rssSubscription.ownerId} has too many links. Skipping new RSS feed items.`
+ `Processing new RSS feed items for ${rssSubscription.name}`
);
- return;
- }
- // Create all links concurrently
- await Promise.all(
- newItems.map(async (item) => {
- return prisma.link.create({
- data: {
- name: item.title,
- url: item.link,
- type: "link",
- createdBy: {
- connect: {
- id: rssSubscription.ownerId,
+ const newItems = feed.items.filter((item) => {
+ const itemPubDate = item.pubDate ? new Date(item.pubDate) : null;
+ return (
+ itemPubDate && itemPubDate > rssSubscription.lastBuildDate!
+ );
+ });
+
+ const hasTooManyLinks = await hasPassedLimit(
+ rssSubscription.ownerId,
+ newItems.length
+ );
+
+ if (hasTooManyLinks) {
+ console.log(
+ "\x1b[34m%s\x1b[0m",
+ `User ${rssSubscription.ownerId} has too many links. Skipping new RSS feed items.`
+ );
+ return;
+ }
+
+ // Create all links concurrently
+ await Promise.all(
+ newItems.map(async (item) => {
+ return prisma.link.create({
+ data: {
+ name: item.title,
+ url: item.link,
+ type: "link",
+ createdBy: {
+ connect: {
+ id: rssSubscription.ownerId,
+ },
},
- },
- collection: {
- connect: {
- id: rssSubscription.collectionId,
+ collection: {
+ connect: {
+ id: rssSubscription.collectionId,
+ },
},
},
- },
- });
- })
- );
+ });
+ })
+ );
- // Update the lastBuildDate in the database
- await prisma.rssSubscription.update({
- where: { id: rssSubscription.id },
- data: { lastBuildDate: new Date(feed.lastBuildDate) },
- });
+ // Update the lastBuildDate in the database
+ await prisma.rssSubscription.update({
+ where: { id: rssSubscription.id },
+ data: { lastBuildDate: new Date(feed.lastBuildDate) },
+ });
+ }
+ } catch (error) {
+ console.error(
+ "\x1b[34m%s\x1b[0m",
+ `Error processing RSS feed ${rssSubscription.url}:`,
+ error
+ );
}
+ })
+ );
+ await delay(pollingIntervalInSeconds);
+ }
+}
+
+const archiveIntervalInSeconds =
+ Number(process.env.ARCHIVE_SCRIPT_INTERVAL) || 10;
+
+async function startArchiveProcessing() {
+ console.log("\x1b[34m%s\x1b[0m", "Starting link preservation...");
+ while (true) {
+ const links = await getLinkBatch({
+ where: {
+ url: { not: null },
+ OR: [
+ {
+ image: null,
+ },
+ {
+ pdf: null,
+ },
+ {
+ readable: null,
+ },
+ {
+ monolith: null,
+ },
+ {
+ createdBy: {
+ aiTagExistingLinks: true,
+ NOT: {
+ aiTaggingMethod: "DISABLED",
+ },
+ },
+ aiTagged: false,
+ },
+ ],
+ },
+ take: archiveTakeCount,
+ include: {
+ collection: {
+ include: {
+ owner: true,
+ },
+ },
+ tags: true,
+ },
+ });
+
+ const archiveLink = async (link: LinkWithCollectionOwnerAndTags) => {
+ try {
+ console.log(
+ "\x1b[34m%s\x1b[0m",
+ `Processing link ${link.url} for user ${link.collection.ownerId}`
+ );
+
+ await archiveHandler(link);
+
+ console.log(
+ "\x1b[34m%s\x1b[0m",
+ `Succeeded processing link ${link.url} for user ${link.collection.ownerId}.`
+ );
} catch (error) {
console.error(
"\x1b[34m%s\x1b[0m",
- `Error processing RSS feed ${rssSubscription.url}:`,
+ `Error processing link ${link.url} for user ${link.collection.ownerId}:`,
error
);
}
- })
- );
-}
+ };
-function delay(sec: number) {
- return new Promise((resolve) => setTimeout(resolve, sec * 1000));
+ // Process each link in the batch concurrently
+ const processingPromises = links.map((e) => archiveLink(e));
+
+ await Promise.allSettled(processingPromises);
+ await delay(archiveIntervalInSeconds);
+ }
}
-const pollingIntervalInSeconds =
- (Number(process.env.NEXT_PUBLIC_RSS_POLLING_INTERVAL_MINUTES) || 60) * 60; // Default to one hour if not set
+async function setupLinksIndexSchema() {
+ if (!meiliClient) return;
-async function startRSSPolling() {
- console.log("\x1b[34m%s\x1b[0m", "Starting RSS polling...");
- while (true) {
- await fetchAndProcessRSS();
- await delay(pollingIntervalInSeconds);
+ let linksIndexExists = true;
+ try {
+ await meiliClient.getIndex("links");
+ } catch (err) {
+ linksIndexExists = false;
+ }
+
+ if (!linksIndexExists) {
+ await meiliClient.createIndex("links", { primaryKey: "id" });
}
+
+ const updateFilterableAttributes = await meiliClient
+ .index("links")
+ .updateFilterableAttributes([
+ "collectionOwnerId",
+ "collectionMemberIds",
+ // "collectionName",
+ // "tagNames",
+ ]);
+ await meiliClient
+ .index("links")
+ .waitForTask(updateFilterableAttributes.taskUid);
+
+ const updateSortableAttributes = await meiliClient
+ .index("links")
+ .updateSortableAttributes(["id", "name"]);
+
+ await meiliClient
+ .index("links")
+ .waitForTask(updateSortableAttributes.taskUid);
}
-const archiveIntervalInSeconds =
- Number(process.env.ARCHIVE_SCRIPT_INTERVAL) || 10;
+export async function startIndexing() {
+ if (!meiliClient) return;
+
+ await setupLinksIndexSchema();
+
+ console.log("\x1b[34m%s\x1b[0m", "Starting link indexing...");
-async function startArchiveProcessing() {
- console.log("\x1b[34m%s\x1b[0m", "Starting link preservation...");
while (true) {
- await processBatch();
+ const links = await getLinkBatch({
+ where: {
+ indexVersion: null,
+ lastPreserved: { not: null },
+ },
+ take: indexTakeCount,
+ include: {
+ collection: {
+ include: {
+ owner: true,
+ members: {
+ select: { userId: true },
+ },
+ },
+ },
+ tags: {
+ select: { name: true },
+ },
+ pinnedBy: {
+ select: { id: true },
+ },
+ },
+ });
+
+ if (links.length === 0) {
+ await delay(archiveIntervalInSeconds);
+ continue;
+ }
+
+ const docs = links.map((link) => ({
+ ...link,
+ id: 1,
+ collectionOwnerId: link.collection.ownerId,
+ collectionMemberIds: link.collection.members.map((m) => m.userId),
+ collectionName: link.collection.name,
+ tags: link.tags.map((t) => t.name),
+ pinnedBy: link.pinnedBy.map((p) => p.id),
+ }));
+
+ const task = await meiliClient.index("links").addDocuments(docs);
+ await meiliClient.index("links").waitForTask(task.taskUid);
+
+ const ids = links.map((l) => l.id);
+ await prisma.link.updateMany({
+ where: { id: { in: ids } },
+ data: { indexVersion: 1 },
+ });
+
+ console.log(
+ "\x1b[34m%s\x1b[0m",
+ `Indexed ${links.length} link${links.length === 1 ? "" : "s"}.`
+ );
+
await delay(archiveIntervalInSeconds);
}
}
async function init() {
- console.log("\x1b[34m%s\x1b[0m", "Initializing application...");
+ console.log("\x1b[34m%s\x1b[0m", "Initializing the worker...");
startRSSPolling();
startArchiveProcessing();
+ startIndexing();
}
init();
diff --git a/types/global.ts b/types/global.ts
index f3c07e2f..1439c4dc 100644
--- a/types/global.ts
+++ b/types/global.ts
@@ -164,3 +164,9 @@ export enum TokenExpiry {
threeMonths = 3,
never = 4,
}
+
+export type ResponseObject<T = any> = {
+ success: boolean;
+ message: string;
+ data: T;
+};