⚡️⚡️⚡️ 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
Now limiting the read size for imports in a configuration compatible way to the previous implementation
dereulenspiegel160845319f1c
diff --git a/components/ImportDropdown.tsx b/components/ImportDropdown.tsxindex a980bf9c..51e5f068 100644--- a/components/ImportDropdown.tsx+++ b/components/ImportDropdown.tsx@@ -5,108 +5,100 @@ import { useTranslation } from "next-i18next";import { dropdownTriggerer } from "@/lib/client/utils";type Props = {};-const ImportDropdown = ({ }: Props) => {- const { t } = useTranslation();- return (- <div className="dropdown dropdown-bottom">- <div- tabIndex={0}- role="button"- onMouseDown={dropdownTriggerer}- className="inline-flex items-center gap-2 text-sm btn bg-neutral-content text-secondary-foreground hover:bg-neutral-content/80 border border-neutral/30 hover:border hover:border-neutral/30"- id="import-dropdown"- >- <i className="bi-cloud-upload text-xl duration-100"></i>- <p>{t("import_links")}</p>- </div>- <ul className="shadow menu dropdown-content z-[1] bg-base-200 border border-neutral-content rounded-box mt-1">- <li>- <label- tabIndex={0}- role="button"- htmlFor="import-linkwarden-file"- title={t("from_linkwarden")}- className="whitespace-nowrap"- >- {t("from_linkwarden")}- <input- type="file"- name="photo"- id="import-linkwarden-file"- accept=".json"- className="hidden"- onChange={(e) =>- importBookmarks(e, MigrationFormat.linkwarden)- }- />- </label>- </li>- <li>- <label- tabIndex={0}- role="button"- htmlFor="import-html-file"- title={t("from_html")}- className="whitespace-nowrap"- >- {t("from_html")}- <input- type="file"- name="photo"- id="import-html-file"- accept=".html"- className="hidden"- onChange={(e) =>- importBookmarks(e, MigrationFormat.htmlFile)- }- />- </label>- </li>- <li>- <label- tabIndex={0}- role="button"- htmlFor="import-wallabag-file"- title={t("from_wallabag")}- className="whitespace-nowrap"- >- {t("from_wallabag")}- <input- type="file"- name="photo"- id="import-wallabag-file"- accept=".json"- className="hidden"- onChange={(e) =>- importBookmarks(e, MigrationFormat.wallabag)- }- />- </label>- </li>- <li>- <label- tabIndex={0}- role="button"- htmlFor="import-omnivore-file"- title={t("from_omnivore")}- className="whitespace-nowrap"- >- {t("from_omnivore")}- <input- type="file"- name="photo"- id="import-omnivore-file"- accept=".zip"- className="hidden"- onChange={(e) =>- importBookmarks(e, MigrationFormat.omnivore)- }- />- </label>- </li>- </ul>- </div>- );+const ImportDropdown = ({}: Props) => {+ const { t } = useTranslation();+ return (+ <div className="dropdown dropdown-bottom">+ <div+ tabIndex={0}+ role="button"+ onMouseDown={dropdownTriggerer}+ className="inline-flex items-center gap-2 text-sm btn bg-neutral-content text-secondary-foreground hover:bg-neutral-content/80 border border-neutral/30 hover:border hover:border-neutral/30"+ id="import-dropdown"+ >+ <i className="bi-cloud-upload text-xl duration-100"></i>+ <p>{t("import_links")}</p>+ </div>+ <ul className="shadow menu dropdown-content z-[1] bg-base-200 border border-neutral-content rounded-box mt-1">+ <li>+ <label+ tabIndex={0}+ role="button"+ htmlFor="import-linkwarden-file"+ title={t("from_linkwarden")}+ className="whitespace-nowrap"+ >+ {t("from_linkwarden")}+ <input+ type="file"+ name="photo"+ id="import-linkwarden-file"+ accept=".json"+ className="hidden"+ onChange={(e) => importBookmarks(e, MigrationFormat.linkwarden)}+ />+ </label>+ </li>+ <li>+ <label+ tabIndex={0}+ role="button"+ htmlFor="import-html-file"+ title={t("from_html")}+ className="whitespace-nowrap"+ >+ {t("from_html")}+ <input+ type="file"+ name="photo"+ id="import-html-file"+ accept=".html"+ className="hidden"+ onChange={(e) => importBookmarks(e, MigrationFormat.htmlFile)}+ />+ </label>+ </li>+ <li>+ <label+ tabIndex={0}+ role="button"+ htmlFor="import-wallabag-file"+ title={t("from_wallabag")}+ className="whitespace-nowrap"+ >+ {t("from_wallabag")}+ <input+ type="file"+ name="photo"+ id="import-wallabag-file"+ accept=".json"+ className="hidden"+ onChange={(e) => importBookmarks(e, MigrationFormat.wallabag)}+ />+ </label>+ </li>+ <li>+ <label+ tabIndex={0}+ role="button"+ htmlFor="import-omnivore-file"+ title={t("from_omnivore")}+ className="whitespace-nowrap"+ >+ {t("from_omnivore")}+ <input+ type="file"+ name="photo"+ id="import-omnivore-file"+ accept=".zip"+ className="hidden"+ onChange={(e) => importBookmarks(e, MigrationFormat.omnivore)}+ />+ </label>+ </li>+ </ul>+ </div>+ );};-export default ImportDropdown;\ No newline at end of file+export default ImportDropdown;diff --git a/lib/api/controllers/migration/importFromHTMLFile.ts b/lib/api/controllers/migration/importFromHTMLFile.tsindex 94a19936..d6e32069 100644--- a/lib/api/controllers/migration/importFromHTMLFile.ts+++ b/lib/api/controllers/migration/importFromHTMLFile.ts@@ -3,7 +3,7 @@ import createFolder from "@/lib/api/storage/createFolder";import { JSDOM } from "jsdom";import { parse, Node, Element, TextNode } from "himalaya";import { hasPassedLimit } from "../../verifyCapacity";-import { Readable } from 'stream';+import { Readable } from "stream";import streamToBlob from "stream-to-blob";export default async function importFromHTMLFile(@@ -170,10 +170,10 @@ const createCollection = async (name: collectionName,parent: parentId? {- connect: {- id: parentId,- },- }+ connect: {+ id: parentId,+ },+ }: undefined,owner: {connect: {@@ -228,25 +228,25 @@ const createLink = async (tags:tags && tags[0]? {- connectOrCreate: tags.map((tag: string) => {- return {- where: {- name_ownerId: {- name: tag.trim(),- ownerId: userId,+ connectOrCreate: tags.map((tag: string) => {+ return {+ where: {+ name_ownerId: {+ name: tag.trim(),+ ownerId: userId,+ },},- },- create: {- name: tag.trim(),- owner: {- connect: {- id: userId,+ create: {+ name: tag.trim(),+ owner: {+ connect: {+ id: userId,+ },},},- },- };- }),- }+ };+ }),+ }: undefined,importDate: importDate || undefined,},diff --git a/lib/api/controllers/migration/importFromLinkwarden.ts b/lib/api/controllers/migration/importFromLinkwarden.tsindex 374b687c..9ade75d8 100644--- a/lib/api/controllers/migration/importFromLinkwarden.ts+++ b/lib/api/controllers/migration/importFromLinkwarden.ts@@ -2,7 +2,7 @@ import { prisma } from "@/lib/api/db";import { Backup } from "@/types/global";import createFolder from "@/lib/api/storage/createFolder";import { hasPassedLimit } from "../../verifyCapacity";-import { Readable } from 'stream';+import { Readable } from "stream";import streamToBlob from "stream-to-blob";export default async function importFromLinkwarden(diff --git a/lib/api/controllers/migration/importFromOmnivore.ts b/lib/api/controllers/migration/importFromOmnivore.tsindex aa06dbe5..83ba8357 100644--- a/lib/api/controllers/migration/importFromOmnivore.ts+++ b/lib/api/controllers/migration/importFromOmnivore.ts@@ -4,126 +4,122 @@ import { JSDOM } from "jsdom";import { parse, Node, Element, TextNode } from "himalaya";import { hasPassedLimit } from "../../verifyCapacity";import { ZipReader, BlobReader, TextWriter } from "@zip.js/zip.js";-import { Readable } from 'stream';+import { Readable } from "stream";import streamToBlob from "stream-to-blob";type OmnivoreMetadata = {- id: string;- slug: string;- title: string;- description: string;- author?: string;- url: string;- state: string;- readingProgress: number;- thumbnail: string;- labels: string[];- savedAt: Date;- updatedAt: Date;- publishedAt?: Date;-}[]+ id: string;+ slug: string;+ title: string;+ description: string;+ author?: string;+ url: string;+ state: string;+ readingProgress: number;+ thumbnail: string;+ labels: string[];+ savedAt: Date;+ updatedAt: Date;+ publishedAt?: Date;+}[];export default async function importFromOmnivore(- userId: number,- rawStream: Readable+ userId: number,+ rawStream: Readable) {- const rawData: Blob = await streamToBlob(rawStream);- const zipFileReader = new BlobReader(rawData);- const importArchive = new ZipReader(zipFileReader);+ const rawData: Blob = await streamToBlob(rawStream);+ const zipFileReader = new BlobReader(rawData);+ const importArchive = new ZipReader(zipFileReader);- const zipEntries = await importArchive.getEntries();+ const zipEntries = await importArchive.getEntries();- await prisma.$transaction(- async () => {- const omnivoreCollection = await prisma.collection.create({- data: {- owner: {- connect: {- id: userId- }- },- name: "Omnivore Imports",- createdBy: {- connect: {- id: userId- }- }- }- });-- createFolder({ filePath: `archives/${omnivoreCollection.id}` });+ await prisma.$transaction(async () => {+ const omnivoreCollection = await prisma.collection.create({+ data: {+ owner: {+ connect: {+ id: userId,+ },+ },+ name: "Omnivore Imports",+ createdBy: {+ connect: {+ id: userId,+ },+ },+ },+ });- for (const entry of zipEntries) {+ createFolder({ filePath: `archives/${omnivoreCollection.id}` });- if (entry.filename.startsWith("metadata_")) {- console.log(`Getting metadata from ${entry.filename}`);+ for (const entry of zipEntries) {+ if (entry.filename.startsWith("metadata_")) {+ console.log(`Getting metadata from ${entry.filename}`);- const jsonWriter = new TextWriter();- const jsonMetadatString: string = await entry.getData(jsonWriter);- const metadata: OmnivoreMetadata = JSON.parse(jsonMetadatString);+ const jsonWriter = new TextWriter();+ const jsonMetadatString: string = await entry.getData(jsonWriter);+ const metadata: OmnivoreMetadata = JSON.parse(jsonMetadatString);- const hasTooManyLinks = await hasPassedLimit(userId, metadata.length);- if (hasTooManyLinks) {- return {- response: `Your subscription have reached the maximum number of links allowed.`,- status: 400,- };- }+ const hasTooManyLinks = await hasPassedLimit(userId, metadata.length);+ if (hasTooManyLinks) {+ return {+ response: `Your subscription have reached the maximum number of links allowed.`,+ status: 400,+ };+ }- for (const data of metadata) {- try {- new URL(data.url.trim());- } catch (err) {- continue;- }- console.log("Extracting text data");- //const textData = await importArchive.get(`content/${data.slug}.html`)?.get_string()+ for (const data of metadata) {+ try {+ new URL(data.url.trim());+ } catch (err) {+ continue;+ }+ console.log("Extracting text data");+ //const textData = await importArchive.get(`content/${data.slug}.html`)?.get_string()- await prisma.link.create(- {- data: {- url: data.url.trim(),- name: data.title.trim().slice(0, 254),- importDate: data.savedAt,- description: data.description ? data.description : "",- //textContent: textData, // TODO maybe we need to cleanup the html- collection: {- connect: {- id: omnivoreCollection.id,- },- },- createdBy: {- connect: {- id: userId,- },- },- tags: data.labels && data.labels[0]- ? {- connectOrCreate: data.labels.map((label) => ({- where: {- name_ownerId: {- name: label?.trim().slice(0, 49),- ownerId: userId,- },- },- create: {- name: label?.trim().slice(0, 49),- owner: {- connect: {- id: userId,- },- },- },- })),- }- : undefined,- }- }- )+ await prisma.link.create({+ data: {+ url: data.url.trim(),+ name: data.title.trim().slice(0, 254),+ importDate: data.savedAt,+ description: data.description ? data.description : "",+ //textContent: textData, // TODO maybe we need to cleanup the html+ collection: {+ connect: {+ id: omnivoreCollection.id,+ },+ },+ createdBy: {+ connect: {+ id: userId,+ },+ },+ tags:+ data.labels && data.labels[0]+ ? {+ connectOrCreate: data.labels.map((label) => ({+ where: {+ name_ownerId: {+ name: label?.trim().slice(0, 49),+ ownerId: userId,+ },+ },+ create: {+ name: label?.trim().slice(0, 49),+ owner: {+ connect: {+ id: userId,+ },+ },+ },+ })),}- }- }+ : undefined,+ },+ });}- );- return { response: "Success.", status: 200 };+ }+ }+ });+ return { response: "Success.", status: 200 };}diff --git a/lib/api/controllers/migration/importFromWallabag.ts b/lib/api/controllers/migration/importFromWallabag.tsindex 0450c8f5..5911caf4 100644--- a/lib/api/controllers/migration/importFromWallabag.ts+++ b/lib/api/controllers/migration/importFromWallabag.ts@@ -1,7 +1,7 @@import { prisma } from "@/lib/api/db";import createFolder from "@/lib/api/storage/createFolder";import { hasPassedLimit } from "../../verifyCapacity";-import { Readable } from 'stream';+import { Readable } from "stream";import streamToBlob from "stream-to-blob";type WallabagBackup = {@@ -99,23 +99,23 @@ export default async function importFromWallabag(tags:link.tags && link.tags[0]? {- connectOrCreate: link.tags.map((tag) => ({- where: {- name_ownerId: {- name: tag?.trim().slice(0, 49),- ownerId: userId,+ connectOrCreate: link.tags.map((tag) => ({+ where: {+ name_ownerId: {+ name: tag?.trim().slice(0, 49),+ ownerId: userId,+ },},- },- create: {- name: tag?.trim().slice(0, 49),- owner: {- connect: {- id: userId,+ create: {+ name: tag?.trim().slice(0, 49),+ owner: {+ connect: {+ id: userId,+ },},},- },- })),- }+ })),+ }: undefined,},});diff --git a/lib/client/importBookmarks.ts b/lib/client/importBookmarks.tsindex cbac2cce..7089b00d 100644--- a/lib/client/importBookmarks.ts+++ b/lib/client/importBookmarks.ts@@ -2,60 +2,63 @@ import { MigrationFormat } from "@/types/global";import { toast } from "react-hot-toast";const importBookmarks = async (- e: React.ChangeEvent<HTMLInputElement>,- format: MigrationFormat+ e: React.ChangeEvent<HTMLInputElement>,+ format: MigrationFormat) => {- const file: File | null = e.target.files && e.target.files[0];-- if (file) {- const reader = new FileReader();-- reader.readAsArrayBuffer(file);- reader.onload = async function (e) {- const load = toast.loading("Importing...");-- try {- const migrationFormatName = MigrationFormat[format];- const response = await fetch(`/api/v1/migration/${migrationFormatName}`, {- method: "POST",- body: e.target?.result as ArrayBuffer,- headers: { "Content-Type": "application/octet-stream" },- });-- if (!response.ok) {- const errorData = await response.json();- toast.dismiss(load);-- toast.error(- errorData.response ||- "Failed to import bookmarks. Please try again."- );- return;- }-- await response.json();- toast.dismiss(load);- toast.success("Imported the Bookmarks! Reloading the page...");-- setTimeout(() => {- location.reload();- }, 2000);- } catch (error) {- console.error("Request failed", error);- toast.dismiss(load);- toast.error(- "An error occurred while importing bookmarks. Please check the logs for more info."- );- }- };-- reader.onerror = function (e) {- console.log("Error reading file:", e);- toast.error(- "Failed to read the file. Please make sure the file is correct and try again."- );- };- }+ const file: File | null = e.target.files && e.target.files[0];++ if (file) {+ const reader = new FileReader();++ reader.readAsArrayBuffer(file);+ reader.onload = async function (e) {+ const load = toast.loading("Importing...");++ try {+ const migrationFormatName = MigrationFormat[format];+ const response = await fetch(+ `/api/v1/migration/${migrationFormatName}`,+ {+ method: "POST",+ body: e.target?.result as ArrayBuffer,+ headers: { "Content-Type": "application/octet-stream" },+ }+ );++ if (!response.ok) {+ const errorData = await response.json();+ toast.dismiss(load);++ toast.error(+ errorData.response ||+ "Failed to import bookmarks. Please try again."+ );+ return;+ }++ await response.json();+ toast.dismiss(load);+ toast.success("Imported the Bookmarks! Reloading the page...");++ setTimeout(() => {+ location.reload();+ }, 2000);+ } catch (error) {+ console.error("Request failed", error);+ toast.dismiss(load);+ toast.error(+ "An error occurred while importing bookmarks. Please check the logs for more info."+ );+ }+ };++ reader.onerror = function (e) {+ console.log("Error reading file:", e);+ toast.error(+ "Failed to read the file. Please make sure the file is correct and try again."+ );+ };+ }};-export default importBookmarks;\ No newline at end of file+export default importBookmarks;diff --git a/package.json b/package.jsonindex 4dbcf7e2..8101411c 100644--- a/package.json+++ b/package.json@@ -80,6 +80,7 @@"react-spinners": "^0.14.1","react-window": "^1.8.10","socks-proxy-agent": "^8.0.2",+ "stream-size": "^0.0.6","stream-to-blob": "^2.0.1","stripe": "^12.13.0","tailwind-merge": "^2.3.0",diff --git a/pages/api/v1/migration/[format].ts b/pages/api/v1/migration/[format].tsindex 9246c79c..212ea379 100644--- a/pages/api/v1/migration/[format].ts+++ b/pages/api/v1/migration/[format].ts@@ -6,19 +6,21 @@ import { MigrationFormat, MigrationRequest } from "@/types/global";import verifyUser from "@/lib/api/verifyUser";import importFromWallabag from "@/lib/api/controllers/migration/importFromWallabag";import importFromOmnivore from "@/lib/api/controllers/migration/importFromOmnivore";-import { Readable } from 'stream';+import { Readable } from "stream";+import getSizeTransform from "stream-size";export const config = {api: {- // bodyParser: {- // sizeLimit: process.env.IMPORT_LIMIT- // ? process.env.IMPORT_LIMIT + "mb"- // : "10mb",- // },+ // Disable body parser to be able to process binary uploadsbodyParser: false,},};+const IMPORT_SIZE_LIMIT_BYTES =+ parseInt(process.env.IMPORT_LIMIT ? process.env.IMPORT_LIMIT : "10") *+ 1024 *+ 1024;+export default async function users(req: NextApiRequest, res: NextApiResponse) {const user = await verifyUser({ req, res });if (!user) return;@@ -30,9 +32,13 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {"This action is disabled because this is a read-only demo of Linkwarden.",});- const importData: Readable = Readable.from(req); // TODO have something like a limit reader- console.log(`received body type ${typeof importData}`);- const importFormatName = String(req.query.format) as keyof typeof MigrationFormat;+ const unlimitedReadable: Readable = Readable.from(req);+ const importData = unlimitedReadable.pipe(+ getSizeTransform(IMPORT_SIZE_LIMIT_BYTES)+ );+ const importFormatName = String(+ req.query.format+ ) as keyof typeof MigrationFormat;const importFormat: MigrationFormat = MigrationFormat[importFormatName];let data;diff --git a/pages/dashboard.tsx b/pages/dashboard.tsxindex 4fdd9b9c..acc18b64 100644--- a/pages/dashboard.tsx+++ b/pages/dashboard.tsx@@ -51,7 +51,7 @@ export default function Dashboard() {account.referredBy === null &&// if user is using Linkwarden for more than 3 daysnew Date().getTime() - new Date(account.createdAt).getTime() >- 3 * 24 * 60 * 60 * 1000+ 3 * 24 * 60 * 60 * 1000) {setTimeout(() => {setShowsSurveyModal(true);@@ -217,7 +217,6 @@ export default function Dashboard() {</div><ImportDropdown />-</div></div>)}diff --git a/pages/register.tsx b/pages/register.tsxindex fdb7e966..282558b4 100644--- a/pages/register.tsx+++ b/pages/register.tsx@@ -149,8 +149,8 @@ export default function Register({text={process.env.NEXT_PUBLIC_STRIPE? t("trial_offer_desc", {- count: Number(process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS || 14),- })+ count: Number(process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS || 14),+ }): t("register_desc")}data-testid="registration-form"diff --git a/pages/settings/account.tsx b/pages/settings/account.tsxindex 16463458..db54d2f0 100644--- a/pages/settings/account.tsx+++ b/pages/settings/account.tsx@@ -31,19 +31,19 @@ export default function Account() {!objectIsEmpty(account)? account: ({- // @ts-ignore- id: null,- name: "",- username: "",- email: "",- emailVerified: null,- password: undefined,- image: "",- isPrivate: true,- // @ts-ignore- createdAt: null,- whitelistedUsers: [],- } as unknown as AccountSettings)+ // @ts-ignore+ id: null,+ name: "",+ username: "",+ email: "",+ emailVerified: null,+ password: undefined,+ image: "",+ isPrivate: true,+ // @ts-ignore+ createdAt: null,+ whitelistedUsers: [],+ } as unknown as AccountSettings));const { t } = useTranslation();diff --git a/yarn.lock b/yarn.lockindex 4c1fcbf8..87879fc0 100644--- a/yarn.lock+++ b/yarn.lock@@ -5755,6 +5755,11 @@ stop-iteration-iterator@^1.0.0:dependencies:internal-slot "^1.0.4"+stream-size@^0.0.6:+ version "0.0.6"+ resolved "https://registry.yarnpkg.com/stream-size/-/stream-size-0.0.6.tgz#05d7132e2d2fdb91b533a6e50aff882f040d7679"+ integrity sha512-TZsxxZzKPkiD7fxcKx0Ze9s0+WnGGbX1yWZNoXXmN6YjyEu/62pYkLKo7P627N27BT9kI93ZfZAx38brr/hq+Q==+stream-to-blob@^2.0.1:version "2.0.1"resolved "https://registry.yarnpkg.com/stream-to-blob/-/stream-to-blob-2.0.1.tgz#59ab71d7a7f0bfb899570e886e44d39f4ac4381a"