⚡️⚡️⚡️ 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
added collaboration mode for collections
Danielcc8e8dbe9aa0
diff --git a/components/Modal/AddCollection.tsx b/components/Modal/AddCollection.tsxindex d2674b77..899e2822 100644--- a/components/Modal/AddCollection.tsx+++ b/components/Modal/AddCollection.tsx@@ -5,9 +5,10 @@import React, { useState } from "react";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { faPlus } from "@fortawesome/free-solid-svg-icons";+import { faClose, faPlus } from "@fortawesome/free-solid-svg-icons";import useCollectionStore from "@/store/collections";import { NewCollection } from "@/types/global";+import { useSession } from "next-auth/react";type Props = {toggleCollectionModal: Function;@@ -17,10 +18,15 @@ export default function AddCollection({ toggleCollectionModal }: Props) {const [newCollection, setNewCollection] = useState<NewCollection>({name: "",description: "",+ members: [],});+ const [memberEmail, setMemberEmail] = useState("");+const { addCollection } = useCollectionStore();+ const session = useSession();+const submitCollection = async () => {console.log(newCollection);@@ -29,6 +35,14 @@ export default function AddCollection({ toggleCollectionModal }: Props) {if (response) toggleCollectionModal();};+ const getUserByEmail = async (email: string) => {+ const response = await fetch(`/api/routes/users?email=${email}`);++ const data = await response.json();++ return data.response;+ };+return (<div className="flex flex-col gap-3 sm:w-[35rem] w-80"><p className="font-bold text-sky-300 mb-2 text-center">New Collection</p>@@ -59,6 +73,176 @@ export default function AddCollection({ toggleCollectionModal }: Props) {/></div>+ <hr className="border rounded my-2" />++ <div className="flex gap-5 items-center justify-between">+ <p className="text-sm font-bold text-sky-300">Members</p>+ <input+ value={memberEmail}+ onChange={(e) => {+ setMemberEmail(e.target.value);+ }}+ onKeyDown={async (e) => {+ const checkIfMemberAlreadyExists = newCollection.members.find(+ (e) => e.email === memberEmail+ );++ const ownerEmail = session.data?.user.email;++ if (+ e.key === "Enter" &&+ // no duplicate members+ !checkIfMemberAlreadyExists &&+ // member can't be empty+ memberEmail.trim() !== "" &&+ // member can't be the owner+ memberEmail.trim() !== ownerEmail+ ) {+ // Lookup, get data/err, list ...+ const user = await getUserByEmail(memberEmail.trim());++ if (user.email) {+ const newMember = {+ name: user.name,+ email: user.email,+ canCreate: false,+ canUpdate: false,+ canDelete: false,+ };++ setNewCollection({+ ...newCollection,+ members: [...newCollection.members, newMember],+ });++ setMemberEmail("");+ }+ }+ }}+ type="text"+ placeholder="Email (Optional)"+ className="w-56 sm:w-96 rounded-md p-3 border-sky-100 border-solid border text-sm outline-none focus:border-sky-500 duration-100"+ />+ </div>++ {newCollection.members[0] ? (+ <p className="text-center text-sky-500 text-xs sm:text-sm">+ (All Members will have <b>Read</b> access to this collection.)+ </p>+ ) : null}++ {newCollection.members.map((e, i) => {+ return (+ <div+ key={i}+ className="border p-2 rounded-md border-sky-100 flex items-center justify-between"+ >+ <div>+ <p className="text-sm font-bold text-sky-500">{e.name}</p>+ <p className="text-sky-900">{e.email}</p>+ </div>+ <div className="relative">+ <FontAwesomeIcon+ icon={faClose}+ className="absolute right-0 top-0 text-gray-500 h-4 hover:text-red-500 duration-100 cursor-pointer"+ title="Remove Member"+ onClick={() => {+ const updatedMembers = newCollection.members.filter(+ (member) => {+ return member.email !== e.email;+ }+ );+ setNewCollection({+ ...newCollection,+ members: updatedMembers,+ });+ }}+ />+ <p className="font-bold text-sm text-gray-500">Permissions</p>+ <p className="text-xs text-gray-400 mb-2">(Click to toggle.)</p>++ <label className="cursor-pointer mr-1">+ <input+ type="checkbox"+ id="canCreate"+ className="peer sr-only"+ checked={e.canCreate}+ onChange={() => {+ const updatedMembers = newCollection.members.map(+ (member) => {+ if (member.email === e.email) {+ return { ...member, canCreate: !e.canCreate };+ }+ return member;+ }+ );+ setNewCollection({+ ...newCollection,+ members: updatedMembers,+ });+ }}+ />+ <span className="text-sky-900 peer-checked:bg-sky-500 text-sm hover:bg-sky-200 duration-75 peer-checked:text-white rounded p-1 select-none">+ Create+ </span>+ </label>++ <label className="cursor-pointer mr-1">+ <input+ type="checkbox"+ id="canUpdate"+ className="peer sr-only"+ checked={e.canUpdate}+ onChange={() => {+ const updatedMembers = newCollection.members.map(+ (member) => {+ if (member.email === e.email) {+ return { ...member, canUpdate: !e.canUpdate };+ }+ return member;+ }+ );+ setNewCollection({+ ...newCollection,+ members: updatedMembers,+ });+ }}+ />+ <span className="text-sky-900 peer-checked:bg-sky-500 text-sm hover:bg-sky-200 duration-75 peer-checked:text-white rounded p-1 select-none">+ Update+ </span>+ </label>++ <label className="cursor-pointer mr-1">+ <input+ type="checkbox"+ id="canDelete"+ className="peer sr-only"+ checked={e.canDelete}+ onChange={() => {+ const updatedMembers = newCollection.members.map(+ (member) => {+ if (member.email === e.email) {+ return { ...member, canDelete: !e.canDelete };+ }+ return member;+ }+ );+ setNewCollection({+ ...newCollection,+ members: updatedMembers,+ });+ }}+ />+ <span className="text-sky-900 peer-checked:bg-sky-500 text-sm hover:bg-sky-200 duration-75 peer-checked:text-white rounded p-1 select-none">+ Delete+ </span>+ </label>+ </div>+ </div>+ );+ })}+<divclassName="mx-auto mt-2 bg-sky-500 text-white flex items-center gap-2 py-2 px-5 rounded-md select-none font-bold cursor-pointer duration-100 hover:bg-sky-400"onClick={submitCollection}diff --git a/components/Modal/EditCollection.tsx b/components/Modal/EditCollection.tsxnew file mode 100644index 00000000..e69de29bdiff --git a/lib/api/controllers/collections/getCollections.ts b/lib/api/controllers/collections/getCollections.tsindex c53a7eac..a494b8b5 100644--- a/lib/api/controllers/collections/getCollections.ts+++ b/lib/api/controllers/collections/getCollections.ts@@ -8,7 +8,13 @@ import { prisma } from "@/lib/api/db";export default async function (userId: number) {const collections = await prisma.collection.findMany({where: {- ownerId: userId,+ OR: [+ { ownerId: userId },+ { members: { some: { user: { id: userId } } } },+ ],+ },+ include: {+ members: true,},});diff --git a/lib/api/controllers/collections/postCollection.ts b/lib/api/controllers/collections/postCollection.tsindex 569d223c..70f1e1a7 100644--- a/lib/api/controllers/collections/postCollection.ts+++ b/lib/api/controllers/collections/postCollection.ts@@ -4,10 +4,10 @@// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.import { prisma } from "@/lib/api/db";-import { Collection } from "@prisma/client";+import { NewCollection } from "@/types/global";import { existsSync, mkdirSync } from "fs";-export default async function (collection: Collection, userId: number) {+export default async function (collection: NewCollection, userId: number) {if (!collection || collection.name.trim() === "")return {response: "Please enter a valid collection.",@@ -41,6 +41,14 @@ export default async function (collection: Collection, userId: number) {},name: collection.name,description: collection.description,+ members: {+ create: collection.members.map((e) => ({+ user: { connect: { email: e.email } },+ canCreate: e.canCreate,+ canUpdate: e.canUpdate,+ canDelete: e.canDelete,+ })),+ },},});diff --git a/lib/api/controllers/links/deleteLink.ts b/lib/api/controllers/links/deleteLink.tsindex e96458c7..12342b57 100644--- a/lib/api/controllers/links/deleteLink.ts+++ b/lib/api/controllers/links/deleteLink.ts@@ -7,15 +7,12 @@ import { prisma } from "@/lib/api/db";import { ExtendedLink } from "@/types/global";import fs from "fs";import { Link, UsersAndCollections } from "@prisma/client";-import hasAccessToCollection from "@/lib/api/hasAccessToCollection";+import getPermission from "@/lib/api/getPermission";export default async function (link: ExtendedLink, userId: number) {if (!link) return { response: "Please choose a valid link.", status: 401 };- const collectionIsAccessible = await hasAccessToCollection(- userId,- link.collectionId- );+ const collectionIsAccessible = await getPermission(userId, link.collectionId);const memberHasAccess = collectionIsAccessible?.members.some((e: UsersAndCollections) => e.userId === userId && e.canDeletediff --git a/lib/api/controllers/links/postLink.ts b/lib/api/controllers/links/postLink.tsindex 093e9cf7..26eb2dc0 100644--- a/lib/api/controllers/links/postLink.ts+++ b/lib/api/controllers/links/postLink.ts@@ -9,7 +9,7 @@ import getTitle from "../../getTitle";import archive from "../../archive";import { Link, UsersAndCollections } from "@prisma/client";import AES from "crypto-js/aes";-import hasAccessToCollection from "@/lib/api/hasAccessToCollection";+import getPermission from "@/lib/api/getPermission";export default async function (link: ExtendedLink, userId: number) {link.collection.name = link.collection.name.trim();@@ -21,7 +21,7 @@ export default async function (link: ExtendedLink, userId: number) {}if (link.collection.ownerId) {- const collectionIsAccessible = await hasAccessToCollection(+ const collectionIsAccessible = await getPermission(userId,link.collection.id);diff --git a/lib/api/controllers/links/updateLink.ts b/lib/api/controllers/links/updateLink.tsindex 1a7e53d4..a1cfd23c 100644--- a/lib/api/controllers/links/updateLink.ts+++ b/lib/api/controllers/links/updateLink.ts@@ -6,15 +6,12 @@import { prisma } from "@/lib/api/db";import { ExtendedLink } from "@/types/global";import { Link, UsersAndCollections } from "@prisma/client";-import hasAccessToCollection from "@/lib/api/hasAccessToCollection";+import getPermission from "@/lib/api/getPermission";export default async function (link: ExtendedLink, userId: number) {if (!link) return { response: "Please choose a valid link.", status: 401 };- const collectionIsAccessible = await hasAccessToCollection(- userId,- link.collectionId- );+ const collectionIsAccessible = await getPermission(userId, link.collectionId);const memberHasAccess = collectionIsAccessible?.members.some((e: UsersAndCollections) => e.userId === userId && e.canUpdatediff --git a/lib/api/controllers/users/getUsers.ts b/lib/api/controllers/users/getUsers.tsnew file mode 100644index 00000000..f1780a45--- /dev/null+++ b/lib/api/controllers/users/getUsers.ts@@ -0,0 +1,22 @@+// Copyright (C) 2022-present Daniel31x13 <[email protected]>+// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.+// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.+// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.++import { prisma } from "@/lib/api/db";++export default async function (email: string) {+ const user = await prisma.user.findUnique({+ where: {+ email,+ },+ });++ const unsensitiveUserInfo = {+ name: user?.name,+ email: user?.email,+ createdAt: user?.createdAt,+ };++ return { response: unsensitiveUserInfo || null, status: 200 };+}diff --git a/lib/api/hasAccessToCollection.ts b/lib/api/getPermission.tssimilarity index 100%rename from lib/api/hasAccessToCollection.tsrename to lib/api/getPermission.tsdiff --git a/pages/api/archives/[...params].ts b/pages/api/archives/[...params].tsindex 5f2d1887..317a05f9 100644--- a/pages/api/archives/[...params].ts+++ b/pages/api/archives/[...params].ts@@ -10,7 +10,7 @@ import AES from "crypto-js/aes";import enc from "crypto-js/enc-utf8";import path from "path";import fs from "fs";-import hasAccessToCollection from "@/lib/api/hasAccessToCollection";+import getPermission from "@/lib/api/getPermission";export default async function (req: NextApiRequest, res: NextApiResponse) {if (!req.query.params)@@ -23,7 +23,7 @@ export default async function (req: NextApiRequest, res: NextApiResponse) {if (!session?.user?.email)return res.status(401).json({ response: "You must be logged in." });- const collectionIsAccessible = await hasAccessToCollection(+ const collectionIsAccessible = await getPermission(session.user.id,Number(collectionId));diff --git a/pages/api/routes/tags/index.ts b/pages/api/routes/tags/index.tsindex b929edfc..c14d9c94 100644--- a/pages/api/routes/tags/index.ts+++ b/pages/api/routes/tags/index.ts@@ -8,14 +8,7 @@ import { getServerSession } from "next-auth/next";import { authOptions } from "pages/api/auth/[...nextauth]";import getTags from "@/lib/api/controllers/tags/getTags";-type Data = {- response: object[] | string;-};--export default async function (- req: NextApiRequest,- res: NextApiResponse<Data>-) {+export default async function (req: NextApiRequest, res: NextApiResponse) {const session = await getServerSession(req, res, authOptions);if (!session?.user?.email) {diff --git a/pages/api/routes/users/index.ts b/pages/api/routes/users/index.tsnew file mode 100644index 00000000..b3359ea5--- /dev/null+++ b/pages/api/routes/users/index.ts@@ -0,0 +1,23 @@+// Copyright (C) 2022-present Daniel31x13 <[email protected]>+// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.+// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.+// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.++import type { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import { authOptions } from "pages/api/auth/[...nextauth]";+import getUsers from "@/lib/api/controllers/users/getUsers";++export default async function (req: NextApiRequest, res: NextApiResponse) {+ const session = await getServerSession(req, res, authOptions);++ if (!session?.user?.email) {+ return res.status(401).json({ response: "You must be logged in." });+ }++ // get unsensitive user info by email+ if (req.method === "GET") {+ const users = await getUsers(req.query.email as string);+ return res.status(users.status).json({ response: users.response });+ }+}diff --git a/pages/register.tsx b/pages/register.tsxindex f39e8c16..e9fae867 100644--- a/pages/register.tsx+++ b/pages/register.tsx@@ -24,7 +24,6 @@ export default function () {async function registerUser() {let success: boolean = false;- console.log(form);if (form.name != "" && form.email != "" && form.password != "") {await fetch("/api/auth/register", {diff --git a/store/collections.ts b/store/collections.tsindex bcf46397..ee39c9c1 100644--- a/store/collections.ts+++ b/store/collections.ts@@ -5,13 +5,13 @@import { create } from "zustand";import { Collection } from "@prisma/client";-import { NewCollection } from "@/types/global";+import { ExtendedCollection, NewCollection } from "@/types/global";type CollectionStore = {- collections: Collection[];+ collections: ExtendedCollection[];setCollections: () => void;addCollection: (body: NewCollection) => Promise<boolean>;- updateCollection: (collection: Collection) => void;+ // updateCollection: (collection: Collection) => void;removeCollection: (collectionId: number) => void;};@@ -44,12 +44,12 @@ const useCollectionStore = create<CollectionStore>()((set) => ({return response.ok;},- updateCollection: (collection) =>- set((state) => ({- collections: state.collections.map((c) =>- c.id === collection.id ? collection : c- ),- })),+ // updateCollection: (collection) =>+ // set((state) => ({+ // collections: state.collections.map((c) =>+ // c.id === collection.id ? collection : c+ // ),+ // })),removeCollection: (collectionId) => {set((state) => ({collections: state.collections.filter((c) => c.id !== collectionId),diff --git a/store/links.ts b/store/links.tsindex 35d57b11..68e9f516 100644--- a/store/links.ts+++ b/store/links.ts@@ -79,6 +79,8 @@ const useLinkStore = create<LinkStore>()((set) => ({const data = await response.json();+ console.log(data);+if (response.ok) {set((state) => ({links: state.links.filter((e) => e.id !== link.id),diff --git a/types/global.ts b/types/global.tsindex d3529104..21500a97 100644--- a/types/global.ts+++ b/types/global.ts@@ -3,7 +3,7 @@// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.// You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.-import { Collection, Link, Tag } from "@prisma/client";+import { Collection, Link, Tag, UsersAndCollections } from "@prisma/client";export interface ExtendedLink extends Link {tags: Tag[];@@ -24,4 +24,15 @@ export interface NewLink {export interface NewCollection {name: string;description: string;+ members: {+ name: string;+ email: string;+ canCreate: boolean;+ canUpdate: boolean;+ canDelete: boolean;+ }[];+}++export interface ExtendedCollection extends Collection {+ members: UsersAndCollections[];}