Skip to content

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

Start RSS Subscriptions

Isaac Wise991f12566fab
diff --git a/package.json b/package.json
index 442e74fc..d24c596c 100644
--- a/package.json
+++ b/package.json
@@ -77,6 +77,7 @@
"react-select": "^5.7.4",
"react-spinners": "^0.14.1",
"react-window": "^1.8.10",
+ "rss-parser": "^3.13.0",
"socks-proxy-agent": "^8.0.2",
"stripe": "^12.13.0",
"tailwind-merge": "^2.3.0",
@@ -102,4 +103,4 @@
"ts-node": "^10.9.2",
"typescript": "4.9.4"
}
-}
+}
\ No newline at end of file
diff --git a/pages/api/v1/user/rss/index.ts b/pages/api/v1/user/rss/index.ts
new file mode 100644
index 00000000..0eeb70c7
--- /dev/null
+++ b/pages/api/v1/user/rss/index.ts
@@ -0,0 +1,51 @@
+import { prisma } from "@/lib/api/db";
+import getPermission from "@/lib/api/getPermission";
+import setLinkCollection from "@/lib/api/setLinkCollection";
+import verifyUser from "@/lib/api/verifyUser";
+import { UsersAndCollections } from "@prisma/client";
+import { NextApiRequest, NextApiResponse } from "next";
+
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ const user = await verifyUser({ req, res });
+ if (!user) return;
+
+ if (req.method === "GET") {
+ const response = await prisma.rssSubscription.findMany({});
+
+ return res.status(200).json({ response });
+ }
+
+ if (req.method === "POST") {
+ console.log(req.body);
+ const { name, url, collectionId } = req.body;
+
+ const collectionIsAccessible = await getPermission({ userId: user.id, collectionId: Number(collectionId) });
+
+ const memberHasAccess = collectionIsAccessible?.members.some(
+ (e: UsersAndCollections) => e.userId === user.id
+ );
+
+ if (collectionIsAccessible?.ownerId !== user.id && !memberHasAccess) {
+ return res.status(403).json({ error: "You do not have permission to add a link to this collection" });
+ }
+
+ const response = await prisma.rssSubscription.create({
+ data: {
+ name,
+ url,
+ ownerId: user.id,
+ collection: {
+ connect: {
+ id: collectionId,
+ },
+ }
+ },
+ });
+
+ return res.status(200).json({ response });
+ }
+}
\ No newline at end of file
diff --git a/prisma/migrations/20241204062531_add_rss_subscriptions/migration.sql b/prisma/migrations/20241204062531_add_rss_subscriptions/migration.sql
new file mode 100644
index 00000000..f537a229
--- /dev/null
+++ b/prisma/migrations/20241204062531_add_rss_subscriptions/migration.sql
@@ -0,0 +1,16 @@
+-- CreateTable
+CREATE TABLE "RssSubscription" (
+ "id" SERIAL NOT NULL,
+ "url" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "lastBuildDate" TIMESTAMP(3),
+ "collectionId" INTEGER NOT NULL,
+ "ownerId" INTEGER NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "RssSubscription_pkey" PRIMARY KEY ("id")
+);
+
+-- AddForeignKey
+ALTER TABLE "RssSubscription" ADD CONSTRAINT "RssSubscription_collectionId_fkey" FOREIGN KEY ("collectionId") REFERENCES "Collection"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 89738ef4..3a2656e9 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -96,25 +96,26 @@ model PasswordResetToken {
}
model Collection {
- id Int @id @default(autoincrement())
- name String
- description String @default("")
- icon String?
- iconWeight String?
- color String @default("#0ea5e9")
- parentId Int?
- parent Collection? @relation("SubCollections", fields: [parentId], references: [id])
- subCollections Collection[] @relation("SubCollections")
- isPublic Boolean @default(false)
- owner User @relation(fields: [ownerId], references: [id])
- ownerId Int
- members UsersAndCollections[]
- createdBy User? @relation("CreatedCollections", fields: [createdById], references: [id])
- createdById Int?
- links Link[]
- createdAt DateTime @default(now())
- updatedAt DateTime @default(now()) @updatedAt
-
+ id Int @id @default(autoincrement())
+ name String
+ description String @default("")
+ icon String?
+ iconWeight String?
+ color String @default("#0ea5e9")
+ parentId Int?
+ parent Collection? @relation("SubCollections", fields: [parentId], references: [id])
+ subCollections Collection[] @relation("SubCollections")
+ isPublic Boolean @default(false)
+ owner User @relation(fields: [ownerId], references: [id])
+ ownerId Int
+ members UsersAndCollections[]
+ createdBy User? @relation("CreatedCollections", fields: [createdById], references: [id])
+ createdById Int?
+ links Link[]
+ rssSubscriptions RssSubscription[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+
@@index([ownerId])
}
@@ -189,7 +190,7 @@ model Subscription {
model AccessToken {
id Int @id @default(autoincrement())
- name String
+ name String
user User @relation(fields: [userId], references: [id])
userId Int
token String @unique
@@ -200,3 +201,15 @@ model AccessToken {
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
}
+
+model RssSubscription {
+ id Int @id @default(autoincrement())
+ url String
+ name String
+ lastBuildDate DateTime?
+ collection Collection @relation(fields: [collectionId], references: [id])
+ collectionId Int
+ ownerId Int
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+}
diff --git a/scripts/worker.ts b/scripts/worker.ts
index 81bd53ef..b3ed9ba6 100644
--- a/scripts/worker.ts
+++ b/scripts/worker.ts
@@ -2,6 +2,7 @@ import "dotenv/config";
import { Collection, Link, User } from "@prisma/client";
import { prisma } from "../lib/api/db";
import archiveHandler from "../lib/api/archiveHandler";
+import Parser from "rss-parser";
const args = process.argv.slice(2).join(" ");
@@ -135,23 +136,113 @@ async function processBatch() {
await Promise.allSettled(processingPromises);
}
-const intervalInSeconds = Number(process.env.ARCHIVE_SCRIPT_INTERVAL) || 10;
+async function fetchAndProcessRSS() {
+ const rssSubscriptions = await prisma.rssSubscription.findMany({});
+ const parser = new Parser();
+
+ rssSubscriptions.forEach(async (rssSubscription) => {
+ try {
+ const feed = await parser.parseURL(rssSubscription.url);
+
+ // If there's no lastBuildDate, process all feed items
+ if (!rssSubscription.lastBuildDate) {
+ feed.items.forEach(async (item) => {
+ await prisma.link.create({
+ data: {
+ name: item.title,
+ url: item.link,
+ type: "link",
+ createdBy: {
+ connect: {
+ id: rssSubscription.ownerId
+ }
+ },
+ collection: {
+ connect: {
+ id: rssSubscription.collectionId
+ }
+ }
+ }
+ });
+ });
+
+ await prisma.rssSubscription.update({
+ where: { id: rssSubscription.id },
+ data: { lastBuildDate: new Date(feed.lastBuildDate) }
+ });
+ } else if (rssSubscription.lastBuildDate && new Date(rssSubscription.lastBuildDate) < new Date(feed.lastBuildDate)) {
+ console.log(`Processing new feeds for ${rssSubscription.name}`);
+
+ const newItems = feed.items.filter(item => {
+ const itemPubDate = item.pubDate ? new Date(item.pubDate) : null;
+ return itemPubDate && itemPubDate > rssSubscription.lastBuildDate!; // We know lastBuildDate is not null here
+ });
+
+ newItems.forEach(async (item) => {
+ await prisma.link.create({
+ data: {
+ name: item.title,
+ url: item.link,
+ type: "link",
+ createdBy: {
+ connect: {
+ id: rssSubscription.ownerId
+ }
+ },
+ 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) }
+ });
+ }
+ } catch (error) {
+ console.error(
+ "\x1b[34m%s\x1b[0m",
+ `Error processing RSS feed ${rssSubscription.url}:`,
+ error
+ );
+ }
+ });
+}
function delay(sec: number) {
return new Promise((resolve) => setTimeout(resolve, sec * 1000));
}
-async function init() {
- console.log("\x1b[34m%s\x1b[0m", "Processing the links...");
+const POLLING_INTERVAL_MINUTES = Number(process.env.RSS_POLLING_INTERVAL_MINUTES) || 60; // Default to one hour if not set
+const pollingIntervalInSeconds = POLLING_INTERVAL_MINUTES * 60;
+
+async function startRSSPolling() {
while (true) {
- try {
- await processBatch();
- await delay(intervalInSeconds);
- } catch (error) {
- console.error("\x1b[34m%s\x1b[0m", "Error processing link:", error);
- await delay(intervalInSeconds);
- }
+ console.log("\x1b[34m%s\x1b[0m", "Starting RSS polling...");
+ await fetchAndProcessRSS();
+ await delay(pollingIntervalInSeconds);
+ }
+}
+
+const archiveIntervalInSeconds = Number(process.env.ARCHIVE_SCRIPT_INTERVAL) || 10;
+
+async function startArchiveProcessing() {
+ while (true) {
+ console.log("\x1b[34m%s\x1b[0m", "Starting archive processing...");
+ await processBatch();
+ await delay(archiveIntervalInSeconds);
}
}
-init();
+async function init() {
+ console.log("\x1b[34m%s\x1b[0m", "Initializing application...");
+ startRSSPolling();
+ startArchiveProcessing();
+}
+
+init();
\ No newline at end of file
diff --git a/yarn.lock b/yarn.lock
index 71ba16b2..86cfc7e4 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2024,6 +2024,11 @@
resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-5.1.2.tgz#07508b45797cb81ec3f273011b054cd0755eddca"
integrity sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==
+"@types/node-cron@^3.0.11":
+ version "3.0.11"
+ resolved "https://registry.yarnpkg.com/@types/node-cron/-/node-cron-3.0.11.tgz#70b7131f65038ae63cfe841354c8aba363632344"
+ integrity sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==
+
"@types/node-fetch@^2.6.10":
version "2.6.10"
resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.6.10.tgz#ff5c1ceacab782f2b7ce69957d38c1c27b0dc469"
@@ -3049,6 +3054,11 @@ enhanced-resolve@^5.10.0:
graceful-fs "^4.2.4"
tapable "^2.2.0"
+entities@^2.0.3:
+ version "2.2.0"
+ resolved "https://registry.yarnpkg.com/entities/-/entities-2.2.0.tgz#098dc90ebb83d8dffa089d55256b351d34c4da55"
+ integrity sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==
+
entities@^4.4.0:
version "4.5.0"
resolved "https://registry.yarnpkg.com/entities/-/entities-4.5.0.tgz#5d268ea5e7113ec74c4d033b79ea5a35a488fb48"
@@ -4703,6 +4713,13 @@ [email protected]:
resolved "https://registry.yarnpkg.com/node-bitmap/-/node-bitmap-0.0.1.tgz#180eac7003e0c707618ef31368f62f84b2a69091"
integrity sha512-Jx5lPaaLdIaOsj2mVLWMWulXF6GQVdyLvNSxmiYCvZ8Ma2hfKX0POoR2kgKOqz+oFsRreq0yYZjQ2wjE9VNzCA==
+node-cron@^3.0.3:
+ version "3.0.3"
+ resolved "https://registry.yarnpkg.com/node-cron/-/node-cron-3.0.3.tgz#c4bc7173dd96d96c50bdb51122c64415458caff2"
+ integrity sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==
+ dependencies:
+ uuid "8.3.2"
+
node-fetch@^2.6.1, node-fetch@^2.7.0:
version "2.7.0"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.7.0.tgz#d0f0fa6e3e2dc1d27efcd8ad99d550bda94d187d"
@@ -5547,6 +5564,14 @@ rrweb-cssom@^0.6.0:
resolved "https://registry.yarnpkg.com/rrweb-cssom/-/rrweb-cssom-0.6.0.tgz#ed298055b97cbddcdeb278f904857629dec5e0e1"
integrity sha512-APM0Gt1KoXBz0iIkkdB/kfvGOwC4UuJFeG/c+yV7wSc7q96cG/kJ0HiYCnzivD9SB53cLV1MlHFNfOuPaadYSw==
+rss-parser@^3.13.0:
+ version "3.13.0"
+ resolved "https://registry.yarnpkg.com/rss-parser/-/rss-parser-3.13.0.tgz#f1f83b0a85166b8310ec531da6fbaa53ff0f50f0"
+ integrity sha512-7jWUBV5yGN3rqMMj7CZufl/291QAhvrrGpDNE4k/02ZchL0npisiYYqULF71jCEKoIiHvK/Q2e6IkDwPziT7+w==
+ dependencies:
+ entities "^2.0.3"
+ xml2js "^0.5.0"
+
run-parallel@^1.1.9:
version "1.2.0"
resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.2.0.tgz#66d1368da7bdf921eb9d95bd1a9229e7f21a43ee"
@@ -6268,16 +6293,16 @@ util-deprecate@^1.0.1, util-deprecate@^1.0.2:
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==
[email protected], uuid@^8.3.2:
+ version "8.3.2"
+ resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2"
+ integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==
+
uuid@^3.3.2:
version "3.4.0"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee"
integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==
-uuid@^8.3.2:
- version "8.3.2"
- resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2"
- integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==
-
v8-compile-cache-lib@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf"
@@ -6461,6 +6486,14 @@ xml2js@^0.4.5:
sax ">=0.6.0"
xmlbuilder "~11.0.0"
+xml2js@^0.5.0:
+ version "0.5.0"
+ resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.5.0.tgz#d9440631fbb2ed800203fad106f2724f62c493b7"
+ integrity sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==
+ dependencies:
+ sax ">=0.6.0"
+ xmlbuilder "~11.0.0"
+
xmlbuilder@~11.0.0:
version "11.0.1"
resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-11.0.1.tgz#be9bae1c8a046e76b31127726347d0ad7002beb3"