Skip to content

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

Refactor worker-related functionality and update UI components

daniel31x136b3dba3faf13
diff --git a/apps/web/components/ConfirmationModal.tsx b/apps/web/components/ConfirmationModal.tsx
index 72737d19..5b45a62d 100644
--- a/apps/web/components/ConfirmationModal.tsx
+++ b/apps/web/components/ConfirmationModal.tsx
@@ -23,7 +23,7 @@ export default function ConfirmationModal({
const { t } = useTranslation();
return (
- <Modal toggleModal={toggleModal} className={className}>
+ <Modal toggleModal={() => toggleModal()} className={className}>
<p className="text-xl font-thin">{title}</p>
<Separator className="mb-3 mt-1" />
{children}
diff --git a/apps/web/components/ModalContent/DeleteUserModal.tsx b/apps/web/components/ModalContent/DeleteUserModal.tsx
index 1a0de921..b73c904d 100644
--- a/apps/web/components/ModalContent/DeleteUserModal.tsx
+++ b/apps/web/components/ModalContent/DeleteUserModal.tsx
@@ -37,7 +37,7 @@ export default function DeleteUserModal({ onClose, userId }: Props) {
const { data: config } = useConfig();
- const isAdmin = data?.user?.id === config?.ADMIN;
+ const isAdmin = data?.user?.id === (config?.ADMIN || 1);
return (
<Modal toggleModal={onClose}>
diff --git a/apps/web/components/SettingsSidebar.tsx b/apps/web/components/SettingsSidebar.tsx
index 919f7d63..62ca6383 100644
--- a/apps/web/components/SettingsSidebar.tsx
+++ b/apps/web/components/SettingsSidebar.tsx
@@ -3,7 +3,6 @@ import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import { useTranslation } from "next-i18next";
import { useUser } from "@linkwarden/router/user";
-import { useConfig } from "@linkwarden/router/config";
import Image from "next/image";
export default function SettingsSidebar({ className }: { className?: string }) {
@@ -11,8 +10,6 @@ export default function SettingsSidebar({ className }: { className?: string }) {
const LINKWARDEN_VERSION = process.env.version;
const { data: user } = useUser();
- const { data: config } = useConfig();
- const isAdmin = user?.id === (config?.ADMIN || 1);
const router = useRouter();
const [active, setActive] = useState("");
@@ -126,17 +123,17 @@ export default function SettingsSidebar({ className }: { className?: string }) {
</div>
</Link>
- <Link href="/settings/worker-console">
+ <Link href="/settings/background-jobs">
<div
className={`${
- active === "/settings/worker-console"
+ active === "/settings/background-jobs"
? "bg-primary/20"
: "hover:bg-neutral/20"
} duration-200 cursor-pointer flex items-center gap-2 rounded-lg px-3 py-1`}
>
<i className="bi-gear-wide-connected text-primary text-xl drop-shadow"></i>
<p className="truncate w-full font-semibold text-sm">
- {t("worker_console")}
+ {t("background_jobs")}
</p>
</div>
</Link>
diff --git a/apps/web/components/TagListing.tsx b/apps/web/components/TagListing.tsx
index ad3ba79c..368f1bdb 100644
--- a/apps/web/components/TagListing.tsx
+++ b/apps/web/components/TagListing.tsx
@@ -14,9 +14,6 @@ export default function TagListing({ tags, active }: TagListingProps) {
const { active: droppableActive } = useDndContext();
const { t } = useTranslation();
- const ctx = useDndContext();
- console.log("DndContext active?", ctx.active);
-
if (!tags[0]) {
return (
<div
diff --git a/apps/web/lib/api/controllers/worker/getWorkerStats.ts b/apps/web/lib/api/controllers/worker/getWorkerStats.ts
new file mode 100644
index 00000000..5ebf0672
--- /dev/null
+++ b/apps/web/lib/api/controllers/worker/getWorkerStats.ts
@@ -0,0 +1,67 @@
+import { prisma } from "@linkwarden/prisma";
+import { WorkerStats } from "@linkwarden/types";
+
+export default async function getWorkerStats(userId: number) {
+ const linkPending = await prisma.link.count({
+ where: {
+ url: { not: null },
+ lastPreserved: null,
+ },
+ });
+
+ const linkDone = await prisma.link.count({
+ where: {
+ lastPreserved: { not: null },
+ OR: [
+ { image: { not: "unavailable" } },
+ { pdf: { not: "unavailable" } },
+ { readable: { not: "unavailable" } },
+ { monolith: { not: "unavailable" } },
+ ],
+ },
+ });
+
+ const linkFailed = await prisma.link.count({
+ where: {
+ url: { not: null },
+ lastPreserved: { not: null },
+ image: "unavailable",
+ pdf: "unavailable",
+ readable: "unavailable",
+ monolith: "unavailable",
+ },
+ });
+
+ const INDEX_VERSION = 1;
+
+ const searchPending = await prisma.link.count({
+ where: {
+ OR: [{ indexVersion: { not: INDEX_VERSION } }, { indexVersion: null }],
+ },
+ });
+
+ const searchDone = await prisma.link.count({
+ where: {
+ indexVersion: INDEX_VERSION,
+ },
+ });
+
+ const data: WorkerStats = {
+ link: {
+ pending: linkPending,
+ done: linkDone,
+ failed: linkFailed,
+ },
+ search: {
+ pending: searchPending,
+ done: searchDone,
+ },
+ };
+
+ return {
+ data,
+ success: true,
+ message: "Worker stats fetched successfully.",
+ status: 200,
+ };
+}
diff --git a/apps/web/pages/admin.tsx b/apps/web/pages/admin.tsx
index 6a63d61a..3859821c 100644
--- a/apps/web/pages/admin.tsx
+++ b/apps/web/pages/admin.tsx
@@ -1,13 +1,16 @@
import NewUserModal from "@/components/ModalContent/NewUserModal";
import { User as U } from "@linkwarden/prisma/client";
import Link from "next/link";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useTranslation } from "next-i18next";
import getServerSideProps from "@/lib/client/getServerSideProps";
import UserListing from "@/components/UserListing";
import { useUsers } from "@linkwarden/router/users";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
+import { useConfig } from "@linkwarden/router/config";
+import { useRouter } from "next/router";
+import { useUser } from "@linkwarden/router/user";
interface User extends U {
subscriptions: {
@@ -25,6 +28,17 @@ export default function Admin() {
const { data: users = [] } = useUsers();
+ const { data: user } = useUser();
+ const { data: config } = useConfig();
+ const router = useRouter();
+
+ useEffect(() => {
+ if (config && user && user?.id !== (config?.ADMIN || 1)) {
+ console.log(config, user);
+ router.replace("/dashboard");
+ }
+ }, [config, user]);
+
const [searchQuery, setSearchQuery] = useState("");
const [filteredUsers, setFilteredUsers] = useState<User[] | null>(null);
diff --git a/apps/web/pages/api/v1/links/archive/index.ts b/apps/web/pages/api/v1/links/archive/index.ts
index 098cdf25..7eec7728 100644
--- a/apps/web/pages/api/v1/links/archive/index.ts
+++ b/apps/web/pages/api/v1/links/archive/index.ts
@@ -2,17 +2,19 @@ import type { NextApiRequest, NextApiResponse } from "next";
import verifyUser from "@/lib/api/verifyUser";
import { prisma } from "@linkwarden/prisma";
import { LinkArchiveActionSchema } from "@linkwarden/lib/schemaValidation";
-import { removeFiles, removePreservationFiles } from "@linkwarden/filesystem";
-import { ArchivalSettings } from "@linkwarden/types";
-import { isArchivalTag } from "@linkwarden/lib";
+import { removeFiles } from "@linkwarden/filesystem";
export default async function links(req: NextApiRequest, res: NextApiResponse) {
const user = await verifyUser({ req, res });
if (!user) return;
- const isServerAdmin = user.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1);
-
if (req.method === "DELETE") {
+ 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 dataValidation = LinkArchiveActionSchema.safeParse(req.body);
if (!dataValidation.success) {
return res.status(400).json({
@@ -22,7 +24,7 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
});
}
- const { action, linkIds } = dataValidation.data;
+ const { linkIds } = dataValidation.data;
if (linkIds) {
const authorizedLinks = await prisma.link.findMany({
@@ -86,169 +88,5 @@ export default async function links(req: NextApiRequest, res: NextApiResponse) {
return;
}
-
- if (action === "allAndIgnore") {
- if (!isServerAdmin) {
- return res.status(401).json({ response: "Permission denied." });
- }
-
- const allLinks = await prisma.link.findMany({
- where: {
- type: "url",
- url: {
- not: null,
- },
- },
- });
-
- for (const link of allLinks) {
- await removePreservationFiles(link.id, link.collectionId);
- await prisma.link.update({
- where: { id: link.id },
- data: {
- preview: link.preview ? link.preview : undefined,
- image: "unavailable",
- pdf: "unavailable",
- readable: "unavailable",
- monolith: "unavailable",
- },
- });
-
- console.log("Deleted preservation link:", link.id);
- }
-
- return res.status(200).json({ response: "Success." });
- } else if (action === "allAndRePreserve") {
- if (!isServerAdmin) {
- return res.status(401).json({ response: "Permission denied." });
- }
-
- const allLinks = await prisma.link.findMany({
- where: {
- type: "url",
- url: {
- not: null,
- },
- },
- });
- for (const link of allLinks) {
- await removeFiles(link.id, link.collectionId);
- await prisma.link.update({
- where: { id: link.id },
- data: {
- image: null,
- pdf: null,
- readable: null,
- monolith: null,
- preview: null,
- lastPreserved: null,
- indexVersion: null,
- },
- });
-
- console.log("Deleted preservation link:", link.id);
- }
-
- return res.status(200).json({ response: "Success." });
- } else if (action === "allBroken") {
- if (!isServerAdmin) {
- return res.status(401).json({ response: "Permission denied." });
- }
-
- const brokenArchives = await prisma.link.findMany({
- where: {
- type: "url",
- url: {
- not: null,
- },
- OR: [
- { image: "unavailable" },
- { pdf: "unavailable" },
- { readable: "unavailable" },
- { monolith: "unavailable" },
- { preview: "unavailable" },
- ],
- },
- include: {
- createdBy: {
- select: {
- archiveAsScreenshot: true,
- archiveAsMonolith: true,
- archiveAsPDF: true,
- archiveAsReadable: true,
- archiveAsWaybackMachine: true,
- },
- },
- tags: true,
- },
- });
-
- for (const link of brokenArchives) {
- const archivalTags = link.tags.filter(isArchivalTag);
-
- const shouldArchive: Omit<
- ArchivalSettings,
- "aiTag" | "archiveAsWaybackMachine"
- > =
- archivalTags.length > 0
- ? {
- archiveAsScreenshot: archivalTags.some(
- (tag) => tag.archiveAsScreenshot
- ),
- archiveAsMonolith: archivalTags.some(
- (tag) => tag.archiveAsMonolith
- ),
- archiveAsPDF: archivalTags.some((tag) => tag.archiveAsPDF),
- archiveAsReadable: archivalTags.some(
- (tag) => tag.archiveAsReadable
- ),
- }
- : {
- archiveAsScreenshot:
- link.createdBy?.archiveAsScreenshot || false,
- archiveAsMonolith: link.createdBy?.archiveAsMonolith || false,
- archiveAsPDF: link.createdBy?.archiveAsPDF || false,
- archiveAsReadable: link.createdBy?.archiveAsReadable || false,
- };
-
- const needsReprocessing =
- (link.image === "unavailable" && shouldArchive.archiveAsScreenshot) ||
- (link.monolith === "unavailable" &&
- shouldArchive.archiveAsMonolith) ||
- (link.pdf === "unavailable" && shouldArchive.archiveAsPDF) ||
- (link.readable === "unavailable" && shouldArchive.archiveAsReadable);
-
- if (needsReprocessing) {
- await prisma.link.update({
- where: { id: link.id },
- data: {
- image:
- shouldArchive.archiveAsScreenshot &&
- link.image === "unavailable"
- ? null
- : link.image,
- pdf:
- shouldArchive.archiveAsPDF && link.pdf === "unavailable"
- ? null
- : link.pdf,
- readable:
- shouldArchive.archiveAsReadable &&
- link.readable === "unavailable"
- ? null
- : link.readable,
- monolith:
- shouldArchive.archiveAsMonolith &&
- link.monolith === "unavailable"
- ? null
- : link.monolith,
- lastPreserved: null,
- indexVersion: null,
- },
- });
- }
- }
-
- return res.status(200).json({ response: "Success." });
- }
}
}
diff --git a/apps/web/pages/api/v1/worker/index.ts b/apps/web/pages/api/v1/worker/index.ts
new file mode 100644
index 00000000..f9da224d
--- /dev/null
+++ b/apps/web/pages/api/v1/worker/index.ts
@@ -0,0 +1,20 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import verifyUser from "@/lib/api/verifyUser";
+import getWorkerStats from "@/lib/api/controllers/worker/getWorkerStats";
+
+export default async function worker(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ const user = await verifyUser({ req, res });
+ if (!user) return;
+
+ if (user.id !== Number(process.env.NEXT_PUBLIC_ADMIN || 1)) {
+ return res.status(403).json({ response: "Forbidden." });
+ }
+
+ if (req.method === "GET") {
+ const { status, ...data } = await getWorkerStats(user.id);
+ return res.status(status).json(data);
+ }
+}
diff --git a/apps/web/pages/api/v1/worker/preservation.tsx b/apps/web/pages/api/v1/worker/preservation.tsx
new file mode 100644
index 00000000..b749d364
--- /dev/null
+++ b/apps/web/pages/api/v1/worker/preservation.tsx
@@ -0,0 +1,167 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import verifyUser from "@/lib/api/verifyUser";
+import { prisma } from "@linkwarden/prisma";
+import { DeletePreservationsSchema } from "@linkwarden/lib/schemaValidation";
+import { removeFiles } from "@linkwarden/filesystem";
+import { ArchivalSettings } from "@linkwarden/types";
+import { isArchivalTag } from "@linkwarden/lib";
+
+export default async function links(req: NextApiRequest, res: NextApiResponse) {
+ const user = await verifyUser({ req, res });
+ if (!user) return;
+
+ const isServerAdmin = user.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1);
+ if (!isServerAdmin) {
+ return res.status(403).json({ response: "Forbidden." });
+ }
+
+ if (req.method === "DELETE") {
+ 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 dataValidation = DeletePreservationsSchema.safeParse(req.body);
+ if (!dataValidation.success) {
+ return res.status(400).json({
+ response: `Error: ${
+ dataValidation.error.issues[0].message
+ } [${dataValidation.error.issues[0].path.join(", ")}]`,
+ });
+ }
+
+ const { action } = dataValidation.data;
+
+ if (action === "allAndRePreserve") {
+ const allLinks = await prisma.link.findMany({
+ where: {
+ collection: {
+ ownerId: user.id,
+ },
+ type: "url",
+ url: {
+ not: null,
+ },
+ },
+ });
+ for (const link of allLinks) {
+ await removeFiles(link.id, link.collectionId);
+ await prisma.link.update({
+ where: { id: link.id },
+ data: {
+ image: null,
+ pdf: null,
+ readable: null,
+ monolith: null,
+ preview: null,
+ lastPreserved: null,
+ indexVersion: null,
+ },
+ });
+
+ console.log("Deleted preservation link:", link.id);
+ }
+
+ return res.status(200).json({ response: "Success." });
+ } else if (action === "allBroken") {
+ const brokenArchives = await prisma.link.findMany({
+ where: {
+ type: "url",
+ url: {
+ not: null,
+ },
+ collection: {
+ ownerId: user.id,
+ },
+ OR: [
+ { image: "unavailable" },
+ { pdf: "unavailable" },
+ { readable: "unavailable" },
+ { monolith: "unavailable" },
+ { preview: "unavailable" },
+ ],
+ },
+ include: {
+ createdBy: {
+ select: {
+ archiveAsScreenshot: true,
+ archiveAsMonolith: true,
+ archiveAsPDF: true,
+ archiveAsReadable: true,
+ archiveAsWaybackMachine: true,
+ },
+ },
+ tags: true,
+ },
+ });
+
+ for (const link of brokenArchives) {
+ const archivalTags = link.tags.filter(isArchivalTag);
+
+ const shouldArchive: Omit<
+ ArchivalSettings,
+ "aiTag" | "archiveAsWaybackMachine"
+ > =
+ archivalTags.length > 0
+ ? {
+ archiveAsScreenshot: archivalTags.some(
+ (tag) => tag.archiveAsScreenshot
+ ),
+ archiveAsMonolith: archivalTags.some(
+ (tag) => tag.archiveAsMonolith
+ ),
+ archiveAsPDF: archivalTags.some((tag) => tag.archiveAsPDF),
+ archiveAsReadable: archivalTags.some(
+ (tag) => tag.archiveAsReadable
+ ),
+ }
+ : {
+ archiveAsScreenshot:
+ link.createdBy?.archiveAsScreenshot || false,
+ archiveAsMonolith: link.createdBy?.archiveAsMonolith || false,
+ archiveAsPDF: link.createdBy?.archiveAsPDF || false,
+ archiveAsReadable: link.createdBy?.archiveAsReadable || false,
+ };
+
+ const needsReprocessing =
+ (link.image === "unavailable" && shouldArchive.archiveAsScreenshot) ||
+ (link.monolith === "unavailable" &&
+ shouldArchive.archiveAsMonolith) ||
+ (link.pdf === "unavailable" && shouldArchive.archiveAsPDF) ||
+ (link.readable === "unavailable" && shouldArchive.archiveAsReadable);
+
+ if (needsReprocessing) {
+ await prisma.link.update({
+ where: { id: link.id },
+ data: {
+ image:
+ shouldArchive.archiveAsScreenshot &&
+ link.image === "unavailable"
+ ? null
+ : link.image,
+ pdf:
+ shouldArchive.archiveAsPDF && link.pdf === "unavailable"
+ ? null
+ : link.pdf,
+ readable:
+ shouldArchive.archiveAsReadable &&
+ link.readable === "unavailable"
+ ? null
+ : link.readable,
+ monolith:
+ shouldArchive.archiveAsMonolith &&
+ link.monolith === "unavailable"
+ ? null
+ : link.monolith,
+ lastPreserved: null,
+ indexVersion: null,
+ },
+ });
+ }
+ }
+
+ return res.status(200).json({ response: "Success." });
+ }
+ }
+}
diff --git a/apps/web/pages/settings/background-jobs.tsx b/apps/web/pages/settings/background-jobs.tsx
new file mode 100644
index 00000000..71fd0d3a
--- /dev/null
+++ b/apps/web/pages/settings/background-jobs.tsx
@@ -0,0 +1,205 @@
+import SettingsLayout from "@/layouts/SettingsLayout";
+import { Trans, useTranslation } from "next-i18next";
+import getServerSideProps from "@/lib/client/getServerSideProps";
+import { ReactElement, use, useEffect, useState } from "react";
+import ConfirmationModal from "@/components/ConfirmationModal";
+import { DeletePreservationsSchemaType } from "@linkwarden/lib/schemaValidation";
+import toast from "react-hot-toast";
+import { useDeletePreservations, useWorker } from "@linkwarden/router/worker";
+import { Button } from "@/components/ui/button";
+import { Separator } from "@/components/ui/separator";
+import { NextPageWithLayout } from "../_app";
+import { useConfig } from "@linkwarden/router/config";
+import { useUser } from "@linkwarden/router/user";
+import { useRouter } from "next/router";
+
+const Page: NextPageWithLayout = () => {
+ const { t } = useTranslation();
+ const deletePreservations = useDeletePreservations();
+ const workerStats = useWorker();
+ const [showModal, setShowModal] = useState(false);
+ const [submitLoader, setSubmitLoader] = useState(false);
+ const [action, setAction] = useState<
+ DeletePreservationsSchemaType["action"] | undefined
+ >();
+
+ const { data: config } = useConfig();
+ const { data: user } = useUser();
+ const router = useRouter();
+
+ useEffect(() => {
+ if (config && user && user?.id !== (config?.ADMIN || 1)) {
+ console.log(config, user);
+ router.replace("/dashboard");
+ }
+ }, [config, user]);
+
+ useEffect(() => {
+ if (showModal === false) {
+ setAction(undefined);
+ }
+ }, [showModal]);
+
+ const submit = async (action: DeletePreservationsSchemaType["action"]) => {
+ if (!action || submitLoader) return;
+ setSubmitLoader(true);
+
+ const load = toast.loading(t("deleting"));
+
+ await deletePreservations.mutateAsync(
+ { action },
+ {
+ onSettled: (data, error) => {
+ setSubmitLoader(false);
+ toast.dismiss(load);
+
+ if (error) {
+ toast.error(error.message);
+ } else {
+ toast.success(t("links_are_being_represerved"));
+ }
+ },
+ }
+ );
+ };
+
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <i className="bi-gear-wide-connected text-primary text-2xl"></i>
+ <p className="capitalize text-3xl font-thin inline">
+ {t("background_jobs")}
+ </p>
+ </div>
+
+ <Separator className="my-3" />
+
+ <p>{t("background_jobs_desc")}</p>
+
+ <div className="flex items-center gap-2 my-3">
+ <p className="capitalize text-2xl font-thin inline">
+ {t("link_preservation_job")}
+ </p>
+ </div>
+
+ <Separator className="my-3" />
+
+ <div className="flex flex-col sm:flex-row gap-3 justify-between items-start">
+ <div>
+ <p>{t("link_preservation_job_desc")}</p>
+ <div className="mt-3 flex gap-3">
+ <div className="flex gap-1 border border-warning bg-warning/20 rounded-md px-2 py-1 w-max">
+ <i className="bi-hourglass-split text-warning text-xl" />
+ <p>{workerStats.data?.link.pending}</p>
+ <p>{t("pending")}</p>
+ </div>
+
+ <div className="flex gap-1 border border-success bg-success/20 rounded-md px-2 py-1 w-max">
+ <i className="bi-check2 text-success text-xl" />
+ <p>{workerStats.data?.link.done}</p>
+ <p>{t("done")}</p>
+ </div>
+ </div>
+ </div>
+ <div className="flex gap-3 flex-col">
+ <Button
+ onClick={() => {
+ setAction("allBroken");
+ setShowModal(true);
+ }}
+ variant="metal"
+ >
+ {t("regenerate_broken_links")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => {
+ setAction("allAndRePreserve");
+ setShowModal(true);
+ }}
+ >
+ {t("regenerate_all_links")}
+ </Button>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-2 my-3">
+ <p className="capitalize text-2xl font-thin inline">
+ {t("search_indexing_job")}
+ </p>
+ </div>
+
+ <Separator className="my-3" />
+
+ <p>{t("search_indexing_job_desc")}</p>
+
+ <p>{t("worker_pending_indexing_desc")}</p>
+
+ <div className="mt-3 flex gap-3">
+ <div className="flex gap-1 border border-warning bg-warning/20 rounded-md px-2 py-1 w-max">
+ <i className="bi-hourglass-split text-warning text-xl" />
+ <p>{workerStats.data?.search.pending}</p>
+ <p>{t("pending")}</p>
+ </div>
+
+ <div className="flex gap-1 border border-success bg-success/20 rounded-md px-2 py-1 w-max">
+ <i className="bi-check2 text-success text-xl" />
+ <p>{workerStats.data?.search.done}</p>
+ <p>{t("done")}</p>
+ </div>
+ </div>
+
+ {showModal && action === "allBroken" && (
+ <ConfirmationModal
+ title={t("regenerate_broken_links")}
+ onConfirmed={() => submit(action)}
+ toggleModal={setShowModal}
+ >
+ <ul className="px-5 list-disc">
+ <Trans
+ i18nKey="regenerate_broken_preserved_content_desc"
+ components={[<li />]}
+ values={{
+ count: workerStats.data?.link.failed,
+ }}
+ />
+ </ul>
+ <div role="alert" className="alert alert-warning mt-3">
+ <i className="bi-exclamation-triangle text-xl" />
+ <span>
+ <b>{t("warning")}:</b> {t("irreversible_action_warning")}
+ </span>
+ </div>
+ </ConfirmationModal>
+ )}
+ {showModal && action === "allAndRePreserve" && (
+ <ConfirmationModal
+ title={t("regenerate_all_links")}
+ onConfirmed={() => submit(action)}
+ toggleModal={setShowModal}
+ >
+ <ul className="px-5 list-disc">
+ <Trans
+ i18nKey="delete_all_preserved_content_and_regenerate_desc"
+ components={[<li />]}
+ />
+ </ul>
+ <div role="alert" className="alert alert-warning mt-3">
+ <i className="bi-exclamation-triangle text-xl" />
+ <span>
+ <b>{t("warning")}:</b> {t("irreversible_action_warning")}
+ </span>
+ </div>
+ </ConfirmationModal>
+ )}
+ </>
+ );
+};
+
+Page.getLayout = function getLayout(page: ReactElement) {
+ return <SettingsLayout>{page}</SettingsLayout>;
+};
+
+export default Page;
+
+export { getServerSideProps };
diff --git a/apps/web/pages/settings/billing.tsx b/apps/web/pages/settings/billing.tsx
index c6f575f4..dac62164 100644
--- a/apps/web/pages/settings/billing.tsx
+++ b/apps/web/pages/settings/billing.tsx
@@ -168,6 +168,7 @@ const Page: NextPageWithLayout = () => {
<th>{t("status")}</th>
)}
<th>{t("date_added")}</th>
+ <th></th>
</tr>
</thead>
<tbody>
@@ -175,7 +176,7 @@ const Page: NextPageWithLayout = () => {
<tr
key={index}
className={clsx(
- "group border-b-neutral-content duration-100 w-full relative flex flex-col sm:table-row",
+ "group border-b-neutral-content last:border-b-0 duration-100 w-full relative flex flex-col sm:table-row",
user.id !== account?.id &&
"hover:bg-neutral-content hover:bg-opacity-30"
)}
@@ -216,8 +217,8 @@ const Page: NextPageWithLayout = () => {
})}
</p>
</td>
- {user.id !== account?.id && (
- <td className="relative">
+ <td className="relative">
+ {user.id !== account?.id && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
@@ -272,8 +273,8 @@ const Page: NextPageWithLayout = () => {
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
- </td>
- )}
+ )}
+ </td>
</tr>
))}
</tbody>
diff --git a/apps/web/pages/settings/password.tsx b/apps/web/pages/settings/password.tsx
index 68c274b4..cae67c11 100644
--- a/apps/web/pages/settings/password.tsx
+++ b/apps/web/pages/settings/password.tsx
@@ -69,7 +69,7 @@ const Page: NextPageWithLayout = () => {
<Separator className="my-3" />
<p className="mb-3">{t("password_change_instructions")}</p>
- <div className="w-full flex flex-col gap-2 justify-between max-w-screen-lg">
+ <div className="w-full flex flex-col gap-2 justify-between max-w-screen-sm">
<p>{t("old_password")}</p>
<TextInput
diff --git a/apps/web/pages/settings/worker-console.tsx b/apps/web/pages/settings/worker-console.tsx
deleted file mode 100644
index b1323f9d..00000000
--- a/apps/web/pages/settings/worker-console.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import SettingsLayout from "@/layouts/SettingsLayout";
-import { useTranslation } from "next-i18next";
-import getServerSideProps from "@/lib/client/getServerSideProps";
-import { ReactElement, useEffect, useState } from "react";
-import ConfirmationModal from "@/components/ConfirmationModal";
-import { LinkArchiveActionSchemaType } from "@linkwarden/lib/schemaValidation";
-import toast from "react-hot-toast";
-import { useArchiveAction } from "@linkwarden/router/links";
-import { Button } from "@/components/ui/button";
-import { Separator } from "@/components/ui/separator";
-import { NextPageWithLayout } from "../_app";
-
-const Page: NextPageWithLayout = () => {
- const { t } = useTranslation();
- const archiveAction = useArchiveAction();
- const [showModal, setShowModal] = useState(false);
- const [submitLoader, setSubmitLoader] = useState(false);
- const [action, setAction] = useState<
- LinkArchiveActionSchemaType["action"] | undefined
- >();
-
- useEffect(() => {
- if (showModal === false) {
- setAction(undefined);
- }
- }, [showModal]);
-
- const submit = async (action: LinkArchiveActionSchemaType["action"]) => {
- if (!action || submitLoader) return;
- setSubmitLoader(true);
-
- const load = toast.loading(t("deleting"));
-
- await archiveAction.mutateAsync(
- { action },
- {
- onSettled: (data, error) => {
- setSubmitLoader(false);
- toast.dismiss(load);
-
- if (error) {
- toast.error(error.message);
- } else {
- if (action === "allAndIgnore") {
- toast.success(t("deleted"));
- } else {
- toast.success(t("links_are_being_represerved"));
- }
- }
- },
- }
- );
- };
-
- return (
- <>
- <div className="flex items-center gap-2">
- <i className="bi-gear-wide-connected text-primary text-2xl"></i>
- <p className="capitalize text-3xl font-thin inline">
- {t("worker_console")}
- </p>
- </div>
-
- <Separator className="my-3" />
-
- <div className="w-full flex flex-col gap-6 justify-between">
- <div className="flex flex-col sm:flex-row sm:items-center gap-3">
- <span>{t("regenerate_broken_preservations")}</span>
- <Button
- onClick={() => submit("allBroken")}
- className="ml-auto"
- variant="primary"
- >
- {t("confirm")}
- </Button>
- </div>
- <div className="flex flex-col sm:flex-row sm:items-center gap-3">
- <span>{t("delete_all_preservations_and_regenerate")}</span>
- <Button
- className="ml-auto"
- variant="destructive"
- onClick={() => {
- setAction("allAndRePreserve");
- setShowModal(true);
- }}
- >
- {t("confirm")}
- </Button>
- </div>
- <div className="flex flex-col sm:flex-row sm:items-center gap-3">
- <span>{t("delete_all_preservations")}</span>
- <Button
- className="ml-auto"
- variant="destructive"
- onClick={() => {
- setAction("allAndIgnore");
- setShowModal(true);
- }}
- >
- {t("confirm")}
- </Button>
- </div>
- </div>
- {showModal && action && (
- <ConfirmationModal
- title={
- action === "allAndIgnore"
- ? t("delete_all_preservations")
- : t("delete_all_preservations_and_regenerate")
- }
- onConfirmed={() => submit(action)}
- toggleModal={setShowModal}
- >
- <p>{t("delete_all_preservation_warning")}</p>
- <div role="alert" className="alert alert-warning mt-3">
- <i className="bi-exclamation-triangle text-xl" />
- <span>
- <b>{t("warning")}:</b> {t("irreversible_action_warning")}
- </span>
- </div>
- </ConfirmationModal>
- )}
- </>
- );
-};
-
-Page.getLayout = function getLayout(page: ReactElement) {
- return <SettingsLayout>{page}</SettingsLayout>;
-};
-
-export default Page;
-
-export { getServerSideProps };
diff --git a/apps/web/pages/settings/worker.tsx b/apps/web/pages/settings/worker.tsx
index f572ebed..03262a09 100644
--- a/apps/web/pages/settings/worker.tsx
+++ b/apps/web/pages/settings/worker.tsx
@@ -1,22 +1,14 @@
-// Redirect to /settings/worker-console page, thats it!
-
-import { ReactElement } from "react";
-import { NextPageWithLayout } from "../_app";
-import { useRouter } from "next/router";
-import { useEffect } from "react";
-
-const Page: NextPageWithLayout = () => {
- const router = useRouter();
-
- useEffect(() => {
- router.replace("/settings/worker-console");
- }, [router]);
-
- return null;
+import type { GetServerSideProps } from "next";
+
+export const getServerSideProps: GetServerSideProps = async () => {
+ return {
+ redirect: {
+ destination: "/settings/background-jobs",
+ permanent: false,
+ },
+ };
};
-export default Page;
-
-Page.getLayout = function getLayout(page: ReactElement) {
- return page;
-};
+export default function WorkerRedirect() {
+ return null;
+}
diff --git a/apps/web/public/locales/en/common.json b/apps/web/public/locales/en/common.json
index 3a560241..f0013628 100644
--- a/apps/web/public/locales/en/common.json
+++ b/apps/web/public/locales/en/common.json
@@ -468,10 +468,6 @@
"tag_preservation_rule_label": "Preservation rules by tag (override global settings):",
"ai_tagging": "AI Tagging",
"worker": "Worker",
- "regenerate_broken_preservations": "Regenerate all broken or missing preservations for all users.",
- "delete_all_preservations": "Delete preservation for all webpages, applies to all users.",
- "delete_all_preservations_and_regenerate": "Delete and re-preserve all webpages, applies to all users.",
- "delete_all_preservation_warning": "This action will delete all existing preservations on the server.",
"no_broken_preservations": "No broken preservations.",
"links_are_being_represerved": "Links are being re-preserved...",
"cancel": "Cancel",
@@ -529,5 +525,16 @@
"apply_members_roles_to_subcollections": "Apply members and roles to subcollections",
"apply_members_roles_to_subcollections_desc": "This will apply the members and their roles to all existing subcollections.",
"back_to_dashboard": "Back to Dashboard",
- "worker_console": "Worker Console"
+ "background_jobs": "Background Jobs",
+ "background_jobs_desc": "Background jobs run 24/7 behind the scenes to process all queued links and tasks.",
+ "link_preservation_job": "Link Preservation Job",
+ "link_preservation_job_desc": "Crawls, preserves, and extracts text from your links.",
+ "search_indexing_job": "Search Indexing Job",
+ "search_indexing_job_desc": "Prepares links and documents for full-text search.",
+ "done": "Done",
+ "worker_pending_indexing_desc": "Pending items first need to be preserved before they can be indexed if they're a link.",
+ "regenerate_broken_links": "Regenerate Broken Links",
+ "regenerate_all_links": "Regenerate All Links",
+ "regenerate_broken_preserved_content_desc": "<0>Delete and re-preserve broken links with at least one missing preserved format.</0><0>This action will immediately delete any existing preserved format for {{count}} links.</0><0>Affected links will be scheduled to have their preserved formats rebuilt.</0>",
+ "delete_all_preserved_content_and_regenerate_desc": "<0>This action will immediately delete all your existing preserved formats.</0><0>Affected links will be scheduled to have their preserved formats rebuilt.</0>"
}
diff --git a/apps/worker/workers/linkIndexing.ts b/apps/worker/workers/linkIndexing.ts
index 948f4e2d..fc533ef4 100644
--- a/apps/worker/workers/linkIndexing.ts
+++ b/apps/worker/workers/linkIndexing.ts
@@ -66,6 +66,8 @@ export async function startIndexing(interval = 10) {
console.log("\x1b[34m%s\x1b[0m", "Starting link indexing...");
const INDEX_VERSION = 1;
+ const TRIAL_PERIOD_DAYS = process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS || 14;
+ const REQUIRE_CC = process.env.NEXT_PUBLIC_REQUIRE_CC === "true";
while (true) {
const links = await getLinkBatch({
@@ -85,6 +87,30 @@ export async function startIndexing(interval = 10) {
},
],
},
+ {
+ ...(process.env.STRIPE_SECRET_KEY
+ ? {
+ createdBy: {
+ OR: [
+ { subscriptions: { is: { active: true } } },
+ { parentSubscription: { is: { active: true } } },
+ ...(REQUIRE_CC
+ ? []
+ : [
+ {
+ createdAt: {
+ gte: new Date(
+ new Date().getTime() -
+ Number(TRIAL_PERIOD_DAYS) * 86400000
+ ),
+ },
+ },
+ ]),
+ ],
+ },
+ }
+ : {}),
+ },
],
},
take: takeCount,
diff --git a/packages/filesystem/manageFiles.ts b/packages/filesystem/manageFiles.ts
index 3ce7165a..e3229efc 100644
--- a/packages/filesystem/manageFiles.ts
+++ b/packages/filesystem/manageFiles.ts
@@ -30,34 +30,6 @@ const removeFiles = async (linkId: number, collectionId: number) => {
});
};
-const removePreservationFiles = async (
- linkId: number,
- collectionId: number
-) => {
- // PDF
- await removeFile({
- filePath: `archives/${collectionId}/${linkId}.pdf`,
- });
- // Images
- await removeFile({
- filePath: `archives/${collectionId}/${linkId}.png`,
- });
- await removeFile({
- filePath: `archives/${collectionId}/${linkId}.jpeg`,
- });
- await removeFile({
- filePath: `archives/${collectionId}/${linkId}.jpg`,
- });
- // HTML
- await removeFile({
- filePath: `archives/${collectionId}/${linkId}.html`,
- });
- // Readability
- await removeFile({
- filePath: `archives/${collectionId}/${linkId}_readability.json`,
- });
-};
-
const moveFiles = async (linkId: number, from: number, to: number) => {
await moveFile(
`archives/${from}/${linkId}.pdf`,
@@ -95,4 +67,4 @@ const moveFiles = async (linkId: number, from: number, to: number) => {
);
};
-export { removeFiles, removePreservationFiles, moveFiles };
+export { removeFiles, moveFiles };
diff --git a/packages/lib/schemaValidation.ts b/packages/lib/schemaValidation.ts
index 52ac2317..15eec1b2 100644
--- a/packages/lib/schemaValidation.ts
+++ b/packages/lib/schemaValidation.ts
@@ -295,7 +295,6 @@ export const PostHighlightSchema = z.object({
export type PostHighlightSchemaType = z.infer<typeof PostHighlightSchema>;
export const LinkArchiveActionSchema = z.object({
- action: z.enum(["allAndRePreserve", "allAndIgnore", "allBroken"]).optional(),
linkIds: z.array(z.number()).optional(),
});
@@ -303,6 +302,14 @@ export type LinkArchiveActionSchemaType = z.infer<
typeof LinkArchiveActionSchema
>;
+export const DeletePreservationsSchema = z.object({
+ action: z.enum(["allAndRePreserve", "allBroken"]),
+});
+
+export type DeletePreservationsSchemaType = z.infer<
+ typeof DeletePreservationsSchema
+>;
+
export const UpdateDashboardLayoutSchema = z.array(
z.object({
type: z.enum(DashboardSectionType),
diff --git a/packages/router/links.tsx b/packages/router/links.tsx
index c8bbf80c..e79cd7c0 100644
--- a/packages/router/links.tsx
+++ b/packages/router/links.tsx
@@ -538,7 +538,6 @@ const useArchiveAction = () => {
mutationFn: async (payload: LinkArchiveActionSchemaType) => {
const response = await fetch("/api/v1/links/archive", {
body: JSON.stringify({
- action: payload.action,
linkIds: payload.linkIds,
}),
method: "DELETE",
diff --git a/packages/router/worker.tsx b/packages/router/worker.tsx
new file mode 100644
index 00000000..5f9a8f82
--- /dev/null
+++ b/packages/router/worker.tsx
@@ -0,0 +1,51 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useSession } from "next-auth/react";
+import { WorkerStats } from "@linkwarden/types";
+import { DeletePreservationsSchemaType } from "@linkwarden/lib/schemaValidation";
+
+const useWorker = () => {
+ const { status } = useSession();
+
+ return useQuery({
+ queryKey: ["worker"],
+ queryFn: async () => {
+ const response = await fetch("/api/v1/worker");
+
+ if (!response.ok) throw new Error("Failed to fetch worker data.");
+ const data = await response.json();
+
+ return data.data as WorkerStats;
+ },
+ enabled: status === "authenticated",
+ });
+};
+
+const useDeletePreservations = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (payload: DeletePreservationsSchemaType) => {
+ const response = await fetch("/api/v1/worker/preservation", {
+ body: JSON.stringify({
+ action: payload.action,
+ }),
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.response);
+
+ return data;
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["links"] });
+ queryClient.invalidateQueries({ queryKey: ["dashboardData"] });
+ queryClient.invalidateQueries({ queryKey: ["worker"] });
+ },
+ });
+};
+
+export { useWorker, useDeletePreservations };
diff --git a/packages/types/global.ts b/packages/types/global.ts
index afc62318..260fc79c 100644
--- a/packages/types/global.ts
+++ b/packages/types/global.ts
@@ -189,3 +189,15 @@ export interface MobileData {
preferredBrowser: "app" | "system";
preferredCollection: CollectionIncludingMembersAndLinkCount | null;
}
+
+export interface WorkerStats {
+ link: {
+ pending: number;
+ done: number;
+ failed: number;
+ };
+ search: {
+ pending: number;
+ done: number;
+ };
+}