Merge branch 'MAILWEB-6067-improve-circular-dependencies-prevention' into 'main'
[ProtonMail-WebClient.git] / packages / drive-store / store / _shares / useContextShareHandler.ts
blobe2fc23fd61e19d275f0447448ccfe34b96275c85
1 import { queryUserLinkAccess } from '@proton/shared/lib/api/drive/link';
3 import useNavigate from '../../hooks/drive/useNavigate';
4 import { Actions, countActionWithTelemetry } from '../../utils/telemetry';
5 import { useInvitationsActions } from '../_actions';
6 import { useDebouncedRequest } from '../_api';
7 import { useLink } from '../_links';
9 export const useContextShareHandler = () => {
10     const { navigateToRoot, navigateToLink, navigateToNoAccess } = useNavigate();
11     const { acceptInvitation } = useInvitationsActions();
12     const debouncedRequest = useDebouncedRequest();
13     const { getLink } = useLink();
15     const handleContextShare = async (
16         abortSignal: AbortSignal,
17         { shareId, linkId, isFile }: { shareId: string; linkId: string; isFile: boolean }
18     ) => {
19         const response = await debouncedRequest<{
20             Code: number;
21             ContextShare?: {
22                 ShareID: string;
23                 LinkID: string;
24                 VolumeID: string;
25             };
26             Invitations?: {
27                 ShareID: string;
28                 VolumeID: string;
29                 InvitationID: string;
30             }[];
31         }>(queryUserLinkAccess({ shareId, linkId }), abortSignal);
32         if (!!response.ContextShare) {
33             countActionWithTelemetry(Actions.RedirectToCorrectContextShare);
34             await getLink(abortSignal, response.ContextShare.ShareID, response.ContextShare.LinkID);
35             navigateToLink(response.ContextShare.ShareID, response.ContextShare.LinkID, isFile, '/shared-with-me');
36             return;
37         }
38         if (!!response.Invitations?.length) {
39             countActionWithTelemetry(Actions.RedirectToCorrectAcceptInvitation);
40             const invitation = response.Invitations[0];
41             const acceptedInvitation = await acceptInvitation(abortSignal, invitation.InvitationID);
42             // No invitation found, this should not happend as we get it from context
43             if (!acceptedInvitation) {
44                 navigateToRoot();
45                 return;
46             }
47             navigateToLink(acceptedInvitation.shareId, acceptedInvitation.linkId, isFile, '/shared-with-me');
48             return;
49         }
50         navigateToNoAccess();
51         return;
52     };
54     return { handleContextShare };