diff --git a/app/components/Sidebar/components/SharedWithMeLink.tsx b/app/components/Sidebar/components/SharedWithMeLink.tsx index 7f38e560f5..66a5743250 100644 --- a/app/components/Sidebar/components/SharedWithMeLink.tsx +++ b/app/components/Sidebar/components/SharedWithMeLink.tsx @@ -63,8 +63,9 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { React.useEffect(() => { if (documentId) { void documents.fetch(documentId); + void membership.fetchDocuments(); } - }, [documentId, documents]); + }, [documentId, documents, membership]); React.useEffect(() => { if (isActiveDocument && membership.documentId) { @@ -115,9 +116,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { ? collections.get(document.collectionId) : undefined; - const node = document.asNavigationNode; - const childDocuments = node.children; - const hasChildDocuments = childDocuments.length > 0; + const hasChildDocuments = (membership.documents?.length || 0) > 0; return ( <> @@ -172,13 +171,13 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { - {childDocuments.map((node, index) => ( + {membership.documents?.map((childNode, index) => ( diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx index ff297d67d6..1105d03501 100644 --- a/app/components/WebsocketProvider.tsx +++ b/app/components/WebsocketProvider.tsx @@ -27,6 +27,7 @@ import withStores from "~/components/withStores"; import { PartialExcept, WebsocketCollectionUpdateIndexEvent, + WebsocketDocumentMovedEvent, WebsocketEntitiesEvent, WebsocketEntityDeletedEvent, } from "~/types"; @@ -147,9 +148,7 @@ class WebsocketProvider extends React.Component { // otherwise, grab the latest version of the document try { - document = await documents.fetch(documentId, { - force: true, - }); + document = await documents.fetch(documentId, { force: true }); } catch (err) { if ( err instanceof AuthorizationError || @@ -176,6 +175,16 @@ class WebsocketProvider extends React.Component { }); } } + + const parentDocuments = document?.parentDocuments ?? []; + for (const parentDoc of parentDocuments) { + await userMemberships + .find({ documentId: parentDoc.id }) + ?.fetchDocuments({ force: true }); + await groupMemberships + .find({ documentId: parentDoc.id }) + ?.fetchDocuments({ force: true }); + } } } @@ -221,6 +230,17 @@ class WebsocketProvider extends React.Component { const collection = collections.get(event.collectionId); collection?.updateDocument(event); } + + const document = documents.get(event.id); + const parentDocuments = document?.parentDocuments ?? []; + for (const parentDoc of parentDocuments) { + userMemberships + .find({ documentId: parentDoc.id }) + ?.updateDocument(event); + groupMemberships + .find({ documentId: parentDoc.id }) + ?.updateDocument(event); + } }) ); @@ -233,6 +253,17 @@ class WebsocketProvider extends React.Component { const collection = collections.get(event.collectionId); collection?.removeDocument(event.id); } + + const document = documents.get(event.id); + const parentDocuments = document?.parentDocuments ?? []; + for (const parentDoc of parentDocuments) { + userMemberships + .find({ documentId: parentDoc.id }) + ?.removeDocument(event.id); + groupMemberships + .find({ documentId: parentDoc.id }) + ?.removeDocument(event.id); + } }) ); @@ -250,6 +281,17 @@ class WebsocketProvider extends React.Component { userMemberships.orderedData .filter((m) => m.documentId === event.id) .forEach((m) => userMemberships.remove(m.id)); + + const document = documents.get(event.id); + const parentDocuments = document?.parentDocuments ?? []; + for (const parentDoc of parentDocuments) { + userMemberships + .find({ documentId: parentDoc.id }) + ?.removeDocument(event.id); + groupMemberships + .find({ documentId: parentDoc.id }) + ?.removeDocument(event.id); + } }) ); @@ -260,6 +302,56 @@ class WebsocketProvider extends React.Component { } ); + this.socket.on( + "documents.move", + action(async (event: WebsocketDocumentMovedEvent) => { + if (event.documentId) { + const document = await documents.fetch(event.documentId, { + force: true, + }); + + // Refresh documents structure in case this document (or) its ancestors is shared to the user. + const docIdsToRefreshStructure = [ + event.documentId, + ...document.parentDocuments.map((doc) => doc.id), + ]; + + for (const documentId of docIdsToRefreshStructure) { + await userMemberships + .find({ documentId }) + ?.fetchDocuments({ force: true }); + await groupMemberships + .find({ documentId }) + ?.fetchDocuments({ force: true }); + } + } + + if (event.prevParentDocumentId) { + const prevDocument = documents.get(event.prevParentDocumentId); + + // Refresh documents structure in case the prev parent document (or) its ancestors is shared to the user. + const docIdsToRefreshStructure = [ + event.prevParentDocumentId, + ...(prevDocument?.parentDocuments.map((doc) => doc.id) ?? []), + ]; + + for (const documentId of docIdsToRefreshStructure) { + await userMemberships + .find({ documentId }) + ?.fetchDocuments({ force: true }); + await groupMemberships + .find({ documentId }) + ?.fetchDocuments({ force: true }); + } + } + + if (event.collectionId) { + const collection = collections.get(event.collectionId); + await collection?.fetchDocuments({ force: true }); + } + }) + ); + this.socket.on( "documents.add_user", async (event: PartialExcept) => { diff --git a/app/models/Document.ts b/app/models/Document.ts index 19e2a10b58..10eb0f3d7c 100644 --- a/app/models/Document.ts +++ b/app/models/Document.ts @@ -617,6 +617,15 @@ export default class Document extends ArchivableModel { ); } + @computed + get parentDocuments(): Document[] { + if (!this.parentDocument) { + return []; + } + const parentDocs = this.parentDocument.parentDocuments; + return [...parentDocs, this.parentDocument]; + } + @computed get asNavigationNode(): NavigationNode { return { diff --git a/app/models/GroupMembership.ts b/app/models/GroupMembership.ts index e9ff597c41..f4e2ce04ec 100644 --- a/app/models/GroupMembership.ts +++ b/app/models/GroupMembership.ts @@ -1,5 +1,11 @@ -import { observable } from "mobx"; -import { CollectionPermission, DocumentPermission } from "@shared/types"; +import invariant from "invariant"; +import { action, observable, runInAction } from "mobx"; +import { + CollectionPermission, + DocumentPermission, + NavigationNode, +} from "@shared/types"; +import { client } from "~/utils/ApiClient"; import Collection from "./Collection"; import Document from "./Document"; import Group from "./Group"; @@ -13,6 +19,8 @@ import Relation from "./decorators/Relation"; class GroupMembership extends Model { static modelName = "GroupMembership"; + private isFetching = false; + /** The group ID that this membership is granted to. */ groupId: string; @@ -45,6 +53,89 @@ class GroupMembership extends Model { @observable permission: CollectionPermission | DocumentPermission; + /** The sub-documents structure, in case this membership provides access to a document. */ + @observable + documents?: NavigationNode[]; + + /** + * Fetches the sub-documents structure, in case this membership provides access to a document. + */ + fetchDocuments = async (options?: { force: boolean }) => { + if (!this.documentId || this.isFetching) { + return; + } + if (this.documents && options?.force !== true) { + return; + } + try { + this.isFetching = true; + const res = await client.post("/documents.sub_documents", { + id: this.documentId, + }); + invariant(res?.data, "Data should be available"); + + runInAction("GroupMembership#fetchSubDocuments", () => { + this.documents = res.data; + }); + } finally { + this.isFetching = false; + } + }; + + /** + * Updates the document identified by the given id in the membership in memory. + * Does not update the document in the database. + * + * @param document The document properties stored in the membership + */ + @action + updateDocument( + document: Pick + ) { + if (!this.documents) { + return; + } + + const travelNodes = (nodes: NavigationNode[]) => + nodes.forEach((node) => { + if (node.id === document.id) { + node.color = document.color ?? undefined; + node.icon = document.icon ?? undefined; + node.title = document.title; + node.url = document.url; + } else { + travelNodes(node.children); + } + }); + + travelNodes(this.documents); + } + + /** + * Removes the document identified by the given id in the membership in memory. + * Does not remove the document from the database. + * + * @param documentId The id of the document to remove. + */ + @action + removeDocument(documentId: string) { + if (!this.documents) { + return; + } + + this.documents = this.documents.filter(function f(node): boolean { + if (node.id === documentId) { + return false; + } + + if (node.children) { + node.children = node.children.filter(f); + } + + return true; + }); + } + // hooks @AfterRemove diff --git a/app/models/UserMembership.ts b/app/models/UserMembership.ts index 49305dcabb..3e5ad006a6 100644 --- a/app/models/UserMembership.ts +++ b/app/models/UserMembership.ts @@ -1,6 +1,8 @@ -import { observable } from "mobx"; -import { DocumentPermission } from "@shared/types"; +import invariant from "invariant"; +import { action, observable, runInAction } from "mobx"; +import { DocumentPermission, NavigationNode } from "@shared/types"; import type UserMembershipsStore from "~/stores/UserMembershipsStore"; +import { client } from "~/utils/ApiClient"; import Document from "./Document"; import User from "./User"; import Model from "./base/Model"; @@ -11,6 +13,8 @@ import Relation from "./decorators/Relation"; class UserMembership extends Model { static modelName = "UserMembership"; + private isFetching = false; + /** The sort order of the membership (In users sidebar) */ @Field @observable @@ -48,6 +52,10 @@ class UserMembership extends Model { /** The user ID that created this membership. */ createdById: string; + /** The sub-documents structure, in case this membership provides access to a document. */ + @observable + documents?: NavigationNode[]; + store: UserMembershipsStore; /** @@ -72,6 +80,85 @@ class UserMembership extends Model { return memberships[index + 1]; } + /** + * Fetches the sub-documents structure, in case this membership provides access to a document. + */ + fetchDocuments = async (options?: { force: boolean }) => { + if (this.isFetching || !this.documentId) { + return; + } + if (this.documents && options?.force !== true) { + return; + } + try { + this.isFetching = true; + const res = await client.post("/documents.sub_documents", { + id: this.documentId, + }); + invariant(res?.data, "Data should be available"); + + runInAction("UserMembership#fetchSubDocuments", () => { + this.documents = res.data; + }); + } finally { + this.isFetching = false; + } + }; + + /** + * Updates the document identified by the given id in the membership in memory. + * Does not update the document in the database. + * + * @param document The document properties stored in the membership + */ + @action + updateDocument( + document: Pick + ) { + if (!this.documents) { + return; + } + + const travelNodes = (nodes: NavigationNode[]) => + nodes.forEach((node) => { + if (node.id === document.id) { + node.color = document.color ?? undefined; + node.icon = document.icon ?? undefined; + node.title = document.title; + node.url = document.url; + } else { + travelNodes(node.children); + } + }); + + travelNodes(this.documents); + } + + /** + * Removes the document identified by the given id in the membership in memory. + * Does not remove the document from the database. + * + * @param documentId The id of the document to remove. + */ + @action + removeDocument(documentId: string) { + if (!this.documents) { + return; + } + + this.documents = this.documents.filter(function f(node): boolean { + if (node.id === documentId) { + return false; + } + + if (node.children) { + node.children = node.children.filter(f); + } + + return true; + }); + } + // hooks @AfterRemove diff --git a/app/stores/GroupMembershipsStore.ts b/app/stores/GroupMembershipsStore.ts index 7624c6943f..5b60466110 100644 --- a/app/stores/GroupMembershipsStore.ts +++ b/app/stores/GroupMembershipsStore.ts @@ -1,6 +1,10 @@ import invariant from "invariant"; -import { action, runInAction } from "mobx"; -import { CollectionPermission, DocumentPermission } from "@shared/types"; +import { action, observable, runInAction } from "mobx"; +import { + CollectionPermission, + DocumentPermission, + NavigationNode, +} from "@shared/types"; import GroupMembership from "~/models/GroupMembership"; import { PaginationParams } from "~/types"; import { client } from "~/utils/ApiClient"; @@ -10,6 +14,9 @@ import Store, { PAGINATION_SYMBOL, RPCAction } from "./base/Store"; export default class GroupMembershipsStore extends Store { actions = [RPCAction.Create, RPCAction.Delete]; + @observable + documents: Map = new Map(); + constructor(rootStore: RootStore) { super(rootStore, GroupMembership); } @@ -45,6 +52,9 @@ export default class GroupMembershipsStore extends Store { runInAction(`GroupMembershipsStore#fetchPage`, () => { res.data.groups?.forEach(this.rootStore.groups.add); res.data.documents?.forEach(this.rootStore.documents.add); + res.data.documentsStructure?.forEach((node: NavigationNode) => + this.documents.set(node.id, node.children) + ); response = res.data.groupMemberships.map(this.add); this.isLoaded = true; }); diff --git a/app/types.ts b/app/types.ts index 5f9d4908cc..a2e4aa3041 100644 --- a/app/types.ts +++ b/app/types.ts @@ -188,11 +188,18 @@ export type WebsocketCollectionUpdateIndexEvent = { index: string; }; +export type WebsocketDocumentMovedEvent = { + documentId?: string; + prevParentDocumentId?: string; + collectionId?: string; +}; + export type WebsocketEvent = | PartialExcept | PartialExcept | PartialExcept | PartialExcept + | WebsocketDocumentMovedEvent | WebsocketCollectionUpdateIndexEvent | WebsocketEntityDeletedEvent | WebsocketEntitiesEvent; diff --git a/server/commands/documentMover.ts b/server/commands/documentMover.ts index a3d25aecad..76c1199f76 100644 --- a/server/commands/documentMover.ts +++ b/server/commands/documentMover.ts @@ -46,6 +46,7 @@ async function documentMover({ transaction, }: Props): Promise { const collectionChanged = collectionId !== document.collectionId; + const prevParentDocumentId = document.parentDocumentId; const previousCollectionId = document.collectionId; const result: Result = { collections: [], @@ -273,9 +274,11 @@ async function documentMover({ collectionId, teamId: document.teamId, data: { - title: document.title, collectionIds: result.collections.map((c) => c.id), documentIds: result.documents.map((d) => d.id), + prevParentDocumentId, + hasParentDocumentChanged: + prevParentDocumentId !== document.parentDocumentId, }, ip, }, diff --git a/server/queues/processors/WebsocketsProcessor.ts b/server/queues/processors/WebsocketsProcessor.ts index 87c730b2dd..99fa3b07ba 100644 --- a/server/queues/processors/WebsocketsProcessor.ts +++ b/server/queues/processors/WebsocketsProcessor.ts @@ -146,26 +146,38 @@ export default class WebsocketsProcessor { }, paranoid: false, }); - documents.forEach((document) => { - socketio.to(`collection-${document.collectionId}`).emit("entities", { - event: event.name, - documentIds: [ - { - id: document.id, - updatedAt: document.updatedAt, - }, - ], + const prevParentDocument = event.data.prevParentDocumentId + ? await Document.findByPk(event.data.prevParentDocumentId, { + paranoid: false, + }) + : undefined; + + await Promise.all( + documents.map(async (document) => { + const channels = await this.getDocumentEventChannels( + event, + document + ); + socketio.to(channels).emit(event.name, { + documentId: document.id, + }); + }) + ); + + if (event.data.hasParentDocumentChanged && prevParentDocument) { + const channels = await this.getDocumentEventChannels( + event, + prevParentDocument + ); + socketio.to(channels).emit(event.name, { + prevParentDocumentId: prevParentDocument.id, }); - }); + } + event.data.collectionIds.forEach((collectionId) => { - socketio.to(`collection-${collectionId}`).emit("entities", { - event: event.name, - collectionIds: [ - { - id: collectionId, - }, - ], - }); + socketio + .to(`collection-${collectionId}`) + .emit(event.name, { collectionId }); }); return; } diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 3323eebda2..f63340a929 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -560,7 +560,7 @@ router.post( auth({ optional: true }), validate(T.DocumentsInfoSchema), async (ctx: APIContext) => { - const { id, shareId } = ctx.input.body; + const { id, shareId, includeStructure } = ctx.input.body; const { user } = ctx.state.auth; const apiVersion = getAPIVersion(ctx); const teamFromCtx = await getTeamFromContext(ctx); @@ -570,6 +570,7 @@ router.post( user, teamId: teamFromCtx?.id, }); + const isPublic = cannot(user, "read", document); const serializedDocument = await presentDocument(ctx, document, { isPublic, @@ -584,6 +585,9 @@ router.post( apiVersion >= 2 ? { document: serializedDocument, + documentStructure: includeStructure + ? collection?.getDocumentTree(document.id) + : undefined, team: team ? presentPublicTeam( team, @@ -687,6 +691,26 @@ router.post( } ); +router.post( + "documents.sub_documents", + auth(), + validate(T.DocumentsChildrenSchema), + async (ctx: APIContext) => { + const { id } = ctx.input.body; + const { user } = ctx.state.auth; + const document = await Document.findByPk(id, { userId: user.id }); + + authorize(user, "read", document); + invariant(document.collectionId, "document not part of a collection"); + + const collection = await Collection.findByPk(document.collectionId); + const documentTree = collection.getDocumentTree(document.id); + + ctx.body = { + data: documentTree?.children, + } + }); + router.post( "documents.export", rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index ed3e76c538..0679829bba 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -127,6 +127,9 @@ export const DocumentsInfoSchema = BaseSchema.extend({ /** @deprecated Version of the API to be used, remove in a few releases */ apiVersion: z.number().optional(), + + /** Whether to return the children document structure (sort order) */ + includeStructure: z.boolean().optional(), }), }).refine((req) => !(isEmpty(req.body.id) && isEmpty(req.body.shareId)), { message: "one of id or shareId is required", @@ -378,6 +381,12 @@ export const DocumentsUsersSchema = BaseSchema.extend({ export type DocumentsUsersReq = z.infer; +export const DocumentsChildrenSchema = BaseSchema.extend({ + body: BaseIdSchema, +}); + +export type DocumentsChildrenReq = z.infer; + export const DocumentsAddUserSchema = BaseSchema.extend({ body: z.object({ /** Id of the document to which the user is supposed to be added */ diff --git a/server/routes/api/groupMemberships/groupMemberships.ts b/server/routes/api/groupMemberships/groupMemberships.ts index 4fdd3f239c..04730eb1e8 100644 --- a/server/routes/api/groupMemberships/groupMemberships.ts +++ b/server/routes/api/groupMemberships/groupMemberships.ts @@ -1,9 +1,12 @@ import Router from "koa-router"; +import compact from "lodash/compact"; +import keyBy from "lodash/keyBy"; +import uniq from "lodash/uniq"; import uniqBy from "lodash/uniqBy"; import { Op } from "sequelize"; import auth from "@server/middlewares/authentication"; import validate from "@server/middlewares/validate"; -import { Document, GroupMembership } from "@server/models"; +import { Collection, Document, GroupMembership } from "@server/models"; import { presentDocument, presentGroup, @@ -67,6 +70,24 @@ router.post( }, }); + const collections = await Collection.findAll({ + attributes: ["id", "documentStructure", "sort"], + where: { + id: compact(uniq(documents.map((doc) => doc.collectionId))), + }, + }); + const collectionsMap = keyBy(collections, "id"); + + const documentsStructure = compact( + documents.map((doc) => { + if (!doc.collectionId) { + return; + } + const collection = collectionsMap[doc.collectionId]; + return collection?.getDocumentTree(doc.id); + }) + ); + const groups = uniqBy( memberships.map((membership) => membership.group), "id" @@ -85,6 +106,7 @@ router.post( documents: await Promise.all( documents.map((document: Document) => presentDocument(ctx, document)) ), + documentsStructure, }, policies, }; diff --git a/server/routes/api/userMemberships/userMemberships.ts b/server/routes/api/userMemberships/userMemberships.ts index 3d67f96a14..5108da50c9 100644 --- a/server/routes/api/userMemberships/userMemberships.ts +++ b/server/routes/api/userMemberships/userMemberships.ts @@ -1,10 +1,12 @@ import Router from "koa-router"; - +import compact from "lodash/compact"; +import keyBy from "lodash/keyBy"; +import uniq from "lodash/uniq"; import { Op, Sequelize } from "sequelize"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; -import { Document, Event, UserMembership } from "@server/models"; +import { Collection, Document, Event, UserMembership } from "@server/models"; import { authorize } from "@server/policies"; import { presentDocument, @@ -56,6 +58,24 @@ router.post( }, }); + const collections = await Collection.findAll({ + attributes: ["id", "documentStructure", "sort"], + where: { + id: compact(uniq(documents.map((doc) => doc.collectionId))), + }, + }); + const collectionsMap = keyBy(collections, "id"); + + const documentsStructure = compact( + documents.map((doc) => { + if (!doc.collectionId) { + return; + } + const collection = collectionsMap[doc.collectionId]; + return collection?.getDocumentTree(doc.id); + }) + ); + const policies = presentPolicies(user, [...documents, ...memberships]); ctx.body = { @@ -65,6 +85,7 @@ router.post( documents: await Promise.all( documents.map((document: Document) => presentDocument(ctx, document)) ), + documentsStructure, }, policies, }; diff --git a/server/types.ts b/server/types.ts index 49c0495722..17b8386078 100644 --- a/server/types.ts +++ b/server/types.ts @@ -200,6 +200,8 @@ export type DocumentEvent = BaseEvent & data: { collectionIds: string[]; documentIds: string[]; + prevParentDocumentId: string | null; + hasParentDocumentChanged: boolean; }; } | {