Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / shared / lib / calendar / crypto / keys / resetHelper.ts
blob0b0f163356bb585532072e0b49fae52062666014
1 import { c } from 'ttag';
3 import type { useGetAddressKeys } from '@proton/account/addressKeys/hooks';
4 import type { useGetAddresses } from '@proton/account/addresses/hooks';
5 import type { useGetCalendars } from '@proton/calendar/calendars/hooks';
6 import { CacheType } from '@proton/redux-utilities';
8 import { getSilentApi } from '../../../api/helpers/customConfig';
9 import getHasSharedCalendars from '../../../calendar/sharing/getHasSharedCalendars';
10 import type { Api } from '../../../interfaces';
11 import type { VisualCalendar } from '../../../interfaces/calendar';
12 import { getIsOwnedCalendar } from '../../calendar';
13 import { reactivateCalendarsKeys } from './reactivateCalendarKeys';
14 import { resetCalendarKeys } from './resetCalendarKeys';
16 interface ProcessArguments {
17     api: Api;
18     getCalendars: ReturnType<typeof useGetCalendars>;
19     getAddresses: ReturnType<typeof useGetAddresses>;
20     getAddressKeys: ReturnType<typeof useGetAddressKeys>;
21     calendarsToReset?: VisualCalendar[];
22     calendarsToReactivate?: VisualCalendar[];
23     calendarsToClean?: VisualCalendar[];
26 export const process = async ({
27     api,
28     getCalendars,
29     getAddresses,
30     getAddressKeys,
31     calendarsToReset = [],
32     calendarsToReactivate = [],
33     calendarsToClean = [],
34 }: ProcessArguments) => {
35     const addresses = await getAddresses();
37     if (!addresses.length) {
38         throw new Error(c('Error').t`Please create an address first.`);
39     }
41     let hasSharedCalendars = false;
42     if (calendarsToReset.length > 0 || calendarsToClean.length > 0) {
43         // Non-owners can't reset calendar keys
44         // Even if calendarsToReset is empty, we want to call the reset endpoint in order to clean shared/holidays calendars
45         const calendars = calendarsToReset.filter((calendar) => getIsOwnedCalendar(calendar));
46         const [hasShared] = await Promise.all([
47             getHasSharedCalendars({
48                 calendars,
49                 api: getSilentApi(api),
50                 catchErrors: true,
51             }),
52             resetCalendarKeys({
53                 calendars,
54                 api,
55                 getAddressKeys,
56             }),
57         ]);
59         hasSharedCalendars = hasShared;
60     }
62     if (calendarsToReactivate.length > 0) {
63         await reactivateCalendarsKeys({
64             api,
65             calendars: calendarsToReactivate,
66             getAddressKeys,
67             addresses,
68         });
69     }
71     // Refresh the calendar model to be able to get the new flags since it's not updated through the event manager
72     await getCalendars({ cache: CacheType.None });
74     return hasSharedCalendars;