Use same lock values as mobile clients
[ProtonMail-WebClient.git] / packages / shared / lib / calendar / crypto / keys / setupCalendarKeys.ts
blob8f034309811501d08b9474e21fc93d8bff912bb4
1 import { c } from 'ttag';
3 import type { useGetAddressKeys } from '@proton/components/hooks';
5 import { setupCalendar } from '../../../api/calendars';
6 import type { Api } from '../../../interfaces';
7 import type { CalendarSetupResponse, CalendarWithOwnMembers } from '../../../interfaces/calendar';
8 import { getPrimaryKey } from '../../../keys';
9 import { generateCalendarKeyPayload } from './calendarKeys';
10 import { isCalendarSetupData } from './helpers';
12 export const setupCalendarKey = async ({
13     calendarID,
14     api,
15     addressID,
16     getAddressKeys,
17 }: {
18     api: Api;
19     getAddressKeys: ReturnType<typeof useGetAddressKeys>;
20     calendarID: string;
21     addressID: string;
22 }) => {
23     const { privateKey, publicKey } = getPrimaryKey(await getAddressKeys(addressID)) || {};
25     if (!privateKey || !publicKey) {
26         throw new Error(c('Error').t`Primary address key is not decrypted`);
27     }
29     const calendarKeyPayload = await generateCalendarKeyPayload({
30         addressID,
31         privateKey,
32         publicKey,
33     });
35     if (!isCalendarSetupData(calendarKeyPayload)) {
36         throw new Error(c('Error').t`Missing key packet`);
37     }
39     return api<CalendarSetupResponse>(setupCalendar(calendarID, calendarKeyPayload));
42 export const setupCalendarKeys = async ({
43     api,
44     calendars,
45     getAddressKeys,
46 }: {
47     api: Api;
48     calendars: CalendarWithOwnMembers[];
49     getAddressKeys: ReturnType<typeof useGetAddressKeys>;
50 }) => {
51     return Promise.all(
52         calendars.map(async ({ ID: calendarID, Members }) => {
53             const addressID = Members[0]?.AddressID;
54             if (!addressID) {
55                 return;
56             }
57             return setupCalendarKey({ calendarID, api, getAddressKeys, addressID });
58         })
59     );