⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
improved mobile app + fixed a bug in the worker script
daniel31x13bbeba7f50fbf
diff --git a/apps/mobile/app/(tabs)/_layout.tsx b/apps/mobile/app/(tabs)/_layout.tsxindex 79ee2de1..c4c029fc 100644--- a/apps/mobile/app/(tabs)/_layout.tsx+++ b/apps/mobile/app/(tabs)/_layout.tsx@@ -4,7 +4,7 @@ import { Platform, TouchableOpacity, useColorScheme } from "react-native";import HapticTab from "@/components/HapticTab";import { IconSymbol } from "@/components/ui/IconSymbol";import * as DropdownMenu from "zeego/dropdown-menu";-import "react-native-reanimated";+// import "react-native-reanimated";import TabBarBackground from "@/components/ui/TabBarBackground";export default function TabLayout() {@@ -13,28 +13,25 @@ export default function TabLayout() {return (<TabsscreenOptions={{+ tabBarBackground: TabBarBackground,tabBarActiveTintColor: colorScheme === "dark" ? "white" : "black",tabBarButton: HapticTab,// headerShown: false,- tabBarBackground: TabBarBackground,tabBarStyle: Platform.select({ios: {position: "absolute",},default: {},}),- headerLeftContainerStyle: {- paddingLeft: 20, // Padding for left content- },- headerRightContainerStyle: {- paddingRight: 20, // Padding for right content- },}}><Tabs.Screen- name="index"+ name="dashboard"options={{title: "Dashboard",+ headerRightContainerStyle: {+ paddingRight: 20,+ },headerRight: ({ tintColor }) => (<DropdownMenu.Root><DropdownMenu.Trigger>@@ -76,6 +73,9 @@ export default function TabLayout() {name="links"options={{title: "Links",+ headerSearchBarOptions: {+ placeholder: "Search",+ },tabBarIcon: ({ color }) => (<IconSymbol size={28} name="link" color={color} />),diff --git a/apps/mobile/app/(tabs)/index.tsx b/apps/mobile/app/(tabs)/dashboard.tsxsimilarity index 100%rename from apps/mobile/app/(tabs)/index.tsxrename to apps/mobile/app/(tabs)/dashboard.tsxdiff --git a/apps/mobile/app/(tabs)/links.tsx b/apps/mobile/app/(tabs)/links.tsxindex 2f3a4b0b..e3be37dd 100644--- a/apps/mobile/app/(tabs)/links.tsx+++ b/apps/mobile/app/(tabs)/links.tsx@@ -2,11 +2,10 @@ import { useLinks } from "@linkwarden/router/links";import {View,StyleSheet,- Text,ActivityIndicator,FlatList,+ Platform,} from "react-native";-import { Platform } from "react-native";import useAuthStore from "@/store/auth";import LinkListing from "@/components/LinkListing";@@ -22,6 +21,7 @@ export default function HomeScreen() {return (<View><FlatList+ ListHeaderComponent={() => <></>}data={links || []}onRefresh={() => data.refetch()}refreshing={data.isRefetching}diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex 15048ed2..8cc52137 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -18,7 +18,16 @@ export default function RootLayout() {gestureEnabled: false,}}>- <Stack.Screen name="(tabs)" />+ {/* <Stack.Screen name="(tabs)" /> */}+ <Stack.Screen+ name="links/[id]"+ options={{+ headerBackTitle: "Back",+ headerShown: true,+ gestureEnabled: true,+ headerTitle: "",+ }}+ /><Stack.Screen name="login" /><Stack.Screen name="+not-found" /></Stack>diff --git a/apps/mobile/app/index.tsx b/apps/mobile/app/index.tsxindex 0c08cd06..7613f885 100644--- a/apps/mobile/app/index.tsx+++ b/apps/mobile/app/index.tsx@@ -11,7 +11,7 @@ export default function HomeScreen() {}, []);if (auth.session) {- return <Redirect href="/(tabs)" />;+ return <Redirect href="/dashboard" />;} else {return <Redirect href="/login" />;}diff --git a/apps/mobile/app/links/[id].tsx b/apps/mobile/app/links/[id].tsxnew file mode 100644index 00000000..7b5572ea--- /dev/null+++ b/apps/mobile/app/links/[id].tsx@@ -0,0 +1,89 @@+import {+ View,+ StyleSheet,+ ActivityIndicator,+ Text,+ // Platform,+} from "react-native";+import { WebView } from "react-native-webview";+import useAuthStore from "@/store/auth";+import { useLocalSearchParams } from "expo-router";+import { useGetLink } from "@linkwarden/router/links";+import { useUser } from "@linkwarden/router/user";+import { useEffect, useState } from "react";+// import { generateLinkHref } from "@linkwarden/lib/generateLinkHref";++export default function HomeScreen() {+ const { auth } = useAuthStore();+ const { id } = useLocalSearchParams();+ const getLink = useGetLink(false, auth);+ const { data: user } = useUser(auth);+ const [url, setUrl] = useState<string>();+ const [isLoading, setIsLoading] = useState(true);++ useEffect(() => {+ async function fetchLinkData() {+ const link = await getLink.mutateAsync({ id: Number(id) });+ if (link && link.url) {+ setUrl(link.url);+ }+ }++ if (user[0]?.id && !url) {+ fetchLinkData();+ }+ }, [user, url]);++ return (+ <View style={styles.container}>+ {url && (+ <WebView+ style={{+ ...(isLoading+ ? {+ opacity: 0,+ }+ : {+ flex: 1,+ }),+ }}+ source={{ uri: url }}+ onLoadEnd={() => setIsLoading(false)}+ />+ )}+ {isLoading && (+ <View+ style={{+ flex: 1,+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ justifyContent: "center",+ alignItems: "center",+ backgroundColor: "#fff",+ padding: 20,+ }}+ >+ <ActivityIndicator size="large" color="gray" />+ <Text+ style={{+ fontSize: 16,+ marginTop: 10,+ color: "gray",+ }}+ >+ Loading...+ </Text>+ </View>+ )}+ </View>+ );+}++const styles = StyleSheet.create({+ container: {+ flex: 1,+ },+});diff --git a/apps/mobile/components/LinkListing.tsx b/apps/mobile/components/LinkListing.tsxindex 5f140a95..52d4d922 100644--- a/apps/mobile/components/LinkListing.tsx+++ b/apps/mobile/components/LinkListing.tsx@@ -5,6 +5,7 @@ import { IconSymbol } from "@/components/ui/IconSymbol";import { ArchivedFormat } from "@linkwarden/types";import { formatAvailable } from "@linkwarden/lib/formatStats";import useAuthStore from "@/store/auth";+import { Link } from "expo-router";type Props = {link: LinkIncludingShortenedCollectionAndTags;@@ -24,138 +25,144 @@ const LinkListing = ({ link }: Props) => {}return (- <View- style={{- padding: 20,- flexDirection: "row",- justifyContent: "space-between",- }}- >+ <Link href={`/links/${link.id}`}><Viewstyle={{- width: "70%",- flexDirection: "column",+ padding: 20,+ flexDirection: "row",justifyContent: "space-between",}}>- <Text+ <Viewstyle={{- fontWeight: "500",- fontSize: 18,+ width: "70%",+ flexDirection: "column",+ justifyContent: "space-between",}}- numberOfLines={2}>- {decode(link.name || link.description || link.url)}- </Text>-- {shortendURL && (<Textstyle={{- marginTop: 5,- fontWeight: "300",- fontSize: 14,+ fontWeight: "500",+ fontSize: 18,}}- numberOfLines={1}+ numberOfLines={2}>- {shortendURL}+ {decode(link.name || link.description || link.url)}</Text>- )}- <View- style={{- flexDirection: "row",- alignItems: "center",- gap: 5,- marginTop: 5,- marginRight: 20,- padding: 5,- alignSelf: "flex-start",- borderRadius: 5,- backgroundColor: link.collection.color- ? `${link.collection.color}33`- : "#00000033",- }}- >- <IconSymbol- name="folder.fill"- size={16}- color={link.collection.color || ""}- />+ {shortendURL && (+ <Text+ style={{+ marginTop: 5,+ fontWeight: "300",+ fontSize: 14,+ }}+ numberOfLines={1}+ >+ {shortendURL}+ </Text>+ )}- <Text+ <Viewstyle={{- fontWeight: "300",- fontSize: 12,+ flexDirection: "row",+ alignItems: "center",+ gap: 5,+ marginTop: 5,+ marginRight: 20,+ padding: 5,+ alignSelf: "flex-start",+ borderRadius: 5,+ backgroundColor: link.collection.color+ ? `${link.collection.color}33`+ : "#00000033",}}- numberOfLines={1}>- {link.collection.name}- </Text>- </View>- </View>-- <View- style={{- flexDirection: "column",- alignItems: "flex-end",- }}- >- <View- style={{ borderRadius: 7, position: "relative", overflow: "hidden" }}- >- {formatAvailable(link, "preview") ? (- <Image- source={{- uri:- auth.instance +- `/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true&updatedAt=${link.updatedAt}`,- headers: {- Authorization: `Bearer ${auth.session}`,- },- }}- style={{- borderRadius: 5,- height: 60,- width: 90,- resizeMode: "cover",- transform: [{ scale: 1.05 }],- }}+ <IconSymbol+ name="folder.fill"+ size={16}+ color={link.collection.color || ""}/>- ) : (- <View++ <Textstyle={{- height: 60,- width: 90,+ fontWeight: "300",+ fontSize: 12,}}- />- )}+ numberOfLines={1}+ >+ {link.collection.name}+ </Text>+ </View></View>+<Viewstyle={{- flexDirection: "row",- alignItems: "center",- gap: 5,- marginTop: 20,- alignSelf: "flex-start",+ flexDirection: "column",+ alignItems: "flex-end",}}>- <IconSymbol name="calendar" size={16} color={"gray"} />- <Text+ <Viewstyle={{- fontWeight: "300",- fontSize: 12,+ borderRadius: 7,+ position: "relative",+ overflow: "hidden",}}- numberOfLines={1}>- {new Date(link.createdAt as string).toLocaleString("en-US", {- year: "numeric",- month: "short",- day: "numeric",- })}- </Text>+ {formatAvailable(link, "preview") ? (+ <Image+ source={{+ uri:+ auth.instance ++ `/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true&updatedAt=${link.updatedAt}`,+ headers: {+ Authorization: `Bearer ${auth.session}`,+ },+ }}+ style={{+ borderRadius: 5,+ height: 60,+ width: 90,+ resizeMode: "cover",+ transform: [{ scale: 1.05 }],+ }}+ />+ ) : (+ <View+ style={{+ height: 60,+ width: 90,+ }}+ />+ )}+ </View>+ <View+ style={{+ flexDirection: "row",+ alignItems: "center",+ gap: 5,+ marginTop: 20,+ alignSelf: "flex-start",+ }}+ >+ <IconSymbol name="calendar" size={16} color={"gray"} />+ <Text+ style={{+ fontWeight: "300",+ fontSize: 12,+ }}+ numberOfLines={1}+ >+ {new Date(link.createdAt as string).toLocaleString("en-US", {+ year: "numeric",+ month: "short",+ day: "numeric",+ })}+ </Text>+ </View></View></View>- </View>+ </Link>);};diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 9563ca81..70cfdbf6 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -18,6 +18,7 @@"@expo/vector-icons": "^14.0.2","@linkwarden/lib": "*","@linkwarden/router": "*",+ "@linkwarden/types": "*","@react-native-menu/menu": "1.2.2","@react-navigation/bottom-tabs": "^7.0.0","@react-navigation/native": "^7.0.0",diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.tsindex 0b756aa6..4143b27e 100644--- a/apps/mobile/store/auth.ts+++ b/apps/mobile/store/auth.ts@@ -1,12 +1,9 @@import { create } from "zustand";import * as SecureStore from "expo-secure-store";import { router } from "expo-router";+import { MobileAuth } from "@linkwarden/types";-type Auth = {- status: "loading" | "authenticated" | "unauthenticated";- session: string | null;- instance: string | null;-};+type Auth = MobileAuth;type AuthStore = {auth: Auth;@@ -73,7 +70,7 @@ const useAuthStore = create<AuthStore>((set) => ({},});- router.push("/(tabs)");+ router.push("/dashboard");} else {set({auth: {diff --git a/apps/web/lib/client/openLink.ts b/apps/web/lib/client/openLink.tsindex 0cbeb63a..756360a4 100644--- a/apps/web/lib/client/openLink.ts+++ b/apps/web/lib/client/openLink.ts@@ -2,7 +2,7 @@ import {AccountSettings,LinkIncludingShortenedCollectionAndTags,} from "@linkwarden/types";-import { generateLinkHref } from "./generateLinkHref";+import { generateLinkHref } from "@linkwarden/lib/generateLinkHref";import { LinksRouteTo } from "@linkwarden/prisma/client";const openLink = (diff --git a/apps/worker/index.ts b/apps/worker/index.tsindex 15e48901..a32bed5a 100644--- a/apps/worker/index.ts+++ b/apps/worker/index.ts@@ -1,292 +1,16 @@-import { prisma } from "@linkwarden/prisma";-import archiveHandler from "./lib/archiveHandler";-import Parser from "rss-parser";-import { LinkWithCollectionOwnerAndTags } from "@linkwarden/types";-import getLinkBatch from "./lib/getLinkBatch";-import { meiliClient } from "@linkwarden/lib";-import { rssHandler } from "@linkwarden/lib";+import { spawn } from "node:child_process";-const archiveTakeCount = Number(process.env.ARCHIVE_TAKE_COUNT || "") || 5;-const indexTakeCount = Number(process.env.INDEX_TAKE_COUNT || "") || 50;+function launch() {+ const child = spawn("tsx", ["worker.ts"], { stdio: "inherit" });-function delay(sec: number) {- return new Promise((resolve) => setTimeout(resolve, sec * 1000));-}--const pollingIntervalInSeconds =- (Number(process.env.NEXT_PUBLIC_RSS_POLLING_INTERVAL_MINUTES) || 60) * 60; // Default to one hour if not set--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();-- await Promise.all(- rssSubscriptions.map(async (rssSubscription) => {- rssHandler(rssSubscription, parser);- })- );- 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 link ${link.url} for user ${link.collection.ownerId}:`,- error- );- }- };-- // Process each link in the batch concurrently- const processingPromises = links.map((e) => archiveLink(e));-- await Promise.allSettled(processingPromises);- await delay(archiveIntervalInSeconds);- }-}--async function setupLinksIndexSchema() {- if (!meiliClient) return;-- 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",- "tags",- "pinnedBy",- "url",- "type",- "name",- "description",- "collectionIsPublic",- "creationTimestamp",- ]);- await meiliClient- .index("links")- .waitForTask(updateFilterableAttributes.taskUid, {- timeOutMs: 1000000,- })- .catch((err) => {- console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);- });-- const updateSortableAttributes = await meiliClient- .index("links")- .updateSortableAttributes(["id", "name"]);-- await meiliClient- .index("links")- .waitForTask(updateSortableAttributes.taskUid, {- timeOutMs: 1000000,- })- .catch((err) => {- console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);- });-- // if (process.env.NODE_ENV !== "production") await clearIndexes(); // For development/debugging purposes ONLY! This function clears all the indexes and you'll have to reindex everything...-}--export async function startIndexing() {- if (!meiliClient) return;-- await setupLinksIndexSchema();-- console.log("\x1b[34m%s\x1b[0m", "Starting link indexing...");-- const INDEX_VERSION = 1;-- while (true) {- const links = await getLinkBatch({- where: {- AND: [- {- OR: [- { indexVersion: { not: INDEX_VERSION } },- { indexVersion: null },- ],- },- {- OR: [- { lastPreserved: { not: null } },- {- url: 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,- collectionOwnerId: link.collection.ownerId,- collectionMemberIds: link.collection.members.map((m) => m.userId),- collectionIsPublic: link.collection.isPublic,- collectionName: link.collection.name,- tags: link.tags.map((t) => t.name),- pinnedBy: link.pinnedBy.map((p) => p.id),- creationTimestamp: Date.parse(link.createdAt.toISOString()) / 1000,- indexVersion: INDEX_VERSION,- }));-- const task = await meiliClient.index("links").addDocuments(docs);- await meiliClient- .index("links")- .waitForTask(task.taskUid, {- timeOutMs: 300000,- })- .catch((err) => {- console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);- });-- const ids = links.map((l) => l.id);- await prisma.link.updateMany({- where: { id: { in: ids } },- data: { indexVersion: INDEX_VERSION },- });-- const indexesLeft = await prisma.link.count({- where: {- OR: [{ indexVersion: { not: INDEX_VERSION } }, { indexVersion: null }],- lastPreserved: { not: null },- },- });-- console.log(- "\x1b[34m%s\x1b[0m",- `Indexed ${links.length} link${- links.length === 1 ? "" : "s"- }, ${indexesLeft} left.`+ child.on("exit", (code, signal) => {+ console.error(+ `worker exited (code=${code} signal=${signal}) – restarting…`);-- await delay(archiveIntervalInSeconds);- }-}--async function init() {- console.log("\x1b[34m%s\x1b[0m", "Initializing the worker...");- startRSSPolling();- startArchiveProcessing();- startIndexing();+ setTimeout(launch, 5000);+ });}-init();--// const clearIndexes = async () => {-// console.log("Clearing db indexes...");--// const clearedLinks = await prisma.link.updateMany({-// where: {},-// data: {-// indexVersion: null,-// },-// });--// console.log("Cleared db indexes:", clearedLinks);--// if (!meiliClient) return;--// const deleteAllDocuments = await meiliClient-// .index("links")-// .deleteAllDocuments();+process.on("SIGINT", () => process.exit());-// await meiliClient.index("links").waitForTask(deleteAllDocuments.taskUid, {-// timeOutMs: 1000000,-// });-// };+launch();diff --git a/apps/worker/worker.ts b/apps/worker/worker.tsnew file mode 100644index 00000000..15e48901--- /dev/null+++ b/apps/worker/worker.ts@@ -0,0 +1,292 @@+import { prisma } from "@linkwarden/prisma";+import archiveHandler from "./lib/archiveHandler";+import Parser from "rss-parser";+import { LinkWithCollectionOwnerAndTags } from "@linkwarden/types";+import getLinkBatch from "./lib/getLinkBatch";+import { meiliClient } from "@linkwarden/lib";+import { rssHandler } from "@linkwarden/lib";++const archiveTakeCount = Number(process.env.ARCHIVE_TAKE_COUNT || "") || 5;+const indexTakeCount = Number(process.env.INDEX_TAKE_COUNT || "") || 50;++function delay(sec: number) {+ return new Promise((resolve) => setTimeout(resolve, sec * 1000));+}++const pollingIntervalInSeconds =+ (Number(process.env.NEXT_PUBLIC_RSS_POLLING_INTERVAL_MINUTES) || 60) * 60; // Default to one hour if not set++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();++ await Promise.all(+ rssSubscriptions.map(async (rssSubscription) => {+ rssHandler(rssSubscription, parser);+ })+ );+ 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 link ${link.url} for user ${link.collection.ownerId}:`,+ error+ );+ }+ };++ // Process each link in the batch concurrently+ const processingPromises = links.map((e) => archiveLink(e));++ await Promise.allSettled(processingPromises);+ await delay(archiveIntervalInSeconds);+ }+}++async function setupLinksIndexSchema() {+ if (!meiliClient) return;++ 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",+ "tags",+ "pinnedBy",+ "url",+ "type",+ "name",+ "description",+ "collectionIsPublic",+ "creationTimestamp",+ ]);+ await meiliClient+ .index("links")+ .waitForTask(updateFilterableAttributes.taskUid, {+ timeOutMs: 1000000,+ })+ .catch((err) => {+ console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);+ });++ const updateSortableAttributes = await meiliClient+ .index("links")+ .updateSortableAttributes(["id", "name"]);++ await meiliClient+ .index("links")+ .waitForTask(updateSortableAttributes.taskUid, {+ timeOutMs: 1000000,+ })+ .catch((err) => {+ console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);+ });++ // if (process.env.NODE_ENV !== "production") await clearIndexes(); // For development/debugging purposes ONLY! This function clears all the indexes and you'll have to reindex everything...+}++export async function startIndexing() {+ if (!meiliClient) return;++ await setupLinksIndexSchema();++ console.log("\x1b[34m%s\x1b[0m", "Starting link indexing...");++ const INDEX_VERSION = 1;++ while (true) {+ const links = await getLinkBatch({+ where: {+ AND: [+ {+ OR: [+ { indexVersion: { not: INDEX_VERSION } },+ { indexVersion: null },+ ],+ },+ {+ OR: [+ { lastPreserved: { not: null } },+ {+ url: 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,+ collectionOwnerId: link.collection.ownerId,+ collectionMemberIds: link.collection.members.map((m) => m.userId),+ collectionIsPublic: link.collection.isPublic,+ collectionName: link.collection.name,+ tags: link.tags.map((t) => t.name),+ pinnedBy: link.pinnedBy.map((p) => p.id),+ creationTimestamp: Date.parse(link.createdAt.toISOString()) / 1000,+ indexVersion: INDEX_VERSION,+ }));++ const task = await meiliClient.index("links").addDocuments(docs);+ await meiliClient+ .index("links")+ .waitForTask(task.taskUid, {+ timeOutMs: 300000,+ })+ .catch((err) => {+ console.error("\x1b[34m%s\x1b[0m", `Error indexing links:`, err);+ });++ const ids = links.map((l) => l.id);+ await prisma.link.updateMany({+ where: { id: { in: ids } },+ data: { indexVersion: INDEX_VERSION },+ });++ const indexesLeft = await prisma.link.count({+ where: {+ OR: [{ indexVersion: { not: INDEX_VERSION } }, { indexVersion: null }],+ lastPreserved: { not: null },+ },+ });++ console.log(+ "\x1b[34m%s\x1b[0m",+ `Indexed ${links.length} link${+ links.length === 1 ? "" : "s"+ }, ${indexesLeft} left.`+ );++ await delay(archiveIntervalInSeconds);+ }+}++async function init() {+ console.log("\x1b[34m%s\x1b[0m", "Initializing the worker...");+ startRSSPolling();+ startArchiveProcessing();+ startIndexing();+}++init();++// const clearIndexes = async () => {+// console.log("Clearing db indexes...");++// const clearedLinks = await prisma.link.updateMany({+// where: {},+// data: {+// indexVersion: null,+// },+// });++// console.log("Cleared db indexes:", clearedLinks);++// if (!meiliClient) return;++// const deleteAllDocuments = await meiliClient+// .index("links")+// .deleteAllDocuments();++// await meiliClient.index("links").waitForTask(deleteAllDocuments.taskUid, {+// timeOutMs: 1000000,+// });+// };diff --git a/apps/web/lib/client/generateLinkHref.ts b/packages/lib/generateLinkHref.tssimilarity index 70%rename from apps/web/lib/client/generateLinkHref.tsrename to packages/lib/generateLinkHref.tsindex b737d25b..acefbf68 100644--- a/apps/web/lib/client/generateLinkHref.ts+++ b/packages/lib/generateLinkHref.ts@@ -8,7 +8,8 @@ import { formatAvailable } from "@linkwarden/lib/formatStats";export const generateLinkHref = (link: LinkIncludingShortenedCollectionAndTags,- account: AccountSettings+ account: AccountSettings,+ instanceURL: string | null = ""): string => {// Return the links href based on the account's preference// If the user's preference is not available, return the original link@@ -17,27 +18,35 @@ export const generateLinkHref = (} else if (account.linksRouteTo === LinksRouteTo.PDF || link.type === "pdf") {if (!formatAvailable(link, "pdf")) return link.url || "";- return `/preserved/${link?.id}?format=${ArchivedFormat.pdf}`;+ return instanceURL + `/preserved/${link?.id}?format=${ArchivedFormat.pdf}`;} else if (account.linksRouteTo === LinksRouteTo.READABLE &&link.type === "url") {if (!formatAvailable(link, "readable")) return link.url || "";- return `/preserved/${link?.id}?format=${ArchivedFormat.readability}`;+ return (+ instanceURL ++ `/preserved/${link?.id}?format=${ArchivedFormat.readability}`+ );} else if (account.linksRouteTo === LinksRouteTo.SCREENSHOT ||link.type === "image") {if (!formatAvailable(link, "image")) return link.url || "";- return `/preserved/${link?.id}?format=${- link?.image?.endsWith("png") ? ArchivedFormat.png : ArchivedFormat.jpeg- }`;+ return (+ instanceURL ++ `/preserved/${link?.id}?format=${+ link?.image?.endsWith("png") ? ArchivedFormat.png : ArchivedFormat.jpeg+ }`+ );} else if (account.linksRouteTo === LinksRouteTo.MONOLITH) {if (!formatAvailable(link, "monolith")) return link.url || "";- return `/preserved/${link?.id}?format=${ArchivedFormat.monolith}`;+ return (+ instanceURL + `/preserved/${link?.id}?format=${ArchivedFormat.monolith}`+ );} else {return link.url || "";}diff --git a/packages/lib/package.json b/packages/lib/package.jsonindex 4631cc26..a685ba6a 100644--- a/packages/lib/package.json+++ b/packages/lib/package.json@@ -5,6 +5,7 @@"main": "index.ts","dependencies": {"@linkwarden/prisma": "*",+ "@linkwarden/types": "*","@linkwarden/filesystem": "*","jimp": "^0.22.10","meilisearch": "^0.48.2",diff --git a/packages/router/links.tsx b/packages/router/links.tsxindex 0806f7d4..7bc903d2 100644--- a/packages/router/links.tsx+++ b/packages/router/links.tsx@@ -8,20 +8,14 @@ import {ArchivedFormat,LinkIncludingShortenedCollectionAndTags,LinkRequestQuery,+ MobileAuth,} from "@linkwarden/types";import { useSession } from "next-auth/react";import { PostLinkSchemaType } from "@linkwarden/lib/schemaValidation";import getFormatFromContentType from "@linkwarden/lib/getFormatFromContentType";import getLinkTypeFromFormat from "@linkwarden/lib/getLinkTypeFromFormat";-const useLinks = (- params: LinkRequestQuery = {},- auth?: {- status: "loading" | "authenticated" | "unauthenticated";- session: string | null;- instance: string | null;- }-) => {+const useLinks = (params: LinkRequestQuery = {}, auth?: MobileAuth) => {const queryParamsObject = {sort: params.sort ?? Number(window.localStorage.getItem("sortBy")) ?? 0,collectionId: params.collectionId,@@ -46,14 +40,7 @@ const useLinks = (};};-const useFetchLinks = (- params: string,- auth?: {- status: "loading" | "authenticated" | "unauthenticated";- session: string | null;- instance: string | null;- }-) => {+const useFetchLinks = (params: string, auth?: MobileAuth) => {let status: "loading" | "authenticated" | "unauthenticated";if (!auth) {@@ -243,16 +230,25 @@ const useDeleteLink = () => {});};-const useGetLink = (isPublicRoute?: boolean) => {+const useGetLink = (isPublicRoute?: boolean, auth?: MobileAuth) => {const queryClient = useQueryClient();return useMutation({mutationFn: async ({ id }: { id: number }) => {- const path = isPublicRoute- ? `/api/v1/public/links/${id}`- : `/api/v1/links/${id}`;+ const path =+ (auth?.instance ? auth?.instance : "") ++ (isPublicRoute ? `/api/v1/public/links/${id}` : `/api/v1/links/${id}`);- const response = await fetch(path);+ const response = await fetch(+ path,+ auth?.session+ ? {+ headers: {+ Authorization: `Bearer ${auth?.session}`,+ },+ }+ : undefined+ );const data = await response.json();if (!response.ok) throw new Error(data.response);diff --git a/packages/router/user.tsx b/packages/router/user.tsxindex ca378ac2..ff5b5feb 100644--- a/packages/router/user.tsx+++ b/packages/router/user.tsx@@ -1,22 +1,47 @@+import { MobileAuth } from "@linkwarden/types";import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { useSession } from "next-auth/react";-const useUser = () => {- const { data, status } = useSession();+const useUser = (auth?: MobileAuth) => {+ let status: "authenticated" | "loading" | "unauthenticated";+ let userId: string = "";- const userId = (data?.user as any)?.id;+ if (!auth) {+ const { data, status: s } = useSession();+ status = s;+ userId = (data?.user as any)?.id;+ } else {+ status = auth.status;+ }++ const url =+ (auth?.instance ? auth?.instance : "") ++ "/api/v1/users" ++ (userId ? `/${userId}` : "");return useQuery({queryKey: ["user"],queryFn: async () => {- const response = await fetch(`/api/v1/users/${userId}`);+ const response = await fetch(+ url,+ auth?.session+ ? {+ headers: {+ Authorization: `Bearer ${auth.session}`,+ },+ }+ : undefined+ );+if (!response.ok) throw new Error("Failed to fetch user data.");const data = await response.json();return data.response;},- enabled: !!userId && status === "authenticated",+ enabled: !auth+ ? !!userId && status === "authenticated"+ : status === "authenticated",placeholderData: {},});};diff --git a/packages/types/global.ts b/packages/types/global.tsindex 4f656e86..eb5b5361 100644--- a/packages/types/global.ts+++ b/packages/types/global.ts@@ -172,3 +172,9 @@ export interface ArchivalSettings {archiveAsWaybackMachine: boolean;aiTag: boolean;}++export interface MobileAuth {+ status: "loading" | "authenticated" | "unauthenticated";+ session: string | null;+ instance: string | null;+}