Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / applications / drive / src / app / store / _links / useLinks.ts
blob79f102272865ed66c8f7fb23f64ad83c9513538b
1 import { MAX_THREADS_PER_REQUEST } from '@proton/shared/lib/drive/constants';
2 import runInQueue from '@proton/shared/lib/helpers/runInQueue';
3 import isTruthy from '@proton/utils/isTruthy';
5 import { isIgnoredError } from '../../utils/errorHandling';
6 import type { DecryptedLink, EncryptedLink } from './interface';
7 import useLink from './useLink';
9 export default function useLinks() {
10     const { decryptLink, getLink } = useLink();
12     const decryptLinks = async (
13         abortSignal: AbortSignal,
14         shareId: string,
15         encryptedLinks: EncryptedLink[]
16     ): Promise<{
17         links: { encrypted: EncryptedLink; decrypted: DecryptedLink }[];
18         errors: any[];
19     }> => {
20         let errors: any[] = [];
21         const queue = encryptedLinks.map((encrypted) => async () => {
22             if (abortSignal.aborted) {
23                 return;
24             }
25             return decryptLink(abortSignal, shareId, encrypted)
26                 .then((decrypted) => {
27                     if (decrypted.corruptedLink) {
28                         errors.push(new Error('Failed to decrypt link'));
29                     }
30                     return { encrypted, decrypted };
31                 })
32                 .catch((err) => {
33                     if (!isIgnoredError(err)) {
34                         errors.push(err);
35                     }
36                 });
37         });
38         // Limit the decryption so the app does not freeze when loading big page.
39         const results = await runInQueue(queue, MAX_THREADS_PER_REQUEST);
40         const links = results.filter(isTruthy);
42         return { links, errors };
43     };
45     const getLinks = async (
46         abortSignal: AbortSignal,
47         ids: { linkId: string; shareId: string }[]
48     ): Promise<DecryptedLink[]> => {
49         const queue = ids.map(
50             ({ linkId, shareId }) =>
51                 async () =>
52                     getLink(abortSignal, shareId, linkId)
53         );
54         return runInQueue(queue, MAX_THREADS_PER_REQUEST);
55     };
57     return {
58         decryptLinks,
59         getLinks,
60     };