Skip to content

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

RSS form

Isaac Wise266f834018f6
diff --git a/components/InputSelect/CollectionSelection.tsx b/components/InputSelect/CollectionSelection.tsx
index f53df37f..20ff0844 100644
--- a/components/InputSelect/CollectionSelection.tsx
+++ b/components/InputSelect/CollectionSelection.tsx
@@ -5,19 +5,21 @@ import { Options } from "./types";
import CreatableSelect from "react-select/creatable";
import Select from "react-select";
import { useCollections } from "@/hooks/store/collections";
+import clsx from "clsx";
type Props = {
onChange: any;
showDefaultValue?: boolean;
defaultValue?:
- | {
- label: string;
- value?: number;
- }
- | undefined;
+ | {
+ label: string;
+ value?: number;
+ }
+ | undefined;
creatable?: boolean;
autoFocus?: boolean;
onBlur?: any;
+ className?: string;
};
export default function CollectionSelection({
@@ -27,6 +29,7 @@ export default function CollectionSelection({
creatable = true,
autoFocus,
onBlur,
+ className
}: Props) {
const { data: collections = [] } = useCollections();
@@ -103,7 +106,7 @@ export default function CollectionSelection({
return (
<CreatableSelect
isClearable={false}
- className="react-select-container"
+ className={clsx("react-select-container", className)}
classNamePrefix="react-select"
onChange={onChange}
options={options}
@@ -114,14 +117,14 @@ export default function CollectionSelection({
components={{
Option: customOption,
}}
- // menuPosition="fixed"
+ // menuPosition="fixed"
/>
);
} else {
return (
<Select
isClearable={false}
- className="react-select-container"
+ className={clsx("react-select-container", className)}
classNamePrefix="react-select"
onChange={onChange}
options={options}
@@ -132,7 +135,7 @@ export default function CollectionSelection({
components={{
Option: customOption,
}}
- // menuPosition="fixed"
+ // menuPosition="fixed"
/>
);
}
diff --git a/components/ModalContent/NewRssSubscriptionModal.tsx b/components/ModalContent/NewRssSubscriptionModal.tsx
new file mode 100644
index 00000000..0b87b261
--- /dev/null
+++ b/components/ModalContent/NewRssSubscriptionModal.tsx
@@ -0,0 +1,98 @@
+import React, { useState } from "react";
+import Modal from "../Modal";
+import { useTranslation } from "next-i18next";
+import { useAddRssSubscription } from "@/hooks/store/rss";
+import toast from "react-hot-toast";
+import TextInput from "../TextInput";
+import CollectionSelection from "../InputSelect/CollectionSelection";
+
+type Props = {
+ onClose: Function;
+};
+
+export default function NewRssSubscriptionModal({ onClose }: Props) {
+ const { t } = useTranslation();
+ const addRssSubscription = useAddRssSubscription();
+ const [submitLoader, setSubmitLoader] = useState(false);
+
+ const [form, setForm] = useState({
+ name: "",
+ url: "",
+ collectionId: 0,
+ collectionName: ""
+ });
+
+ const submit = async () => {
+ if (submitLoader) return;
+
+ setSubmitLoader(true);
+
+ const load = toast.loading(t("creating"));
+
+ await addRssSubscription.mutateAsync(form, {
+ onSettled: (_, error) => {
+ setSubmitLoader(false);
+ toast.dismiss(load);
+
+ if (error) {
+ toast.error(error.message);
+ } else {
+ onClose();
+ toast.success(t("created"));
+ }
+ },
+ });
+ }
+
+ return (
+ <Modal toggleModal={onClose}>
+ <>
+ <p className="text-xl font-thin">{t("create_rss_subscription")}</p>
+
+ <div className="divider mb-3 mt-1"></div>
+ <div className="flex sm:flex-row flex-col gap-3 items-center">
+ <div className="w-full">
+ <label>{t("name")}</label>
+ <TextInput
+ type="text"
+ className="bg-base-200 mt-2"
+ value={form.name}
+ onChange={(e) => setForm({ ...form, name: e.target.value })}
+ />
+ </div>
+ <div className="w-full">
+ <label>{t("link")}</label>
+ <TextInput
+ type="text"
+ className="bg-base-200 mt-2"
+ value={form.url}
+ onChange={(e) => setForm({ ...form, url: e.target.value })}
+ />
+ </div>
+ </div>
+ <div className="w-full mt-3">
+ <label>{t("collection")}</label>
+ <CollectionSelection
+ className="mt-2"
+ onChange={(e: any) => {
+ if (e?.__isNew__) e.value = undefined;
+ setForm({
+ ...form,
+ collectionId: e?.value,
+ collectionName: e?.label,
+ });
+ }}
+ />
+ </div>
+ <div className="flex justify-end items-center mt-5">
+ <button
+ className="btn btn-accent dark:border-violet-400 text-white"
+ onClick={submit}
+ >
+ {t("create_token")}
+ </button>
+ </div>
+ </>
+ </Modal>
+ );
+}
diff --git a/hooks/store/rss.tsx b/hooks/store/rss.tsx
index 9260ddfe..8ac15153 100644
--- a/hooks/store/rss.tsx
+++ b/hooks/store/rss.tsx
@@ -45,7 +45,7 @@ const useAddRssSubscription = () => {
onSuccess: (data) => {
queryClient.setQueryData(
["rss-subscriptions"],
- (oldData: RssSubscription[]) => [...oldData, data.rssSubscription]
+ (oldData: RssSubscription[]) => [...oldData, data]
);
},
});
diff --git a/lib/api/controllers/links/postLink.ts b/lib/api/controllers/links/postLink.ts
index e292dfa0..5b0b0059 100644
--- a/lib/api/controllers/links/postLink.ts
+++ b/lib/api/controllers/links/postLink.ts
@@ -1,7 +1,8 @@
import { prisma } from "@/lib/api/db";
import fetchTitleAndHeaders from "@/lib/shared/fetchTitleAndHeaders";
import createFolder from "@/lib/api/storage/createFolder";
-import setLinkCollection from "../../setLinkCollection";
+import setCollection from "../../setCollection";
+
import {
PostLinkSchema,
PostLinkSchemaType,
@@ -16,16 +17,19 @@ export default async function postLink(
if (!dataValidation.success) {
return {
- response: `Error: ${
- dataValidation.error.issues[0].message
- } [${dataValidation.error.issues[0].path.join(", ")}]`,
+ response: `Error: ${dataValidation.error.issues[0].message
+ } [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
};
}
const link = dataValidation.data;
- const linkCollection = await setLinkCollection(link, userId);
+ const linkCollection = await setCollection({
+ userId,
+ collectionId: link.collection?.id,
+ collectionName: link.collection?.name,
+ });
if (!linkCollection)
return { response: "Collection is not accessible.", status: 400 };
diff --git a/lib/api/setCollection.ts b/lib/api/setCollection.ts
new file mode 100644
index 00000000..a7b34ec9
--- /dev/null
+++ b/lib/api/setCollection.ts
@@ -0,0 +1,96 @@
+import { prisma } from "./db";
+import getPermission from "./getPermission";
+import { UsersAndCollections } from "@prisma/client";
+
+type SetCollectionInput = {
+ userId: number;
+ collectionId?: number;
+ collectionName?: string;
+};
+
+const setCollection = async ({ userId, collectionId, collectionName }: SetCollectionInput) => {
+ if (collectionId) {
+ // Check if the collection exists
+ const existingCollection = await prisma.collection.findUnique({
+ where: { id: collectionId },
+ });
+
+ if (!existingCollection) return null;
+
+ // Check if the user has access to the collection
+ const collectionIsAccessible = await getPermission({
+ userId,
+ collectionId: existingCollection.id,
+ });
+
+ const memberHasAccess = collectionIsAccessible?.members.some(
+ (e: UsersAndCollections) => e.userId === userId && e.canCreate
+ );
+
+ if (!(collectionIsAccessible?.ownerId === userId || memberHasAccess)) {
+ return null;
+ }
+
+ return existingCollection;
+ }
+
+ if (collectionName) {
+ // If the collection name is "Unorganized", find or create it
+ if (collectionName === "Unorganized") {
+ const firstTopLevelUnorganizedCollection = await prisma.collection.findFirst({
+ where: {
+ name: "Unorganized",
+ ownerId: userId,
+ parentId: null,
+ },
+ });
+
+ if (firstTopLevelUnorganizedCollection) return firstTopLevelUnorganizedCollection;
+ }
+
+ // Create a new collection with the given name
+ const newCollection = await prisma.collection.create({
+ data: {
+ name: collectionName.trim(),
+ ownerId: userId,
+ createdById: userId,
+ },
+ });
+
+ // Update the user's collection order
+ await prisma.user.update({
+ where: { id: userId },
+ data: {
+ collectionOrder: {
+ push: newCollection.id,
+ },
+ },
+ });
+
+ return newCollection;
+ }
+
+ // Default behavior for "Unorganized" collection if neither collectionId nor collectionName is provided
+ const firstTopLevelUnorganizedCollection = await prisma.collection.findFirst({
+ where: {
+ name: "Unorganized",
+ ownerId: userId,
+ parentId: null,
+ },
+ });
+
+ if (firstTopLevelUnorganizedCollection) {
+ return firstTopLevelUnorganizedCollection;
+ }
+
+ return await prisma.collection.create({
+ data: {
+ name: "Unorganized",
+ ownerId: userId,
+ parentId: null,
+ createdById: userId,
+ },
+ });
+};
+
+export default setCollection;
diff --git a/lib/api/setLinkCollection.ts b/lib/api/setLinkCollection.ts
deleted file mode 100644
index f5270a75..00000000
--- a/lib/api/setLinkCollection.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { prisma } from "./db";
-import getPermission from "./getPermission";
-import { UsersAndCollections } from "@prisma/client";
-import { PostLinkSchemaType } from "../shared/schemaValidation";
-
-const setLinkCollection = async (link: PostLinkSchemaType, userId: number) => {
- if (link.collection?.id && typeof link.collection?.id === "number") {
- const existingCollection = await prisma.collection.findUnique({
- where: {
- id: link.collection.id,
- },
- });
-
- if (!existingCollection) return null;
-
- const collectionIsAccessible = await getPermission({
- userId,
- collectionId: existingCollection.id,
- });
-
- const memberHasAccess = collectionIsAccessible?.members.some(
- (e: UsersAndCollections) => e.userId === userId && e.canCreate
- );
-
- if (!(collectionIsAccessible?.ownerId === userId || memberHasAccess))
- return null;
-
- return existingCollection;
- } else if (link.collection?.name) {
- if (link.collection.name === "Unorganized") {
- const firstTopLevelUnorganizedCollection =
- await prisma.collection.findFirst({
- where: {
- name: "Unorganized",
- ownerId: userId,
- parentId: null,
- },
- });
-
- if (firstTopLevelUnorganizedCollection)
- return firstTopLevelUnorganizedCollection;
- }
-
- const newCollection = await prisma.collection.create({
- data: {
- name: link.collection.name.trim(),
- ownerId: userId,
- createdById: userId,
- },
- });
-
- await prisma.user.update({
- where: {
- id: userId,
- },
- data: {
- collectionOrder: {
- push: newCollection.id,
- },
- },
- });
-
- return newCollection;
- } else {
- const firstTopLevelUnorganizedCollection =
- await prisma.collection.findFirst({
- where: {
- name: "Unorganized",
- ownerId: userId,
- parentId: null,
- },
- });
-
- if (firstTopLevelUnorganizedCollection)
- return firstTopLevelUnorganizedCollection;
- else
- return await prisma.collection.create({
- data: {
- name: "Unorganized",
- ownerId: userId,
- parentId: null,
- createdById: userId,
- },
- });
- }
-};
-
-export default setLinkCollection;
diff --git a/lib/shared/schemaValidation.ts b/lib/shared/schemaValidation.ts
index 11d6b92b..a3949488 100644
--- a/lib/shared/schemaValidation.ts
+++ b/lib/shared/schemaValidation.ts
@@ -41,12 +41,12 @@ export const PostUserSchema = () => {
username: emailEnabled
? z.string().optional()
: z
- .string()
- .trim()
- .toLowerCase()
- .min(3)
- .max(50)
- .regex(/^[a-z0-9_-]{3,50}$/),
+ .string()
+ .trim()
+ .toLowerCase()
+ .min(3)
+ .max(50)
+ .regex(/^[a-z0-9_-]{3,50}$/),
invite: z.boolean().optional(),
});
};
@@ -209,3 +209,11 @@ export const UpdateTagSchema = z.object({
});
export type UpdateTagSchemaType = z.infer<typeof UpdateTagSchema>;
+
+export const PostRssSubscriptionSchema = z.object({
+ name: z.string(),
+ url: z.string().url(),
+ collectionId: z.number().optional(),
+ collectionName: z.string().optional(),
+});
+
diff --git a/pages/api/v1/user/rss/index.ts b/pages/api/v1/user/rss/index.ts
index 4c54cb17..88ad2223 100644
--- a/pages/api/v1/user/rss/index.ts
+++ b/pages/api/v1/user/rss/index.ts
@@ -1,6 +1,8 @@
import { prisma } from "@/lib/api/db";
import getPermission from "@/lib/api/getPermission";
+import setCollection from "@/lib/api/setCollection";
import verifyUser from "@/lib/api/verifyUser";
+import { PostRssSubscriptionSchema } from "@/lib/shared/schemaValidation";
import { UsersAndCollections } from "@prisma/client";
import { NextApiRequest, NextApiResponse } from "next";
@@ -26,18 +28,24 @@ export default async function handler(
}
if (req.method === "POST") {
- const { name, url, collectionId } = req.body;
+ const dataValidation = PostRssSubscriptionSchema.safeParse(req.body);
- const collectionIsAccessible = await getPermission({
+ if (!dataValidation.success) {
+ return res.status(400).json({
+ response: `Error: ${dataValidation.error.issues[0].message
+ } [${dataValidation.error.issues[0].path.join(", ")}]`,
+ });
+ }
+
+ const { name, url, collectionId, collectionName } = dataValidation.data;
+
+ const linkCollection = await setCollection({
userId: user.id,
- collectionId: Number(collectionId),
+ collectionId: collectionId,
+ collectionName: collectionName,
});
- const memberHasAccess = collectionIsAccessible?.members.some(
- (e: UsersAndCollections) => e.userId === user.id
- );
-
- if (collectionIsAccessible?.ownerId !== user.id && !memberHasAccess) {
+ if (!linkCollection) {
return res
.status(403)
.json({
@@ -46,6 +54,20 @@ export default async function handler(
});
}
+ const existingRssSubscription = await prisma.rssSubscription.findFirst({
+ where: {
+ name: name,
+ ownerId: user.id,
+ },
+ });
+
+ if (existingRssSubscription) {
+ return {
+ response: "RSS Subscription with that name already exists.",
+ status: 400,
+ };
+ }
+
const response = await prisma.rssSubscription.create({
data: {
name,
@@ -54,7 +76,7 @@ export default async function handler(
lastBuildDate: new Date(),
collection: {
connect: {
- id: collectionId,
+ id: linkCollection.id,
},
},
},
diff --git a/pages/settings/rss-subscriptions.tsx b/pages/settings/rss-subscriptions.tsx
index a5489feb..f6eb8282 100644
--- a/pages/settings/rss-subscriptions.tsx
+++ b/pages/settings/rss-subscriptions.tsx
@@ -5,13 +5,14 @@ import { useRssSubscriptions } from "@/hooks/store/rss";
import DeleteRssSubscriptionModal from "@/components/ModalContent/DeleteRssSubscriptionModal";
import { useState } from "react";
import { RssSubscription } from "@prisma/client";
-import Link from "next/link";
+import NewRssSubscriptionModal from "@/components/ModalContent/NewRssSubscriptionModal";
export default function RssSubscriptions() {
const { t } = useTranslation();
const { data: rssSubscriptions = [] } = useRssSubscriptions();
const [deleteSubscriptionModal, setDeleteSubscriptionModal] = useState(false);
+ const [newSubscriptionModal, setNewSubscriptionModal] = useState(false);
const [selectedSubscription, setSelectedSubscription] =
useState<RssSubscription | null>(null);
@@ -20,6 +21,8 @@ export default function RssSubscriptions() {
setDeleteSubscriptionModal(true);
};
+ console.log(rssSubscriptions);
+
return (
<SettingsLayout>
<p className="capitalize text-3xl font-thin inline">
@@ -32,9 +35,9 @@ export default function RssSubscriptions() {
<button
className={`btn ml-auto btn-accent dark:border-violet-400 text-white tracking-wider w-fit flex items-center gap-2`}
- // onClick={() => {
- // setNewTokenModal(true);
- // }}
+ onClick={() => {
+ setNewSubscriptionModal(true);
+ }}
>
{t("new_rss_subscription")}
</button>
@@ -53,14 +56,14 @@ export default function RssSubscriptions() {
<tr key={i}>
<td>{rssSubscription.name}</td>
<td>{rssSubscription.url}</td>
- <td>
+ {/* <td>
<Link
className="hover:underline"
href={`/collections/${rssSubscription.collectionId}`}
>
{rssSubscription.collection.name}
</Link>
- </td>
+ </td> */}
<td>
<button
className="btn btn-sm btn-ghost btn-square hover:bg-red-500"
@@ -75,6 +78,9 @@ export default function RssSubscriptions() {
</table>
)}
</div>
+ {newSubscriptionModal && (
+ <NewRssSubscriptionModal onClose={() => setNewSubscriptionModal(false)} />
+ )}
{deleteSubscriptionModal && selectedSubscription && (
<DeleteRssSubscriptionModal
rssSubscription={selectedSubscription}
diff --git a/public/locales/en/common.json b/public/locales/en/common.json
index e0de17d3..d1038f21 100644
--- a/public/locales/en/common.json
+++ b/public/locales/en/common.json
@@ -434,5 +434,6 @@
"rss_subscriptions_desc": "RSS Subscriptions are a way to keep up with your favorite websites and blogs. Linkwarden will automatically fetch the latest articles from the feeds you provide.",
"rss_deletion_confirmation": "Are you sure you want to delete this RSS Subscription?",
"new_rss_subscription": "New RSS Subscription",
- "rss_subscription_deleted": "RSS Subscription deleted!"
+ "rss_subscription_deleted": "RSS Subscription deleted!",
+ "create_rss_subscription": "Create RSS Subscription"
}
\ No newline at end of file
diff --git a/scripts/worker.ts b/scripts/worker.ts
index b1914e6b..9ca91c8a 100644
--- a/scripts/worker.ts
+++ b/scripts/worker.ts
@@ -148,9 +148,7 @@ async function fetchAndProcessRSS() {
rssSubscription.lastBuildDate &&
new Date(rssSubscription.lastBuildDate) < new Date(feed.lastBuildDate)
) {
- console.log(
- `Processing new RSS feed items for ${rssSubscription.name}`
- );
+ console.log("\x1b[34m%s\x1b[0m", `Processing new RSS feed items for ${rssSubscription.name}`);
const newItems = feed.items.filter((item) => {
const itemPubDate = item.pubDate ? new Date(item.pubDate) : null;