Use same lock values as mobile clients
[ProtonMail-WebClient.git] / packages / shared / lib / calendar / crypto / keys / setupCalendarHelper.ts
blob9a39aaf4fe1a05296a5622bbe3c159f21152fae6
1 import { c } from 'ttag';
3 import type { useGetAddressKeys } from '@proton/components';
5 import { createCalendar, updateCalendarUserSettings } from '../../../api/calendars';
6 import { getRandomAccentColor } from '../../../colors';
7 import { getTimezone } from '../../../date/timezone';
8 import { getActiveAddresses } from '../../../helpers/address';
9 import type { Address, Api } from '../../../interfaces';
10 import type { CalendarWithOwnMembers } from '../../../interfaces/calendar';
11 import { getPrimaryKey } from '../../../keys';
12 import { DEFAULT_CALENDAR } from '../../constants';
13 import { setupCalendarKey } from './setupCalendarKeys';
15 interface Args {
16     addresses: Address[];
17     api: Api;
18     getAddressKeys: ReturnType<typeof useGetAddressKeys>;
21 const setupCalendarHelper = async ({ addresses, api, getAddressKeys }: Args) => {
22     const activeAddresses = getActiveAddresses(addresses);
23     if (!activeAddresses.length) {
24         throw new Error(c('Error').t`No valid address found`);
25     }
27     const [{ ID: addressID }] = activeAddresses;
28     const { privateKey: primaryAddressKey } = getPrimaryKey(await getAddressKeys(addressID)) || {};
29     if (!primaryAddressKey) {
30         throw new Error(c('Error').t`Primary address key is not decrypted.`);
31     }
33     const { Calendar } = await api<{ Calendar: CalendarWithOwnMembers }>(
34         createCalendar({
35             Name: DEFAULT_CALENDAR.name,
36             Color: getRandomAccentColor(),
37             Description: DEFAULT_CALENDAR.description,
38             Display: 1,
39             AddressID: addressID,
40         })
41     );
42     const updatedCalendarUserSettings = {
43         PrimaryTimezone: getTimezone(),
44         AutoDetectPrimaryTimezone: 1,
45     };
47     const [
48         {
49             Passphrase: { Flags },
50         },
51     ] = await Promise.all([
52         setupCalendarKey({
53             api,
54             calendarID: Calendar.ID,
55             addressID,
56             getAddressKeys,
57         }),
58         api(updateCalendarUserSettings(updatedCalendarUserSettings)),
59     ]);
61     // There is only one member in the calendar at this point
62     const calendarWithUpdatedFlags = {
63         ...Calendar,
64         Members: [
65             {
66                 ...Calendar.Members[0],
67                 Flags,
68             },
69         ],
70     };
72     return {
73         calendar: calendarWithUpdatedFlags,
74         updatedCalendarUserSettings,
75     };
78 export default setupCalendarHelper;