index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/compatibilityCheck/compatibilityCheckHelper.ts
const isGoodPrngAvailable = () => { if (window.crypto && !!window.crypto.getRandomValues) { return true; } // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function'; }; const hasCookies = () => { try { return navigator.cookieEnabled; } catch (e: any) { // Safari throws SecurityError if storage is disabled return false; } }; const hasSessionStorage = () => { try { return !!window.sessionStorage; } catch (e: any) { // Safari throws SecurityError if storage is disabled return false; } }; const hasLocalStorage = () => { try { return !!window.localStorage; } catch (e: any) { // Safari throws SecurityError if storage is disabled return false; } }; // Locale is not loaded here so no translations export const getCompatibilityList = () => { const isSSR = typeof window === 'undefined'; return [ { name: 'Cookies', valid: isSSR || hasCookies(), text: 'Please enable cookies in your browser.', }, { name: 'Storage', valid: isSSR || hasSessionStorage(), text: 'Please enable sessionStorage in your browser.', }, { name: 'Storage', valid: isSSR || hasLocalStorage(), text: 'Please enable localStorage in your browser.', }, { name: 'PRNG', valid: isSSR || isGoodPrngAvailable(), text: 'Please update to a modern browser with support for PRNG.', }, ]; };
6,000
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/compatibilityCheck/index.ts
export { default as CompatibilityCheck } from './CompatibilityCheck'; export { default as CompatibilityCheckView } from './CompatibilityCheckView'; export * from './compatibilityCheckHelper';
6,001
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/config/Provider.tsx
import { ReactNode } from 'react'; import { ProtonConfig } from '@proton/shared/lib/interfaces'; import ConfigContext from './configContext'; interface Props { children?: ReactNode; config: ProtonConfig; } const Provider = ({ config, children }: Props) => { return <ConfigContext.Provider value={config}>{children}</ConfigContext.Provider>; }; export default Provider;
6,002
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/config/configContext.ts
import { createContext } from 'react'; import { ProtonConfig } from '@proton/shared/lib/interfaces'; export default createContext<ProtonConfig>(null as unknown as ProtonConfig);
6,003
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/config/index.ts
export { default as ConfigProvider } from './Provider';
6,004
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/ContactEmailsProvider.tsx
import { ReactNode, createContext, useContext, useMemo } from 'react'; import { useContactEmails, useContactGroups } from '@proton/components/hooks'; import { canonicalizeEmail } from '@proton/shared/lib/helpers/email'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; export type GroupWithContacts = { group: ContactGroup; contacts: ContactEmail[] }; export type GroupsWithContactsMap = SimpleMap<GroupWithContacts>; export type ContactEmailsCache = { contactEmails: ContactEmail[]; contactGroups: ContactGroup[]; contactEmailsMap: SimpleMap<ContactEmail>; contactEmailsMapWithDuplicates: SimpleMap<ContactEmail[]>; groupsWithContactsMap: GroupsWithContactsMap; }; const ContactEmailsContext = createContext<ContactEmailsCache | null>(null); const computeGroupsMap = (contacts: ContactEmail[], contactGroups: ContactGroup[]) => contacts.reduce<GroupsWithContactsMap>((acc, contact) => { contact.LabelIDs?.forEach((labelID) => { if (acc[labelID]) { acc[labelID]?.contacts.push(contact); } else { const group = contactGroups.find((group) => group.ID === labelID); if (group) { acc[labelID] = { group, contacts: [contact] }; } } }); return acc; }, {}); export const useContactEmailsCache = () => { const state = useContext(ContactEmailsContext); if (!state) { throw new Error('Trying to use uninitialized ContactEmailsProvider'); } return state; }; const toMapWithDuplicates = (contacts: ContactEmail[]) => { const contactEmailsMapWithDuplicates = contacts.reduce<SimpleMap<ContactEmail[]>>((acc, contact) => { const email = canonicalizeEmail(contact.Email); const contacts = acc[email]; if (!contacts) { acc[email] = [contact]; } else { contacts.push(contact); contacts.sort((a, b) => a.Order - b.Order); } return acc; }, {}); const contactEmailsMap = Object.keys(contactEmailsMapWithDuplicates).reduce<SimpleMap<ContactEmail>>((acc, key) => { acc[key] = contactEmailsMapWithDuplicates[key]?.[0]; return acc; }, {}); return { contactEmailsMap, contactEmailsMapWithDuplicates }; }; interface Props { children?: ReactNode; } const ContactEmailsProvider = ({ children }: Props) => { const [contactEmails = []] = useContactEmails(); const [contactGroups = []] = useContactGroups(); const cache = useMemo(() => { return { contactEmails, contactGroups, ...toMapWithDuplicates(contactEmails), groupsWithContactsMap: computeGroupsMap(contactEmails, contactGroups), }; }, [contactEmails, contactGroups]); return <ContactEmailsContext.Provider value={cache}>{children}</ContactEmailsContext.Provider>; }; export default ContactEmailsProvider;
6,005
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/ContactGroupDropdown.scss
@import '~@proton/styles/scss/lib'; .contactGroupDropdown { .dropdown-content { @include media('<=small') { display: flex; flex-flow: column nowrap; } } &-list-container { @include media('<=small') { min-block-size: 5em; } @include media('>small') { max-inline-size: 20em; max-block-size: 15em; } } }
6,006
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/ContactGroupDropdown.tsx
import { ChangeEvent, FormEvent, ReactNode, useEffect, useMemo, useState } from 'react'; import { c } from 'ttag'; import { Button, ButtonProps } from '@proton/atoms'; import { getContactGroupsDelayedSaveChanges, hasReachedContactGroupMembersLimit, } from '@proton/shared/lib/contacts/helpers/contactGroup'; import { validateEmailAddress } from '@proton/shared/lib/helpers/email'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import { normalize } from '@proton/shared/lib/helpers/string'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts/Contact'; import clsx from '@proton/utils/clsx'; import { DropdownButton, DropdownSizeUnit } from '../../components'; import Dropdown from '../../components/dropdown/Dropdown'; import Icon from '../../components/icon/Icon'; import Checkbox from '../../components/input/Checkbox'; import SearchInput from '../../components/input/SearchInput'; import { usePopperAnchor } from '../../components/popper'; import Mark from '../../components/text/Mark'; import Tooltip from '../../components/tooltip/Tooltip'; import { generateUID } from '../../helpers'; import { useContactEmails, useContactGroups, useMailSettings, useUser } from '../../hooks'; import { ContactGroupEditProps } from './group/ContactGroupEditModal'; import useApplyGroups from './hooks/useApplyGroups'; import { ContactGroupLimitReachedProps } from './modals/ContactGroupLimitReachedModal'; import { SelectEmailsProps } from './modals/SelectEmailsModal'; import './ContactGroupDropdown.scss'; const UNCHECKED = 0; const CHECKED = 1; const INDETERMINATE = 2; /** * Build initial dropdown model */ const getModel = (contactGroups: ContactGroup[] = [], contactEmails: ContactEmail[]) => { if (!contactGroups.length) { return Object.create(null); } return contactGroups.reduce((acc, { ID }) => { const inGroup = contactEmails.filter(({ LabelIDs = [] }) => { return LabelIDs.includes(ID); }); if (inGroup.length) { acc[ID] = contactEmails.length === inGroup.length ? CHECKED : INDETERMINATE; } else { acc[ID] = UNCHECKED; } return acc; }, Object.create(null)); }; interface Props extends ButtonProps { children?: ReactNode; className?: string; disabled?: boolean; contactEmails: ContactEmail[]; tooltip?: string; forToolbar?: boolean; onDelayedSave?: (changes: { [groupID: string]: boolean }) => void; onLock?: (lock: boolean) => void; onSuccess?: () => void; onGroupEdit: (props: ContactGroupEditProps) => void; onLimitReached?: (props: ContactGroupLimitReachedProps) => void; onUpgrade: () => void; // Required when called with more than 1 contactEmail at a time onSelectEmails?: (props: SelectEmailsProps) => Promise<ContactEmail[]>; } const ContactGroupDropdown = ({ children, className, contactEmails, disabled = false, forToolbar = false, tooltip = c('Action').t`Add to group`, onDelayedSave, onLock: onLockWidget, onSuccess, onGroupEdit, onLimitReached, onUpgrade, onSelectEmails, ...rest }: Props) => { const [mailSettings] = useMailSettings(); const [{ hasPaidMail }] = useUser(); const [keyword, setKeyword] = useState(''); const [loading, setLoading] = useState(false); const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); const [contactGroups = []] = useContactGroups(); const [userContactEmails = []] = useContactEmails(); const [initialModel, setInitialModel] = useState<{ [groupID: string]: number }>(Object.create(null)); const [model, setModel] = useState<{ [groupID: string]: number }>(Object.create(null)); const [uid] = useState(generateUID('contactGroupDropdown')); const [lock, setLock] = useState(false); const { applyGroups, contactGroupLimitReachedModal } = useApplyGroups(setLock, setLoading, onSelectEmails); // If the name and email are not empty, we can create a new group, otherwise we disable the button const { Email, Name } = contactEmails[0] ?? {}; const canCreateNewGroup = Email !== '' && Name?.trim() !== '' && validateEmailAddress(Email ?? ''); useEffect(() => onLockWidget?.(isOpen), [isOpen]); const handleClick = () => { if (hasPaidMail) { if (hasReachedContactGroupMembersLimit(contactEmails.length, mailSettings, false)) { toggle(); } else { onLimitReached?.({}); } } else { onUpgrade(); } }; const handleCheck = (contactGroupID: string) => ({ target }: ChangeEvent<HTMLInputElement>) => setModel({ ...model, [contactGroupID]: +target.checked }); const handleCreateContactGroup = async (groupID: string) => { // If creating a group with a delayed save, check the associated checkbox handleCheck(groupID); // Do the delayed save with the group ID if (onDelayedSave) { onDelayedSave({ [groupID]: true }); } }; const handleAdd = () => { // Should be handled differently with the delayed save, because we need to add the current email to the new group onGroupEdit({ selectedContactEmails: contactEmails, onDelayedSave: onDelayedSave ? handleCreateContactGroup : undefined, }); close(); }; const handleApply = async () => { const changes = Object.entries(model).reduce<{ [groupID: string]: boolean }>((acc, [groupID, isChecked]) => { if (isChecked !== initialModel[groupID]) { acc[groupID] = isChecked === CHECKED; } return acc; }, {}); // Use delayed save when editing a contact, in this case contact might not be created yet so we save later if (onDelayedSave) { const updatedChanges = getContactGroupsDelayedSaveChanges({ userContactEmails, changes, onLimitReached, model, initialModel, mailSettings, }); onDelayedSave(updatedChanges); } else { await applyGroups(contactEmails, changes); } close(); onSuccess?.(); }; useEffect(() => { if (isOpen) { const initialModel = getModel(contactGroups, contactEmails); setInitialModel(initialModel); setModel(initialModel); } }, [contactGroups, contactEmails, isOpen]); const isPristine = useMemo(() => { return isDeepEqual(initialModel, model); }, [initialModel, model]); const filteredContactGroups = useMemo(() => { if (!Array.isArray(contactGroups)) { return []; } const normalizedKeyword = normalize(keyword, true); if (!normalizedKeyword.length) { return contactGroups; } return contactGroups.filter(({ Name }) => normalize(Name, true).includes(normalizedKeyword)); }, [keyword, contactGroups]); const handleSubmit = async (e: FormEvent) => { e.preventDefault(); setLoading(true); try { await handleApply(); } finally { setLoading(false); } }; return ( <> <Tooltip title={tooltip}> <DropdownButton ref={anchorRef} isOpen={isOpen} onClick={handleClick} hasCaret={!forToolbar} disabled={disabled} className={clsx([forToolbar ? 'button-for-icon' : 'flex flex-align-items-center', className])} {...rest} > {children} </DropdownButton> </Tooltip> <Dropdown id="contact-group-dropdown" className="contactGroupDropdown" isOpen={isOpen} anchorRef={anchorRef} onClose={close} autoClose={false} autoCloseOutside={!lock} size={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: DropdownSizeUnit.Viewport }} > <form onSubmit={handleSubmit}> <div className="flex flex-justify-space-between flex-align-items-center m-4 mb-0"> <strong>{c('Label').t`Add to group`}</strong> <Tooltip title={ canCreateNewGroup ? c('Info').t`Create a new contact group` : c('Info').t`Please provide a name and an email address for creating a group.` } > <div> <Button icon color="norm" size="small" onClick={handleAdd} className="flex flex-align-items-center" data-prevent-arrow-navigation disabled={!canCreateNewGroup} > <Icon name="users" alt={c('Action').t`Create a new contact group`} /> + </Button> </div> </Tooltip> </div> <div className="m-4 mb-0"> <SearchInput value={keyword} onChange={setKeyword} autoFocus placeholder={c('Placeholder').t`Filter groups`} data-prevent-arrow-navigation /> </div> <div className="scroll-if-needed mt-4 contactGroupDropdown-list-container"> {filteredContactGroups.length ? ( <ul className="unstyled my-0"> {filteredContactGroups.map(({ ID, Name, Color }) => { const checkboxId = `${uid}${ID}`; return ( <li key={ID} className="dropdown-item w-full flex flex-nowrap flex-align-items-center py-2 px-4" > <Checkbox className="flex-item-noshrink" id={checkboxId} checked={model[ID] === CHECKED} indeterminate={model[ID] === INDETERMINATE} onChange={handleCheck(ID)} /> <label htmlFor={checkboxId} className="flex flex-align-items-center flex-item-fluid flex-nowrap" data-testid={`contact-group-dropdown:item-${Name}`} > <Icon name="circle-filled" className="ml-1 mr-2 flex-item-noshrink" size={16} color={Color} /> <span className="flex-item-fluid text-ellipsis" title={Name}> <Mark value={keyword}>{Name}</Mark> </span> </label> </li> ); })} </ul> ) : null} {!filteredContactGroups.length && keyword ? ( <div className="w-full flex flex-nowrap flex-align-items-center py-2 px-4"> <Icon name="exclamation-circle" className="mr-2" /> {c('Info').t`No group found`} </div> ) : null} </div> <div className="m-4"> <Button color="norm" fullWidth loading={loading} disabled={isPristine || !filteredContactGroups.length} data-prevent-arrow-navigation type="submit" data-testid="contact-group-dropdown:apply-chosen-groups" > {c('Action').t`Apply`} </Button> </div> </form> </Dropdown> {contactGroupLimitReachedModal} </> ); }; export default ContactGroupDropdown;
6,007
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/ContactImage.tsx
import { useEffect, useState } from 'react'; import { useMailSettings } from '@proton/components/hooks'; import { getInitials } from '@proton/shared/lib/helpers/string'; import { HIDE_SENDER_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import clsx from '@proton/utils/clsx'; import useSenderImage from './hooks/useSenderImage'; interface Props { email: string; name: string; className?: string; bimiSelector?: string; displaySenderImage?: boolean; } const ContactImage = ({ email, name, className, bimiSelector, displaySenderImage }: Props) => { const [mailSettings] = useMailSettings(); const canLoad = !!displaySenderImage && !!email && mailSettings?.HideSenderImages === HIDE_SENDER_IMAGES.SHOW; const url = useSenderImage(canLoad ? email : '', bimiSelector); const [tryToLoad, setTryToLoad] = useState(false); useEffect(() => { if (url) { setTryToLoad(true); } }, [url]); if (tryToLoad) { return ( <img className={clsx(className, 'item-sender-image')} alt="" width="32" src={url} onError={() => setTryToLoad(false)} loading="lazy" // Lazy load the image only when it's in the viewport data-testid="contact-image" style={{ inlineSize: '2rem' }} // 32px, but following main font size /> ); } return <span data-testid="contact-initials">{getInitials(name)}</span>; }; export default ContactImage;
6,008
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/ContactProvider.tsx
import { ReactNode, useLayoutEffect } from 'react'; import useInstance from '@proton/hooks/useInstance'; import { EVENT_ACTIONS } from '@proton/shared/lib/constants'; import createCache from '@proton/shared/lib/helpers/cache'; import createLRU from '@proton/shared/lib/helpers/lru'; import { STATUS } from '@proton/shared/lib/models/cache'; import { useEventManager } from '../../hooks'; import ContactProviderContext from './ContactProviderContext'; interface Props { children: ReactNode; } /** * The purpose of this provider is to synchronize individual contact fetches with updates from the event manager, * and to have a separate LRU cache for it. */ const ContactProvider = ({ children }: Props) => { const { subscribe } = useEventManager(); const cache = useInstance(() => { return createCache(createLRU({ max: 10 })); }); useLayoutEffect(() => { return subscribe(({ Contacts }: any) => { if (!Array.isArray(Contacts)) { return; } for (const { ID, Action, Contact } of Contacts) { // Ignore updates for non-fetched contacts. if (!cache.has(ID)) { continue; } if (Action === EVENT_ACTIONS.DELETE) { cache.delete(ID); } if (Action === EVENT_ACTIONS.UPDATE) { // The contact is always received in full, so we can ignore if the contact would be currently fetching (to merge the old data) cache.set(ID, { value: Contact, status: STATUS.RESOLVED }); } } }); }, []); return <ContactProviderContext.Provider value={cache}>{children}</ContactProviderContext.Provider>; }; export default ContactProvider;
6,009
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/ContactProviderContext.ts
import { createContext } from 'react'; export default createContext(new Map());
6,010
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/index.ts
export { default as ContacEmailsProvider } from './ContactEmailsProvider'; export { default as ContactGroupDropdown } from './ContactGroupDropdown'; export { default as ContactImage } from './ContactImage'; export { default as ContactProvider } from './ContactProvider'; export { default as ContactEditModal } from './edit/ContactEditModal'; export { default as ContactGroupModal } from './group/ContactGroupEditModal'; export { default as useApplyGroups } from './hooks/useApplyGroups'; export { useContactModals } from './hooks/useContactModals'; export { default as useSenderImage } from './hooks/useSenderImage'; export { default as ContactsRow } from './lists/ContactRow'; export { default as ContactsList } from './lists/ContactsList'; export { default as MergeModal } from './merge/ContactMergeModal'; export { default as ContactDeleteModal } from './modals/ContactDeleteModal'; export { default as ContactExportingModal } from './modals/ContactExportingModal'; export { default as ContactSelectorModal } from './selector/ContactSelectorModal'; export { default as ContactDetailsModal } from './view/ContactDetailsModal'; export { default as ContactView } from './view/ContactView'; export { default as ContactViewErrors } from './view/ContactViewErrors';
6,011
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/ContactEditLabel.tsx
import { getAllTypes, getOtherInformationFields } from '@proton/shared/lib/helpers/contacts'; import { VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { Label, Option, SelectTwo } from '../../../components'; import { SelectChangeEvent } from '../../../components/selectTwo/select'; import ContactLabelProperty from '../view/ContactLabelProperty'; interface Props { vCardProperty: VCardProperty; onChangeVCard: (vCardProperty: VCardProperty) => void; /** * fixedType means you don't want to change the type of data (ie: no select) */ fixedType?: boolean; /** * list of types not to propose in the other information fields * mostly useful not to propose second instance of fields limited to one entry in vcards */ filteredTypes?: string[]; } const ContactEditLabel = ({ vCardProperty, onChangeVCard, fixedType = false, filteredTypes = [] }: Props) => { const { field } = vCardProperty; const types = getAllTypes(); const fieldTypes = types[field]; const type = vCardProperty.params?.type || ''; const fieldsToReset = ['bday', 'anniversary', 'photo', 'logo']; const otherInformationFields = getOtherInformationFields(); const handleChangeType = ({ value }: SelectChangeEvent<string>) => { onChangeVCard({ ...vCardProperty, params: { ...vCardProperty.params, type: value } }); }; const handleChangeField = ({ value }: SelectChangeEvent<string>) => { let maybeResetValue = {}; if (fieldsToReset.includes(vCardProperty.field) || value.includes(vCardProperty.field)) { maybeResetValue = { value: undefined }; } onChangeVCard({ ...vCardProperty, field: value, ...maybeResetValue }); }; if (!fixedType && otherInformationFields.map(({ value: f }) => f).includes(field)) { const selectedField = otherInformationFields.find((otherField) => otherField.value === field); const filteredOtherInformationFields = otherInformationFields.filter( (field) => !filteredTypes.includes(field.value) ); return ( <Label className="pt-0 md:mr-6 w-full"> <SelectTwo value={field} onChange={handleChangeField} title={selectedField?.text} data-testid="create-contact:other-info-select" > {filteredOtherInformationFields.map((field) => ( <Option data-testid={`create-contact:dropdown-item-${field.text}`} key={field.value} title={field.text} value={field.value} /> ))} </SelectTwo> </Label> ); } if (field === 'fn' || field === 'n' || fixedType || !fieldTypes.map(({ value: type }) => type).includes(type)) { return <ContactLabelProperty className="pt-2" field={field} type={type} />; } const selectedType = fieldTypes.find((fieldType) => fieldType.value === type) || fieldTypes[0]; return ( <Label className="pt-0 md:mr-6 w-full"> <SelectTwo value={type} onChange={handleChangeType} title={selectedType.text}> {fieldTypes.map((fieldType) => ( <Option key={fieldType.value} title={fieldType.text} value={fieldType.value} /> ))} </SelectTwo> </Label> ); }; export default ContactEditLabel;
6,012
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/ContactEditModal.test.tsx
import { fireEvent, waitFor } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import { API_CODES, CONTACT_CARD_TYPE } from '@proton/shared/lib/constants'; import { parseToVCard } from '@proton/shared/lib/contacts/vcard'; import { wait } from '@proton/shared/lib/helpers/promise'; import { api, clearAll, mockedCryptoApi, notificationManager, render } from '../tests/render'; import ContactEditModal, { ContactEditModalProps, ContactEditProps } from './ContactEditModal'; jest.mock('../../../hooks/useAuthentication', () => { return { __esModule: true, default: jest.fn(() => ({ getUID: jest.fn(), })), }; }); jest.mock('../../../hooks/useConfig', () => () => ({ API_URL: 'api' })); jest.mock('@proton/shared/lib/helpers/image.ts', () => { return { toImage: (src: string) => ({ src }), }; }); describe('ContactEditModal', () => { const props: ContactEditProps & ContactEditModalProps = { contactID: 'ContactID', vCardContact: { fn: [] }, onUpgrade: jest.fn(), onSelectImage: jest.fn(), onGroupEdit: jest.fn(), onLimitReached: jest.fn(), }; beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should prefill all fields with contact values', async () => { const vcard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN:J. Doe FN:FN2 EMAIL:jdoe@example.com NOTE:TestNote ADR:1;2;3;4;5;6;7 ADR:;;;;;;testadr TEL:testtel PHOTO:https://example.com/myphoto.jpg END:VCARD`; const vCardContact = parseToVCard(vcard); const { getByDisplayValue } = render(<ContactEditModal open={true} {...props} vCardContact={vCardContact} />); // To see the image loaded await wait(0); getByDisplayValue('J. Doe'); expect(document.querySelector('img[src="https://example.com/myphoto.jpg"]')).not.toBe(null); getByDisplayValue('FN2'); getByDisplayValue('jdoe@example.com'); getByDisplayValue('testtel'); getByDisplayValue('1'); getByDisplayValue('4'); getByDisplayValue('5'); getByDisplayValue('6'); getByDisplayValue('7'); getByDisplayValue('testadr'); getByDisplayValue('TestNote'); }); it.skip('should update basic properties', async () => { const vcard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN:J. Doe EMAIL:jdoe@example.com TEL:testtel NOTE:TestNote END:VCARD`; const vCardContact = parseToVCard(vcard); const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByDisplayValue, getByTestId, getByText } = render( <ContactEditModal open={true} {...props} vCardContact={vCardContact} /> ); const name = getByDisplayValue('J. Doe'); fireEvent.change(name, { target: { value: 'New name' } }); const email = getByDisplayValue('jdoe@example.com'); fireEvent.change(email, { target: { value: 'new@email.com' } }); const tel = getByDisplayValue('testtel'); fireEvent.change(tel, { target: { value: 'newtel' } }); const note = getByDisplayValue('TestNote'); fireEvent.change(note, { target: { value: 'NewNote' } }); const addButton = getByTestId('add-other'); fireEvent.click(addButton); const properties = document.querySelectorAll('[data-contact-property-id]'); const newProperty = properties[properties.length - 1]; const typeSelect = newProperty.querySelector('button.select'); fireEvent.click(typeSelect as Element); const titleOption = document.querySelector('.dropdown button[title="Title"]'); fireEvent.click(titleOption as Element); const titleInput = getByTestId('Title'); fireEvent.change(titleInput, { target: { value: 'NewTitle' } }); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => { if (notificationManager.createNotification.mock.calls.length > 0) { throw new Error(); } }); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; const encryptedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.ENCRYPTED_AND_SIGNED ).Data; const expectedSignedCard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN;PREF=1:New name ITEM1.EMAIL;PREF=1:new@email.com END:VCARD`.replaceAll('\n', '\r\n'); const expectedEncryptedCard = `BEGIN:VCARD VERSION:4.0 TEL;PREF=1:newtel NOTE:NewNote N:;;;; TITLE:NewTitle END:VCARD`.replaceAll('\n', '\r\n'); expect(signedCardContent).toBe(expectedSignedCard); expect(encryptedCardContent).toBe(expectedEncryptedCard); }); it('should create a contact', async () => { const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByTestId, getByText } = render(<ContactEditModal open={true} {...props} />); const firstName = getByTestId('First name'); fireEvent.change(firstName, { target: { value: 'Bruno' } }); const lastName = getByTestId('Last name'); fireEvent.change(lastName, { target: { value: 'Mars' } }); const displayName = getByTestId('Enter a display name or nickname'); fireEvent.change(displayName, { target: { value: 'New name' } }); const email = getByTestId('Email'); fireEvent.change(email, { target: { value: 'new@email.com' } }); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; const encryptedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.ENCRYPTED_AND_SIGNED ).Data; expect(signedCardContent).toContain('FN;PREF=1:New name'); expect(signedCardContent).toContain('ITEM1.EMAIL;PREF=1:new@email.com'); expect(encryptedCardContent).toContain('N:Mars;Bruno;;;'); }); it('should trigger an error if display name is empty when creating a contact', async () => { const { getByText } = render(<ContactEditModal open={true} {...props} />); const saveButton = getByText('Save'); fireEvent.click(saveButton); const errorZone = getByText('Please provide either a first name, a last name or a display name'); expect(errorZone).toBeVisible(); }); it('should trigger an error if display name is empty when editing a contact', async () => { const vcard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 EMAIL:jdoe@example.com END:VCARD`; const vCardContact = parseToVCard(vcard); const { getByText } = render(<ContactEditModal open={true} {...props} vCardContact={vCardContact} />); const saveButton = getByText('Save'); fireEvent.click(saveButton); const errorZone = getByText('This field is required'); expect(errorZone).toBeVisible(); }); });
6,013
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/ContactEditModal.tsx
import { useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { addVCardProperty, getSortedProperties, getVCardProperties, removeVCardProperty, updateVCardContact, } from '@proton/shared/lib/contacts/properties'; import { isContactNameValid, isFirstLastNameValid } from '@proton/shared/lib/contacts/property'; import { prepareForEdition } from '@proton/shared/lib/contacts/surgery'; import { isMultiValue } from '@proton/shared/lib/contacts/vcard'; import { getOtherInformationFields } from '@proton/shared/lib/helpers/contacts'; import { canonicalizeEmail, validateEmailAddress } from '@proton/shared/lib/helpers/email'; import { ContactEmailModel } from '@proton/shared/lib/interfaces/contacts/Contact'; import { VCardContact, VCardProperty, VcardNValue } from '@proton/shared/lib/interfaces/contacts/VCard'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import isTruthy from '@proton/utils/isTruthy'; import randomIntFromInterval from '@proton/utils/randomIntFromInterval'; import { ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components'; import { useContactEmails, useEventManager, useHandler, useNotifications } from '../../../hooks'; import { ContactGroupEditProps } from '../group/ContactGroupEditModal'; import useApplyGroups from '../hooks/useApplyGroups'; import { useSaveVCardContact } from '../hooks/useSaveVCardContact'; import { ContactGroupLimitReachedProps } from '../modals/ContactGroupLimitReachedModal'; import { ContactImageProps } from '../modals/ContactImageModal'; import ContactEditProperties from './ContactEditProperties'; import ContactEditProperty from './ContactEditProperty'; const otherInformationFields = getOtherInformationFields().map(({ value }) => value); export interface ContactEditProps { contactID?: string; vCardContact?: VCardContact; newField?: string; } export interface ContactEditModalProps { onUpgrade: () => void; onChange?: () => void; onSelectImage: (props: ContactImageProps) => void; onGroupEdit: (props: ContactGroupEditProps) => void; onLimitReached: (props: ContactGroupLimitReachedProps) => void; } type Props = ContactEditProps & ContactEditModalProps & ModalProps; const ContactEditModal = ({ contactID, vCardContact: inputVCardContact = { fn: [] }, newField, onUpgrade, onChange, onSelectImage, onGroupEdit, onLimitReached, ...rest }: Props) => { const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const { call } = useEventManager(); const [isSubmitted, setIsSubmitted] = useState(false); const [vCardContact, setVCardContact] = useState<VCardContact>(prepareForEdition(inputVCardContact)); const displayNameFieldRef = useRef<HTMLInputElement>(null); const firstNameFieldRef = useRef<HTMLInputElement>(null); const [contactEmails = [], loadingContactEmails] = useContactEmails(); const [modelContactEmails, setModelContactEmails] = useState<SimpleMap<ContactEmailModel>>({}); const saveVCardContact = useSaveVCardContact(); const { applyGroups, contactGroupLimitReachedModal } = useApplyGroups(); const title = contactID ? c('Title').t`Edit contact` : c('Title').t`Create contact`; const displayNameProperty = getSortedProperties(vCardContact, 'fn')[0] as VCardProperty<string>; const nameProperty = getSortedProperties(vCardContact, 'n')[0] as VCardProperty<VcardNValue>; const photoProperty = getSortedProperties(vCardContact, 'photo')[0] as VCardProperty<string>; const getContactEmail = (email: string) => { return contactEmails.find((contactEmail) => { if (contactID) { return ( contactEmail.ContactID === contactID && canonicalizeEmail(contactEmail.Email) === canonicalizeEmail(email) ); } // If the contact did not exist before adding contact group to of his addresses, contactID is not defined, and we have no ways to get it. // If we rely on thi contactID, adding contact groups would become impossible. // => To avoid adding to the wrong contact, check the contact name + the email instead // This is still not perfect, because creating a new contact with the same name and same address than a one existing // might (depending on the first one found in the list) add the group to the older contact. // That's a super rare case, so I will suggest to live with this "bug" // --- // We also need to trim the value, contactEmails names are trimmed when we save a new contact, but we might have an extra space in the input return ( displayNameProperty.value.trim() === contactEmail.Name && canonicalizeEmail(contactEmail.Email) === canonicalizeEmail(email) ); }); }; useEffect(() => { if (loadingContactEmails) { return; } const newModelContactEmails = { ...modelContactEmails }; const emails = vCardContact.email || []; const displayName = displayNameProperty.value; const givenName = vCardContact?.n?.value.givenNames.join(' ').trim() || ''; const familyName = vCardContact?.n?.value.familyNames.join(' ').trim() || ''; const computedName = `${givenName} ${familyName}`; // The name can either be the display name, or the computed name if we're creating a new contact const Name = contactID ? displayName : displayName || computedName; emails.forEach((emailProperty) => { const uid = emailProperty.uid; const email = emailProperty.value || ''; const existingModel = Object.values(newModelContactEmails).find( (contactEmail) => contactEmail?.uid === uid ); if (existingModel) { if (existingModel.Email !== email) { const oldEmail = existingModel.Email; newModelContactEmails[email] = { ...existingModel, Email: email, Name, }; delete newModelContactEmails[oldEmail]; } return; } const existingContactEmail = getContactEmail(email); if (existingContactEmail) { newModelContactEmails[email] = { ...existingContactEmail, uid, changes: {}, Name, }; return; } newModelContactEmails[email] = { uid, changes: {}, Email: email, ContactID: contactID || '', LabelIDs: [], Name, }; }); setModelContactEmails(newModelContactEmails); }, [loadingContactEmails, vCardContact.email]); // The condition defining if the form is valid is different if we are editing an existing contact or creating a new one // In all cases we want to make sure that all emails are correct const isFormValid = () => { const allEmailsAddress = vCardContact.email?.map((emailProperty) => emailProperty.value).filter(isTruthy) ?? []; // Check if all present address are valid email addresses if (!allEmailsAddress.every((email) => validateEmailAddress(email))) { return false; } const displayName = displayNameProperty.value.trim(); const givenName = nameProperty.value.givenNames[0].trim(); const familyName = nameProperty.value.familyNames[0].trim(); const fullName = `${givenName} ${familyName}`; // Check if there is any name present in the contact if (!familyName && !givenName && !displayName) { return false; } // Check if the last name is valid if (familyName && !isFirstLastNameValid(familyName)) { return false; } // Check if the first name is valid if (givenName && !isFirstLastNameValid(givenName)) { return false; } // Check if the display name is valid when editing a contact if ((contactID && displayName && !isContactNameValid(displayName)) || (contactID && !displayName)) { return false; } // Check if the full name is valid when creating a contact if ((!contactID && fullName && !isContactNameValid(fullName)) || (!contactID && !fullName)) { return false; } return true; }; const handleRemove = (propertyUID: string) => { setVCardContact((vCardContact) => { return removeVCardProperty(vCardContact, propertyUID); }); }; const focusOnField = (uid: string) => { const elm = document.querySelector(`[data-contact-property-id="${uid}"]`) as HTMLElement; // Try to focus on the input field, if not present try the textarea const hasInput = elm?.querySelector('input'); if (hasInput) { hasInput.focus(); return; } elm?.querySelector('textarea')?.focus(); }; const handleAdd = (inputField?: string) => () => { let field = inputField; if (!field) { // Get random field from other info, but not a limited one const properties = getVCardProperties(vCardContact); const filteredOtherInformationFields = otherInformationFields.filter( (field) => isMultiValue(field) || !properties.find((property) => property.field === field) ); const index = randomIntFromInterval(0, filteredOtherInformationFields.length - 1); field = filteredOtherInformationFields[index]; } setVCardContact((vCardContact) => { const { newVCardContact, newVCardProperty } = addVCardProperty(vCardContact, { field } as VCardProperty); setTimeout(() => focusOnField(newVCardProperty.uid)); return newVCardContact; }); }; // eslint-disable-next-line @typescript-eslint/no-misused-promises const saveContactGroups = useHandler(async () => { await Promise.all( Object.values(modelContactEmails).map(async (modelContactEmail) => { if (modelContactEmail) { const contactEmail = getContactEmail(modelContactEmail.Email); if (contactEmail) { await applyGroups([contactEmail], modelContactEmail.changes, true); } } }) ); }); const handleSubmit = async () => { setIsSubmitted(true); if (!isFormValid()) { firstNameFieldRef.current?.focus(); return; } try { await saveVCardContact(contactID, vCardContact); await call(); await saveContactGroups(); onChange?.(); createNotification({ text: c('Success').t`Contact saved` }); } finally { rest.onClose?.(); } }; const handleChangeVCard = (property: VCardProperty) => { setVCardContact((vCardContact) => { return updateVCardContact(vCardContact, property); }); }; const handleContactEmailChange = (contactEmail: ContactEmailModel) => setModelContactEmails((modelContactEmails) => ({ ...modelContactEmails, [contactEmail.Email]: contactEmail })); useEffect(() => { if (newField) { handleAdd(newField)(); } }, [newField]); // Default focus on name field useEffect(() => { firstNameFieldRef.current?.focus(); }, []); return ( <> <ModalTwo size="large" className="contacts-modal" {...rest}> <ModalTwoHeader title={title} /> <ModalTwoContent> <div className="mb-4"> <ContactEditProperty ref={firstNameFieldRef} vCardContact={vCardContact} isSubmitted={isSubmitted} onRemove={handleRemove} actionRow={false} vCardProperty={nameProperty} onChangeVCard={handleChangeVCard} onUpgrade={onUpgrade} onSelectImage={onSelectImage} onGroupEdit={onGroupEdit} /> <ContactEditProperty ref={displayNameFieldRef} vCardContact={vCardContact} isSubmitted={isSubmitted} onRemove={handleRemove} actionRow={false} vCardProperty={displayNameProperty} onChangeVCard={handleChangeVCard} onUpgrade={onUpgrade} onSelectImage={onSelectImage} onGroupEdit={onGroupEdit} /> <ContactEditProperty vCardContact={vCardContact} isSubmitted={isSubmitted} onRemove={handleRemove} actionRow fixedType vCardProperty={photoProperty} onChangeVCard={handleChangeVCard} onUpgrade={onUpgrade} onSelectImage={onSelectImage} onGroupEdit={onGroupEdit} /> </div> <ContactEditProperties field="fn" isSignatureVerified isSubmitted={isSubmitted} onRemove={handleRemove} vCardContact={vCardContact} onChangeVCard={handleChangeVCard} onUpgrade={onUpgrade} onSelectImage={onSelectImage} onGroupEdit={onGroupEdit} /> <ContactEditProperties field="email" isSignatureVerified isSubmitted={isSubmitted} onRemove={handleRemove} sortable onAdd={handleAdd('email')} contactEmails={modelContactEmails} onContactEmailChange={handleContactEmailChange} vCardContact={vCardContact} onChangeVCard={handleChangeVCard} onUpgrade={onUpgrade} onSelectImage={onSelectImage} onGroupEdit={onGroupEdit} onLimitReached={onLimitReached} /> {['tel', 'adr', 'bday', 'note'].map((item) => ( <ContactEditProperties key={item} field={item} isSignatureVerified isSubmitted={isSubmitted} onRemove={handleRemove} sortable onAdd={handleAdd(item)} vCardContact={vCardContact} onChangeVCard={handleChangeVCard} onUpgrade={onUpgrade} onSelectImage={onSelectImage} onGroupEdit={onGroupEdit} /> ))} <ContactEditProperties isSubmitted={isSubmitted} isSignatureVerified onRemove={handleRemove} onAdd={handleAdd()} vCardContact={vCardContact} onChangeVCard={handleChangeVCard} onUpgrade={onUpgrade} onSelectImage={onSelectImage} onGroupEdit={onGroupEdit} /> </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" loading={loading} data-testid="create-contact:save" onClick={() => withLoading(handleSubmit())} > {c('Action').t`Save`} </Button> </ModalTwoFooter> </ModalTwo> {contactGroupLimitReachedModal} </> ); }; export default ContactEditModal;
6,014
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/ContactEditProperties.tsx
import { Ref, forwardRef, useCallback, useMemo } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { OTHER_INFORMATION_FIELDS } from '@proton/shared/lib/contacts/constants'; import { compareVCardPropertyByPref, compareVCardPropertyByUid, getSortedProperties, getVCardProperties, } from '@proton/shared/lib/contacts/properties'; import { EXACTLY_ONE_MAY_BE_PRESENT, PROPERTIES } from '@proton/shared/lib/contacts/vcard'; import { SimpleMap } from '@proton/shared/lib/interfaces'; import { ContactEmailModel } from '@proton/shared/lib/interfaces/contacts'; import { VCardContact, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import isTruthy from '@proton/utils/isTruthy'; import move from '@proton/utils/move'; import { Icon, IconName, OrderableContainer, OrderableElement } from '../../../components'; import { ContactGroupEditProps } from '../group/ContactGroupEditModal'; import { ContactGroupLimitReachedProps } from '../modals/ContactGroupLimitReachedModal'; import { ContactImageProps } from '../modals/ContactImageModal'; import EncryptedIcon from '../view/EncryptedIcon'; import ContactEditProperty from './ContactEditProperty'; const ICONS: { [key: string]: IconName } = { fn: 'user', email: 'envelope', tel: 'phone', adr: 'map-pin', bday: 'candles-cake', note: 'note', other: 'info-circle', }; interface Props { field?: string; isSignatureVerified: boolean; sortable?: boolean; onAdd?: () => void; onRemove: (value: string) => void; isSubmitted?: boolean; contactEmails?: SimpleMap<ContactEmailModel>; onContactEmailChange?: (contactEmail: ContactEmailModel) => void; vCardContact: VCardContact; onChangeVCard: (vCardProperty: VCardProperty) => void; onUpgrade: () => void; onSelectImage: (props: ContactImageProps) => void; onGroupEdit: (props: ContactGroupEditProps) => void; onLimitReached?: (props: ContactGroupLimitReachedProps) => void; } const ContactEditProperties = ( { isSignatureVerified, field, sortable: inputSortable = false, onAdd, onRemove, isSubmitted = false, contactEmails, onContactEmailChange, vCardContact, onChangeVCard, onUpgrade, onSelectImage, onGroupEdit, onLimitReached, }: Props, ref: Ref<HTMLInputElement> ) => { const TITLES: { [key: string]: string } = { fn: c('Title').t`Other names`, email: c('Title').t`Email addresses`, tel: c('Title').t`Phone numbers`, adr: c('Title').t`Addresses`, bday: c('Title').t`Birthday`, note: c('Title').t`Notes`, other: c('Title').t`Other information`, }; const title = field ? TITLES[field] : TITLES.other; const iconName = field ? ICONS[field] : ICONS.other; const fields = field ? [field] : OTHER_INFORMATION_FIELDS; const excluded = [ getSortedProperties(vCardContact, 'fn')[0]?.uid, getSortedProperties(vCardContact, 'photo')[0]?.uid, ]; const properties: VCardProperty[] = getVCardProperties(vCardContact) .filter(({ field }) => fields.includes(field)) .filter(({ uid }) => !excluded.includes(uid)) .sort((a, b) => { if (fields.length === 1) { return compareVCardPropertyByPref(a, b); } return compareVCardPropertyByUid(a, b); }); const sortable = inputSortable && properties.length > 1; // Only allow adding a property if there are no properties or if the field is not fn or bday const canAdd = properties.length === 0 || !['fn', 'bday'].includes(field || ''); const rows = useMemo(() => { const isOtherFields = fields === OTHER_INFORMATION_FIELDS; const filteredTypes = isOtherFields ? properties .filter(({ field }) => PROPERTIES[field].cardinality === EXACTLY_ONE_MAY_BE_PRESENT) .map(({ field }) => field) : []; return properties.map((property) => ( <ContactEditProperty key={property.uid} vCardContact={vCardContact} ref={ref} isSubmitted={isSubmitted} onRemove={onRemove} sortable={sortable} filteredTypes={ // Accept the currently set type filteredTypes.filter((type) => property.field !== type) } contactEmail={contactEmails?.[property.value as string]} onContactEmailChange={onContactEmailChange} vCardProperty={property} onChangeVCard={onChangeVCard} onUpgrade={onUpgrade} onSelectImage={onSelectImage} onGroupEdit={onGroupEdit} onLimitReached={onLimitReached} /> )); }, [properties, vCardContact, onChangeVCard, onRemove, onAdd, sortable]); const handleSortEnd = useCallback( ({ newIndex, oldIndex }) => { const orderedProperties = move(properties, oldIndex, newIndex); orderedProperties.forEach((property, index) => { onChangeVCard({ ...property, params: { ...property.params, pref: String(index + 1) } }); }); }, [properties, field] ); // In most cases, (other) name section will be empty, and we don't want to display it // if it is empty because the main name is always displayed at the top of the modal // only used for exceptions - old records imported with multiple names if (field === 'fn' && !properties.length) { return null; } const handleAdd = () => { if (!canAdd || !onAdd) { return; } // Other fields (at the bottom of the form) don't have fields and can be added at anytime if (!field) { onAdd(); return; } const vcardPropertyField: any = vCardContact[field as keyof VCardContact]; const presentData = vcardPropertyField?.map((item: any) => item.value).filter(isTruthy); // We add a field if all the fields are filled, or there is no data yet if (rows?.length === presentData?.length || !presentData) { onAdd(); return; } // We find the first empty row and focus on it, the row can be an input or a textarea const firstEmptyRow = vcardPropertyField?.findIndex((field: any) => { // Address field are objects and not a string, we need to make sure that all the values are empty if (field.field === 'adr') { return Object.values(field.value).every((value: any) => !value); } return !field.value; }); if (firstEmptyRow === -1) { return; } // We didn't use ref here because the ref is not available for the child rows const contactFieldToFocus = document.querySelector( `[data-contact-property-id="${vcardPropertyField[firstEmptyRow]?.uid}"]` ); const input = contactFieldToFocus?.getElementsByTagName('input')?.[0]; if (input) { input.focus(); return; } const textarea = contactFieldToFocus?.getElementsByTagName('textarea')?.[0]; if (textarea) { textarea.focus(); return; } }; return ( <div className="border-bottom mb-4" data-testid={title}> <h3 className="mb-4 flex flex-nowrap flex-align-items-center flex-item-noshrink"> <Icon className="mr-1 flex-item-noshrink" name={iconName} /> <span className="ml-0.5 mr-2">{title}</span> {((field && !['fn', 'email'].includes(field)) || field === undefined) && ( <EncryptedIcon className="flex flex-item-centered-vert flex-item-noshrink" isSignatureVerified={isSignatureVerified} /> )} </h3> {field && ['email'].includes(field) && ( <span className="text-semibold ml-5 pl-1 mb-2">{c('Info').t`Primary`}</span> )} {sortable ? ( <OrderableContainer helperClass="row--orderable" onSortEnd={handleSortEnd} useDragHandle> <div className="mt-2"> {rows.map((row, index) => ( <OrderableElement key={row.key || `row${index}`} index={index}> {row} </OrderableElement> ))} </div> </OrderableContainer> ) : ( <div>{rows}</div> )} {canAdd && ( <div className="flex flex-nowrap flex-item-noshrink"> <div className="mr-2 flex flex-align-items-center flex-item-noshrink"> <Icon name="text-align-justify" className="visibility-hidden" /> </div> <div className="flex flex-nowrap w-custom" style={{ '--w-custom': '95%' }}> <Button color="weak" shape="outline" size="small" className="mb-4" onClick={handleAdd} data-testid={field ? `add-${field}` : 'add-other'} > {c('Action').t`Add`} </Button> </div> </div> )} </div> ); }; export default forwardRef(ContactEditProperties);
6,015
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/ContactEditProperty.tsx
import { Ref, forwardRef } from 'react'; import { c } from 'ttag'; import { ContactEmail, ContactEmailModel } from '@proton/shared/lib/interfaces/contacts'; import { VCardContact, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import clsx from '@proton/utils/clsx'; import { DropdownActions, Icon, OrderableHandle } from '../../../components'; import ContactGroupDropdown from '../ContactGroupDropdown'; import { ContactGroupEditProps } from '../group/ContactGroupEditModal'; import { ContactGroupLimitReachedProps } from '../modals/ContactGroupLimitReachedModal'; import { ContactImageProps } from '../modals/ContactImageModal'; import ContactEditLabel from './ContactEditLabel'; import ContactFieldProperty from './fields/ContactFieldProperty'; interface Props { vCardProperty: VCardProperty; vCardContact: VCardContact; onChangeVCard: (vCardProperty: VCardProperty) => void; onRemove: (value: string) => void; sortable?: boolean; isSubmitted?: boolean; actionRow?: boolean; fixedType?: boolean; labelWidthClassName?: string; filteredTypes?: string[]; contactEmail?: ContactEmailModel; onContactEmailChange?: (contactEmail: ContactEmailModel) => void; onUpgrade: () => void; onSelectImage: (props: ContactImageProps) => void; onGroupEdit: (props: ContactGroupEditProps) => void; onLimitReached?: (props: ContactGroupLimitReachedProps) => void; } const ContactEditProperty = ( { vCardProperty, vCardContact, onChangeVCard, onRemove, sortable = false, isSubmitted = false, actionRow = true, labelWidthClassName, fixedType, filteredTypes, contactEmail, onContactEmailChange, onUpgrade, onSelectImage, onGroupEdit, onLimitReached, }: Props, ref: Ref<HTMLInputElement> ) => { const { field, value } = vCardProperty; const canDelete = !(field === 'photo' && !value); const list = []; // Delete is always available (except when primary and no image). Primary name has action row disabled. if (canDelete) { list.push({ color: 'weak', shape: 'outline', text: <Icon name="trash" className="m-auto" alt={c('Action').t`Delete`} />, onClick: () => { if (vCardProperty.uid) { onRemove(vCardProperty.uid); } }, }); } const handleUpdateContactGroups = (changes: { [groupID: string]: boolean }) => { if (contactEmail && onContactEmailChange) { let LabelIDs = [...contactEmail.LabelIDs]; Object.entries(changes).forEach(([groupID, checked]) => { if (checked) { LabelIDs.push(groupID); } else { LabelIDs = contactEmail.LabelIDs.filter((id: string) => id !== groupID); } }); onContactEmailChange({ ...contactEmail, LabelIDs, changes: { ...contactEmail.changes, ...changes } }); } }; // The data-contact-property-id is used to focus on the element in ContactEditProperties return ( <div className="flex flex-nowrap flex-item-noshrink" data-contact-property-id={vCardProperty.uid}> {sortable ? ( <OrderableHandle key="icon"> <div className="cursor-row-resize mr-2 flex flex-item-noshrink mb-4"> <Icon name="text-align-justify" className="mt-3 " /> </div> </OrderableHandle> ) : ( <div className="mr-2 flex flex-align-items-center flex-item-noshrink"> <Icon name="text-align-justify" className="visibility-hidden" /> </div> )} <div className="contact-modal-field relative flex flex-nowrap on-mobile-flex-column w-full flex-align-items-start"> <span className={clsx([ 'contact-modal-select flex flex-nowrap mb-2 md:mb-4 flex-align-items-start on-mobile-flex-align-self-start', labelWidthClassName || 'w-3/10', ])} > <ContactEditLabel vCardProperty={vCardProperty} onChangeVCard={onChangeVCard} fixedType={fixedType} filteredTypes={filteredTypes} /> </span> <div className="flex flex-nowrap flex-align-items-startoupas flex-item-fluid flex-item-noshrink"> <span className="flex-item-fluid mb-4"> <ContactFieldProperty ref={ref} vCardProperty={vCardProperty} vCardContact={vCardContact} onChangeVCard={onChangeVCard} isSubmitted={isSubmitted} onSelectImage={onSelectImage} /> </span> {actionRow && ( <span className="mb-4 ml-2 flex"> {list.length > 0 && ( <div className={clsx([ 'flex flex-item-noshrink h-4', field, (field === 'photo' || field === 'note' || field === 'logo' || field === 'adr') && 'flex-align-items-start', ])} > {field === 'email' && ( <ContactGroupDropdown icon color="weak" shape="outline" className="mr-2" contactEmails={[contactEmail as unknown as ContactEmail]} onDelayedSave={handleUpdateContactGroups} tooltip={c('Title').t`Contact group`} onGroupEdit={onGroupEdit} onLimitReached={onLimitReached} onUpgrade={onUpgrade} > <Icon name="users" alt={c('Action').t`Contact group`} /> </ContactGroupDropdown> )} <DropdownActions icon list={list} /> </div> )} </span> )} </div> </div> </div> ); }; export default forwardRef(ContactEditProperty);
6,016
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldAdr.tsx
import { ChangeEvent, useState } from 'react'; import { c } from 'ttag'; import { Input } from '@proton/atoms'; import { VCardAddress, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { generateUID } from '../../../../helpers'; interface Props { vCardProperty: VCardProperty<VCardAddress>; onChange: (vCardProperty: VCardProperty) => void; } const ContactFieldAdr = ({ vCardProperty, onChange }: Props) => { const [uid] = useState(generateUID('contact-adr')); const handleChange = (part: keyof VCardAddress) => ({ target }: ChangeEvent<HTMLInputElement>) => { onChange({ ...vCardProperty, value: { ...vCardProperty.value, [part]: target.value } }); }; const address = vCardProperty.value || {}; return ( <> <div className="mb-2"> <Input id={`${uid}-street`} value={address.streetAddress || ''} placeholder={c('Label').t`Street address`} onChange={handleChange('streetAddress')} data-testid="street" /> </div> {address.extendedAddress ? ( <div className="mb-2"> <Input id={`${uid}-extended`} value={address.extendedAddress || ''} placeholder={c('Label').t`Extended address`} onChange={handleChange('extendedAddress')} data-testid="extended" /> </div> ) : null} <div className="mb-2 flex gap-2"> <Input id={`${uid}-postalCode`} value={address.postalCode || ''} placeholder={c('Label').t`Postal code`} onChange={handleChange('postalCode')} data-testid="postalCode" /> <Input id={`${uid}-locality`} value={address.locality || ''} placeholder={c('Label').t`City`} onChange={handleChange('locality')} data-testid="city" className="flex-item-grow-2" /> </div> {address.postOfficeBox ? ( <div className="mb-2"> <Input id={`${uid}-postBox`} value={address.postOfficeBox || ''} placeholder={c('Label').t`Post office box`} onChange={handleChange('postOfficeBox')} data-testid="postBox" /> </div> ) : null} <div className="mb-2 flex gap-2"> <Input id={`${uid}-region`} value={address.region || ''} placeholder={c('Label').t`Region`} onChange={handleChange('region')} data-testid="region" /> <Input id={`${uid}-country`} value={address.country || ''} placeholder={c('Label').t`Country`} onChange={handleChange('country')} data-testid="country" /> </div> </> ); }; export default ContactFieldAdr;
6,017
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldDate.tsx
import { isValid } from 'date-fns'; import { getDateFromVCardProperty } from '@proton/shared/lib/contacts/property'; import { getAllFieldLabels } from '@proton/shared/lib/helpers/contacts'; import { VCardDateOrText, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { DateInput } from '../../../../components'; interface Props { vCardProperty: VCardProperty<VCardDateOrText>; onChange: (vCardProperty: VCardProperty) => void; } const ContactFieldDate = ({ vCardProperty, onChange, ...rest }: Props) => { const label = (getAllFieldLabels() as any)[vCardProperty.field] || ''; const date = getDateFromVCardProperty(vCardProperty); const handleChange = (date?: Date) => { if (!date || !isValid(date)) { return; } onChange({ ...vCardProperty, value: { ...vCardProperty.value, date } }); }; return <DateInput placeholder={label} value={date} onChange={handleChange} data-testid={label} {...rest} />; }; export default ContactFieldDate;
6,018
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldEmail.tsx
import { ChangeEvent } from 'react'; import { getAllFieldLabels } from '@proton/shared/lib/helpers/contacts'; import { VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { EmailInput } from '../../../../components'; interface Props { vCardProperty: VCardProperty<string>; onChange: (vCardProperty: VCardProperty) => void; } const ContactFieldEmail = ({ vCardProperty, onChange, ...rest }: Props) => { const label = getAllFieldLabels().email; const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { const newValue = target.value; onChange({ ...vCardProperty, value: newValue }); }; return ( <EmailInput value={vCardProperty.value} placeholder={label} onChange={handleChange} data-testid={label} {...rest} /> ); }; export default ContactFieldEmail;
6,019
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldFn.tsx
import { ChangeEvent, Ref, forwardRef } from 'react'; import { c } from 'ttag'; import { Input, InputProps } from '@proton/atoms'; import { isContactNameValid } from '@proton/shared/lib/contacts/property'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { VCardContact, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { ErrorZone } from '../../../../components'; interface Props extends Omit<InputProps, 'onChange'> { vCardContact: VCardContact; vCardProperty: VCardProperty<string>; isSubmitted: boolean; onChange: (vCardProperty: VCardProperty) => void; } const ContactFieldFn = ( { vCardContact, vCardProperty, isSubmitted, onChange, ...rest }: Props, ref: Ref<HTMLInputElement> ) => { // The version field is not present when creating new contacts const isNewContact = !vCardContact?.version; const label = c('Contact field label').t`Enter a display name or nickname`; const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { const newValue = target.value; onChange({ ...vCardProperty, value: newValue }); }; const givenName = vCardContact.n?.value.givenNames.join(' ')?.trim() ?? null; const familyName = vCardContact.n?.value.familyNames.join(' ')?.trim() ?? null; const nameTooLongError = !isContactNameValid(vCardProperty.value); // The fn field can be left empty when creating a new contact as long as something is present in the first or last name field const requiredError = isNewContact ? isSubmitted && !givenName && !familyName && requiredValidator(vCardProperty.value) : isSubmitted && requiredValidator(vCardProperty.value); return ( <> <Input ref={ref} value={vCardProperty.value} placeholder={label} onChange={handleChange} data-testid={label} error={!!requiredError || nameTooLongError} {...rest} /> {nameTooLongError ? <ErrorZone>{c('Error').t`Contact name is too long`}</ErrorZone> : null} {!!requiredError && !isNewContact ? <ErrorZone>{requiredError}</ErrorZone> : null} {!!requiredError && isNewContact ? ( <ErrorZone>{c('Error').t`Please provide either a first name, a last name or a display name`}</ErrorZone> ) : null} </> ); }; export default forwardRef(ContactFieldFn);
6,020
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldGender.tsx
import { ChangeEvent } from 'react'; import { Input, InputProps } from '@proton/atoms'; import { getAllFieldLabels } from '@proton/shared/lib/helpers/contacts'; import { VCardGenderValue, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; interface Props extends Omit<InputProps, 'onChange'> { vCardProperty: VCardProperty<VCardGenderValue>; onChange: (vCardProperty: VCardProperty) => void; } const ContactFieldGender = ({ vCardProperty, onChange, ...rest }: Props) => { const label = (getAllFieldLabels() as any).gender; const value = vCardProperty.value?.text || ''; const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { const newValue = target.value; onChange({ ...vCardProperty, value: { gender: vCardProperty.value?.gender, text: newValue } }); }; return <Input value={value} placeholder={label} onChange={handleChange} data-testid={label} {...rest} />; }; export default ContactFieldGender;
6,021
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldImage.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import RemoteImage from '../../../../components/image/RemoteImage'; import { ContactImageProps } from '../../modals/ContactImageModal'; interface Props { vCardProperty: VCardProperty<string>; onChange: (vCardProperty: VCardProperty) => void; onSelectImage: (props: ContactImageProps) => void; } const ContactFieldImage = ({ vCardProperty, onChange, onSelectImage }: Props) => { const [loadNewImage, setLoadNewImage] = useState(false); const handleChangeImage = () => { const handleSubmit = (value: string) => { onChange({ ...vCardProperty, value }); setLoadNewImage(true); }; onSelectImage({ url: vCardProperty.value, onSubmit: handleSubmit }); }; /** * Load image by default in edit mode * AND allow image update when "default" contact photo is deleted * In that case, photo from "Other" field will become the contact photo (if any). * But we need to reload them, using this useEffect */ useEffect(() => { if (vCardProperty.value) { setLoadNewImage(true); } }, [vCardProperty.value]); return ( <div> {vCardProperty.value ? ( <RemoteImage src={vCardProperty.value} autoLoad={loadNewImage} /> ) : ( <Button onClick={handleChangeImage}>{c('Action').t`Upload picture`}</Button> )} </div> ); }; export default ContactFieldImage;
6,022
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldN.tsx
import { Ref, forwardRef } from 'react'; import { c } from 'ttag'; import { ErrorZone } from '@proton/components/components'; import { isFirstLastNameValid } from '@proton/shared/lib/contacts/property'; import { VCardContact, VCardProperty, VcardNValue } from '@proton/shared/lib/interfaces/contacts/VCard'; import ContactFieldString from './ContactFieldString'; interface Props { vCardContact: VCardContact; vCardProperty: VCardProperty<VcardNValue>; isSubmitted: boolean; onChangeVCard: (vCardProperty: VCardProperty<VcardNValue>) => void; } enum FieldsPos { familyName = 0, givenName = 1, } const ContactFieldN = ( { vCardContact, vCardProperty, isSubmitted, onChangeVCard, ...rest }: Props, firstNameFieldRef: Ref<HTMLInputElement> ) => { const givenName = vCardProperty.value.givenNames[0] || ''; const familyName = vCardProperty.value.familyNames[0] || ''; // The N field is an array where the first element is the family name and the second element is the given name. const handleChange = (change: VCardProperty, pos: FieldsPos) => { const { value } = change; const newValue = { ...vCardProperty.value }; if (pos === FieldsPos.familyName) { newValue.familyNames[0] = value; } else { newValue.givenNames[0] = value; } onChangeVCard({ ...vCardProperty, field: 'n', value: newValue }); }; const givenNameTooLong = !isFirstLastNameValid(givenName); const familyNameTooLong = !isFirstLastNameValid(familyName); const requiredError = !vCardContact.fn?.[0].value && isSubmitted && !givenName && !familyName; return ( <div className="flex on-mobile-flex-column gap-2"> <div className="flex-item-fluid"> <ContactFieldString ref={firstNameFieldRef} placeholder={c('Placeholder').t`First name`} data-testid="First name" vCardProperty={{ ...vCardProperty, field: 'givenName', value: givenName }} onChange={(change) => handleChange(change, FieldsPos.givenName)} error={requiredError || givenNameTooLong} {...rest} /> {givenNameTooLong ? <ErrorZone>{c('Error').t`First name is too long`}</ErrorZone> : null} </div> <div className="flex-item-fluid"> <ContactFieldString placeholder={c('Placeholder').t`Last name`} data-testid="Last name" vCardProperty={{ ...vCardProperty, field: 'familyName', value: familyName }} onChange={(change) => handleChange(change, FieldsPos.familyName)} error={requiredError || familyNameTooLong} {...rest} /> {familyNameTooLong ? <ErrorZone>{c('Error').t`Last name is too long`}</ErrorZone> : null} </div> </div> ); }; export default forwardRef(ContactFieldN);
6,023
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldNote.tsx
import { ChangeEvent } from 'react'; import { getAllFieldLabels } from '@proton/shared/lib/helpers/contacts'; import { VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { TextAreaTwo } from '../../../../components'; interface Props { vCardProperty: VCardProperty<string>; onChange: (vCardProperty: VCardProperty) => void; } const ContactFieldNote = ({ vCardProperty, onChange, ...rest }: Props) => { const label = getAllFieldLabels().note; const handleChange = ({ target }: ChangeEvent<HTMLTextAreaElement>) => { const newValue = target.value; onChange({ ...vCardProperty, value: newValue }); }; const value = vCardProperty.value || ''; return <TextAreaTwo value={value} placeholder={label} onChange={handleChange} data-testid={label} {...rest} />; }; export default ContactFieldNote;
6,024
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldOrg.tsx
import { ChangeEvent, Ref, forwardRef } from 'react'; import { Input, InputProps } from '@proton/atoms'; import { getAllFieldLabels } from '@proton/shared/lib/helpers/contacts'; import { VCardOrg, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import isTruthy from '@proton/utils/isTruthy'; interface Props extends Omit<InputProps, 'onChange'> { vCardProperty: VCardProperty<VCardOrg>; onChange: (vCardProperty: VCardProperty<VCardOrg>) => void; } const ContactFieldOrg = ({ vCardProperty, onChange, ...rest }: Props, ref: Ref<HTMLInputElement>) => { const label = getAllFieldLabels().org; const property = vCardProperty; const value = `${[ property.value?.organizationalName ?? '', ...(property.value?.organizationalUnitNames ?? []), ].join(';')}`; const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { const isBackspace = value.length > target.value.length; let splitted = target.value.split(';'); splitted = isBackspace ? splitted.filter(isTruthy) : splitted; const [organizationalName, ...organizationalUnitNames] = splitted; const newValue = { organizationalName, organizationalUnitNames, }; onChange({ ...vCardProperty, value: newValue }); }; return <Input ref={ref} value={value} placeholder={label} onChange={handleChange} data-testid={label} {...rest} />; }; export default forwardRef(ContactFieldOrg);
6,025
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldProperty.tsx
import { Ref, forwardRef } from 'react'; import { VCardContact, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { ContactImageProps } from '../../modals/ContactImageModal'; import ContactFieldAdr from './ContactFieldAdr'; import ContactFieldDate from './ContactFieldDate'; import ContactFieldEmail from './ContactFieldEmail'; import ContactFieldFn from './ContactFieldFn'; import ContactFieldGender from './ContactFieldGender'; import ContactFieldImage from './ContactFieldImage'; import ContactFieldN from './ContactFieldN'; import ContactFieldNote from './ContactFieldNote'; import ContactFieldOrg from './ContactFieldOrg'; import ContactFieldString from './ContactFieldString'; import ContactFieldTel from './ContactFieldTel'; interface Props { vCardContact: VCardContact; vCardProperty: VCardProperty<any>; onChangeVCard: (vCardProperty: VCardProperty) => void; onSelectImage: (props: ContactImageProps) => void; isSubmitted?: boolean; } const ContactFieldProperty = ( { vCardContact, vCardProperty, onChangeVCard, onSelectImage, isSubmitted = false, ...rest }: Props, ref: Ref<HTMLInputElement> ) => { const { field } = vCardProperty; if (field === 'email') { return <ContactFieldEmail vCardProperty={vCardProperty} onChange={onChangeVCard} {...rest} />; } if (field === 'tel') { return <ContactFieldTel vCardProperty={vCardProperty} onChange={onChangeVCard} {...rest} />; } if (field === 'adr') { return <ContactFieldAdr vCardProperty={vCardProperty} onChange={onChangeVCard} {...rest} />; } if (field === 'note') { return <ContactFieldNote vCardProperty={vCardProperty} onChange={onChangeVCard} {...rest} />; } if (field === 'bday' || field === 'anniversary') { return <ContactFieldDate vCardProperty={vCardProperty} onChange={onChangeVCard} {...rest} />; } if (field === 'photo' || field === 'logo') { return ( <ContactFieldImage vCardProperty={vCardProperty} onChange={onChangeVCard} onSelectImage={onSelectImage} {...rest} /> ); } if (field === 'fn') { return ( <ContactFieldFn ref={ref} vCardProperty={vCardProperty} vCardContact={vCardContact} onChange={onChangeVCard} isSubmitted={isSubmitted} {...rest} /> ); } if (field === 'gender') { return <ContactFieldGender vCardProperty={vCardProperty} onChange={onChangeVCard} {...rest} />; } if (field === 'n') { return ( <ContactFieldN ref={ref} vCardContact={vCardContact} isSubmitted={isSubmitted} vCardProperty={vCardProperty} onChangeVCard={onChangeVCard} {...rest} /> ); } if (field === 'org') { return <ContactFieldOrg vCardProperty={vCardProperty} onChange={onChangeVCard} {...rest} />; } return <ContactFieldString vCardProperty={vCardProperty} onChange={onChangeVCard} {...rest} />; }; export default forwardRef(ContactFieldProperty);
6,026
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldString.tsx
import { ChangeEvent, Ref, forwardRef } from 'react'; import { Input, InputProps } from '@proton/atoms'; import { getAllFieldLabels } from '@proton/shared/lib/helpers/contacts'; import { VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; interface Props extends Omit<InputProps, 'onChange'> { vCardProperty: VCardProperty<string>; onChange: (vCardProperty: VCardProperty<string>) => void; } const ContactFieldString = ({ vCardProperty, onChange, ...rest }: Props, ref: Ref<HTMLInputElement>) => { const label = (getAllFieldLabels() as any)[vCardProperty.field] || ''; const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { const newValue = target.value; onChange({ ...vCardProperty, value: newValue }); }; return ( <Input ref={ref} value={vCardProperty.value} placeholder={label} onChange={handleChange} data-testid={label} {...rest} /> ); }; export default forwardRef(ContactFieldString);
6,027
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/edit/fields/ContactFieldTel.tsx
import { ChangeEvent } from 'react'; import { getAllFieldLabels } from '@proton/shared/lib/helpers/contacts'; import { VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { TelInput } from '../../../../components'; interface Props { vCardProperty: VCardProperty<string>; onChange: (vCardProperty: VCardProperty) => void; } const ContactFieldTel = ({ vCardProperty, onChange, ...rest }: Props) => { const label = getAllFieldLabels().tel; const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { const newValue = target.value; onChange({ ...vCardProperty, value: newValue }); }; const value = vCardProperty.value || ''; return <TelInput value={value} placeholder={label} onChange={handleChange} data-testid={label} {...rest} />; }; export default ContactFieldTel;
6,028
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/email/ContactEmailSettingsModal.test.tsx
import { fireEvent, waitFor } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import { API_CODES, CONTACT_CARD_TYPE, KEY_FLAG } from '@proton/shared/lib/constants'; import { parseToVCard } from '@proton/shared/lib/contacts/vcard'; import { RequireSome } from '@proton/shared/lib/interfaces'; import { VCardContact, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { api, clearAll, mockedCryptoApi, notificationManager, render } from '../tests/render'; import ContactEmailSettingsModal, { ContactEmailSettingsProps } from './ContactEmailSettingsModal'; describe('ContactEmailSettingsModal', () => { const props: ContactEmailSettingsProps = { contactID: 'ContactID', vCardContact: { fn: [] }, emailProperty: {} as VCardProperty<string>, onClose: jest.fn(), }; beforeEach(clearAll); afterEach(async () => { await CryptoProxy.releaseEndpoint(); }); it('should save a contact with updated email settings (no keys)', async () => { CryptoProxy.setEndpoint(mockedCryptoApi); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:jdoe@example.com END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] } }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText, getByTitle } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); const encryptToggle = document.getElementById('encrypt-toggle'); expect(encryptToggle).toBeDisabled(); const signSelect = getByText("Use global default (Don't sign)", { exact: false }); fireEvent.click(signSelect); const signOption = getByTitle('Sign'); fireEvent.click(signOption); const pgpSelect = getByText('Use global default (PGP/MIME)', { exact: false }); fireEvent.click(pgpSelect); const pgpInlineOption = getByTitle('PGP/Inline'); fireEvent.click(pgpInlineOption); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const expectedEncryptedCard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:jdoe@example.com ITEM1.X-PM-MIMETYPE:text/plain ITEM1.X-PM-SIGN:true ITEM1.X-PM-SCHEME:pgp-inline END:VCARD`.replaceAll('\n', '\r\n'); const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent).toBe(expectedEncryptedCard); }); it('should not store X-PM-SIGN if global default signing setting is selected', async () => { CryptoProxy.setEndpoint(mockedCryptoApi); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:jdoe@example.com ITEM1.X-PM-SIGN:true END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] } }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText, getByTitle } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); const signSelect = getByText('Sign', { exact: true }); fireEvent.click(signSelect); const signOption = getByTitle("Use global default (Don't sign)"); fireEvent.click(signOption); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const expectedCard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:jdoe@example.com END:VCARD`.replaceAll('\n', '\r\n'); const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent).toBe(expectedCard); }); it('should warn if encryption is enabled and uploaded keys are not valid for sending', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async () => ({ getFingerprint: () => `abcdef`, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<userid@userid.com>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => false), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => true), isRevokedKey: jest.fn().mockImplementation(() => false), }); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:expired UID:proton-web-b2dc0409-262d-96db-8925-3ee4f0030fd8 ITEM1.EMAIL;PREF=1:expired@test.com ITEM1.KEY;PREF=1:data:application/pgp-keys;base64,xjMEYS376BYJKwYBBAHaRw8BA QdAm9ZJKSCnCg28vJ/1Iegycsiq9wKxFP5/BMDeP51C/jbNGmV4cGlyZWQgPGV4cGlyZWRAdGVz dC5jb20+wpIEEBYKACMFAmEt++gFCQAAAPoECwkHCAMVCAoEFgACAQIZAQIbAwIeAQAhCRDs7cn 9e8csRhYhBP/xHanO8KRS6sPFiOztyf17xyxGhYIBANpMcbjGa3w3qPzWDfb3b/TgfbJuYFQ49Y ik/Zd/ZZQZAP42rtyxbSz/XfKkNdcJPbZ+MQa2nalOZ6+uXm9ScCQtBc44BGEt++gSCisGAQQBl 1UBBQEBB0Dj+ZNzODXqLeZchFOVE4E87HD8QsoSI60bDkpklgK3eQMBCAfCfgQYFggADwUCYS37 6AUJAAAA+gIbDAAhCRDs7cn9e8csRhYhBP/xHanO8KRS6sPFiOztyf17xyxGbyIA/2Jz6p/6WBo yh279kjiKpX8NWde/2/O7M7W7deYulO4oAQDWtYZNTw1OTYfYI2PBcs1kMbB3hhBr1VEG0pLvtz xoAA== ITEM1.X-PM-ENCRYPT:true ITEM1.X-PM-SIGN:true END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] } }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); await waitFor(() => { const keyFingerprint = getByText('abcdef'); return expect(keyFingerprint).toBeVisible(); }); const warningInvalidKey = getByText(/None of the uploaded keys are valid for encryption/); expect(warningInvalidKey).toBeVisible(); const encryptToggleLabel = getByText('Encrypt emails'); fireEvent.click(encryptToggleLabel); expect(warningInvalidKey).not.toBeVisible(); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent.includes('ITEM1.X-PM-ENCRYPT:false')).toBe(true); }); it('should enable encryption by default if WKD keys are found', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async () => ({ getFingerprint: () => `abcdef`, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<jdoe@example.com>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => true), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => false), isRevokedKey: jest.fn().mockImplementation(() => false), }); const armoredPublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- xjMEYRaiLRYJKwYBBAHaRw8BAQdAMrsrfniSJuxOLn+Q3VKP0WWqgizG4VOF 6t0HZYx8mSnNEHRlc3QgPHRlc3RAYS5pdD7CjAQQFgoAHQUCYRaiLQQLCQcI AxUICgQWAAIBAhkBAhsDAh4BACEJEKaNwv/NOLSZFiEEnJT1OMsrVBCZa+wE po3C/804tJnYOAD/YR2og60sJ2VVhPwYRL258dYIHnJXI2dDXB+m76GK9x4A /imlPnTOgIJAV1xOqkvO96QcbawjKgvH829zxN9DZEgMzjgEYRaiLRIKKwYB BAGXVQEFAQEHQN5UswYds0RWr4I7xNKNK+fOn+o9pYkkYzJwCbqxCsBwAwEI B8J4BBgWCAAJBQJhFqItAhsMACEJEKaNwv/NOLSZFiEEnJT1OMsrVBCZa+wE po3C/804tJkeKgEA0ruKx9rcMTi4LxfYgijjPrI+GgrfegfREt/YN2KQ75gA /Rs9S+8arbQVoniq7izz3uisWxfjMup+IVEC5uqMld8L =8+ep -----END PGP PUBLIC KEY BLOCK-----`; const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:jdoe@example.com ITEM1.X-PM-ENCRYPT:true END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] }, Unverified: { Keys: [{ Flags: 3, PublicKey: armoredPublicKey }], }, }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); const encryptToggle = document.getElementById('encrypt-toggle'); expect(encryptToggle).not.toBeDisabled(); expect(encryptToggle).toBeChecked(); const signSelectDropdown = document.getElementById('sign-select'); expect(signSelectDropdown).toBeDisabled(); signSelectDropdown?.innerHTML.includes('Sign'); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const expectedEncryptedCard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:jdoe@example.com ITEM1.X-PM-ENCRYPT-UNTRUSTED:true ITEM1.X-PM-SIGN:true END:VCARD`.replaceAll('\n', '\r\n'); const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent).toBe(expectedEncryptedCard); }); it('should warn if encryption is enabled and WKD keys are not valid for sending', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async () => ({ getFingerprint: () => `abcdef`, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<userid@userid.com>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => false), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => true), isRevokedKey: jest.fn().mockImplementation(() => false), }); const armoredPublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- xjMEYS376BYJKwYBBAHaRw8BAQdAm9ZJKSCnCg28vJ/1Iegycsiq9wKxFP5/ BMDeP51C/jbNGmV4cGlyZWQgPGV4cGlyZWRAdGVzdC5jb20+wpIEEBYKACMF AmEt++gFCQAAAPoECwkHCAMVCAoEFgACAQIZAQIbAwIeAQAhCRDs7cn9e8cs RhYhBP/xHanO8KRS6sPFiOztyf17xyxGhYIBANpMcbjGa3w3qPzWDfb3b/Tg fbJuYFQ49Yik/Zd/ZZQZAP42rtyxbSz/XfKkNdcJPbZ+MQa2nalOZ6+uXm9S cCQtBc44BGEt++gSCisGAQQBl1UBBQEBB0Dj+ZNzODXqLeZchFOVE4E87HD8 QsoSI60bDkpklgK3eQMBCAfCfgQYFggADwUCYS376AUJAAAA+gIbDAAhCRDs 7cn9e8csRhYhBP/xHanO8KRS6sPFiOztyf17xyxGbyIA/2Jz6p/6WBoyh279 kjiKpX8NWde/2/O7M7W7deYulO4oAQDWtYZNTw1OTYfYI2PBcs1kMbB3hhBr 1VEG0pLvtzxoAA== =456g -----END PGP PUBLIC KEY BLOCK-----`; const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:jdoe@example.com END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [] }, Unverified: { Keys: [{ Flags: 3, PublicKey: armoredPublicKey }] }, }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); await waitFor(() => { const keyFingerprint = getByText('abcdef'); return expect(keyFingerprint).toBeVisible(); }); const warningInvalidKey = getByText(/None of the uploaded keys are valid for encryption/); expect(warningInvalidKey).toBeVisible(); const encryptToggleLabel = getByText('Encrypt emails'); fireEvent.click(encryptToggleLabel); expect(warningInvalidKey).not.toBeVisible(); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent.includes('ITEM1.X-PM-ENCRYPT-UNTRUSTED:false')).toBe(true); }); it('should indicate that end-to-end encryption is disabled for internal addresses whose keys have e2ee-disabled flags', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async () => ({ getFingerprint: () => `abcdef`, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<userid@userid.com>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => true), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => false), isRevokedKey: jest.fn().mockImplementation(() => false), }); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:jdoe@proton.me END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [ { PublicKey: 'mocked armored key', Flags: KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT | KEY_FLAG.FLAG_NOT_COMPROMISED, }, ], }, ProtonMX: true, // internal address }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText, getByTitle, queryByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); await waitFor(() => { const keyFingerprint = getByText('abcdef'); return expect(keyFingerprint).toBeVisible(); }); const infoEncryptionDisabled = getByText(/The owner of this address has disabled end-to-end encryption/); expect(infoEncryptionDisabled).toBeVisible(); expect(queryByText('Encrypt emails')).toBeNull(); expect(queryByText('Sign emails')).toBeNull(); expect(queryByText('Upload keys')).toBeNull(); const dropdownButton = getByTitle('Open actions dropdown'); fireEvent.click(dropdownButton); const trustKeyButton = getByText('Trust'); fireEvent.click(trustKeyButton); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent.includes('ITEM1.KEY;PREF=1:data:application/pgp-keys')).toBe(true); expect(signedCardContent.includes('ITEM1.X-PM-ENCRYPT')).toBe(false); expect(signedCardContent.includes('ITEM1.X-PM-SIGN')).toBe(false); }); it('shoul display WKD keys but not internal address keys for external account with internal address keys', async () => { CryptoProxy.setEndpoint({ ...mockedCryptoApi, importPublicKey: jest.fn().mockImplementation(async ({ armoredKey }) => ({ getFingerprint: () => armoredKey, getCreationTime: () => new Date(0), getExpirationTime: () => new Date(0), getAlgorithmInfo: () => ({ algorithm: 'eddsa', curve: 'curve25519' }), subkeys: [], getUserIDs: jest.fn().mockImplementation(() => ['<userid@userid.com>']), })), canKeyEncrypt: jest.fn().mockImplementation(() => true), exportPublicKey: jest.fn().mockImplementation(() => new Uint8Array()), isExpiredKey: jest.fn().mockImplementation(() => false), isRevokedKey: jest.fn().mockImplementation(() => false), }); const vcard = `BEGIN:VCARD VERSION:4.0 FN;PREF=1:J. Doe UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 ITEM1.EMAIL;PREF=1:jdoe@example.com END:VCARD`; const vCardContact = parseToVCard(vcard) as RequireSome<VCardContact, 'email'>; const saveRequestSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'core/v4/keys/all') { return { Address: { Keys: [ { PublicKey: 'internal mocked armored key', Flags: KEY_FLAG.FLAG_EMAIL_NO_ENCRYPT | KEY_FLAG.FLAG_NOT_COMPROMISED, }, ], }, Unverified: { Keys: [{ PublicKey: 'wkd mocked armored key', Flags: KEY_FLAG.FLAG_NOT_COMPROMISED }], }, ProtonMX: false, // external account }; } if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses: [{ Response: { Code: API_CODES.SINGLE_SUCCESS } }] }; } if (args.url === 'contacts/v4/contacts/ContactID') { saveRequestSpy(args.data); return { Code: API_CODES.SINGLE_SUCCESS }; } }); const { getByText, getByTitle, queryByText } = render( <ContactEmailSettingsModal open={true} {...props} vCardContact={vCardContact} emailProperty={vCardContact.email?.[0]} /> ); const showMoreButton = getByText('Show advanced PGP settings'); await waitFor(() => expect(showMoreButton).not.toBeDisabled()); fireEvent.click(showMoreButton); await waitFor(() => { const internalAddressKeyFingerprint = queryByText('internal mocked armored key'); return expect(internalAddressKeyFingerprint).toBeNull(); }); await waitFor(() => { const wkdKeyFingerprint = getByText('wkd mocked armored key'); return expect(wkdKeyFingerprint).toBeVisible(); }); const infoEncryptionDisabled = queryByText(/The owner of this address has disabled end-to-end encryption/); expect(infoEncryptionDisabled).toBeNull(); // only shown to internal accounts // Ensure the UI matches that of external recipients with WKD keys: // - encryption should be enabled by default, and toggable // - key uploads are not permitted // - key pinning works stores the X-PM-ENCRYPT flag const encryptToggle = document.getElementById('encrypt-toggle'); expect(encryptToggle).not.toBeDisabled(); expect(encryptToggle).toBeChecked(); const signSelectDropdown = document.getElementById('sign-select'); expect(signSelectDropdown).toBeDisabled(); signSelectDropdown?.innerHTML.includes('Sign'); expect(queryByText('Upload keys')).toBeNull(); const dropdownButton = getByTitle('Open actions dropdown'); fireEvent.click(dropdownButton); const trustKeyButton = getByText('Trust'); fireEvent.click(trustKeyButton); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => expect(notificationManager.createNotification).toHaveBeenCalled()); const sentData = saveRequestSpy.mock.calls[0][0]; const cards = sentData.Cards; const signedCardContent = cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === CONTACT_CARD_TYPE.SIGNED ).Data; expect(signedCardContent.includes('ITEM1.KEY;PREF=1:data:application/pgp-keys')).toBe(true); expect(signedCardContent.includes('ITEM1.X-PM-ENCRYPT:true')).toBe(true); expect(signedCardContent.includes('ITEM1.X-PM-SIGN:true')).toBe(true); }); });
6,029
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/email/ContactEmailSettingsModal.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import getPublicKeysEmailHelper from '@proton/shared/lib/api/helpers/getPublicKeysEmailHelper'; import { extractScheme } from '@proton/shared/lib/api/helpers/mailSettings'; import { CONTACT_MIME_TYPES, MIME_TYPES, MIME_TYPES_MORE, PGP_SCHEMES } from '@proton/shared/lib/constants'; import { VCARD_KEY_FIELDS } from '@proton/shared/lib/contacts/constants'; import { getKeyInfoFromProperties, getMimeTypeVcard, toKeyProperty } from '@proton/shared/lib/contacts/keyProperties'; import { createContactPropertyUid, fromVCardProperties, getVCardProperties, } from '@proton/shared/lib/contacts/properties'; import { ContactPublicKeyModel } from '@proton/shared/lib/interfaces'; import { VCardContact, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { getContactPublicKeyModel, getVerifyingKeys, sortApiKeys, sortPinnedKeys, } from '@proton/shared/lib/keys/publicKeys'; import clsx from '@proton/utils/clsx'; import uniqueBy from '@proton/utils/uniqueBy'; import { Alert, Collapsible, CollapsibleContent, CollapsibleHeader, CollapsibleHeaderIconButton, Field, Icon, Info, Label, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Row, } from '../../../components'; import { useApi, useEventManager, useMailSettings, useNotifications } from '../../../hooks'; import { useKeyTransparencyContext } from '../../keyTransparency'; import { useSaveVCardContact } from '../hooks/useSaveVCardContact'; import ContactMIMETypeSelect from './ContactMIMETypeSelect'; import ContactPGPSettings from './ContactPGPSettings'; const { PGP_INLINE } = PGP_SCHEMES; export interface ContactEmailSettingsProps { contactID: string; vCardContact: VCardContact; emailProperty: VCardProperty<string>; onClose?: () => void; } type Props = ContactEmailSettingsProps & ModalProps; const ContactEmailSettingsModal = ({ contactID, vCardContact, emailProperty, ...rest }: Props) => { const { value: emailAddressValue, group: emailGroup } = emailProperty; const emailAddress = emailAddressValue as string; const api = useApi(); const { call } = useEventManager(); const [model, setModel] = useState<ContactPublicKeyModel>(); const [showPgpSettings, setShowPgpSettings] = useState(false); const [loadingPgpSettings, withLoadingPgpSettings] = useLoading(true); const [loadingSave, withLoadingSave] = useLoading(false); const { createNotification } = useNotifications(); const [mailSettings] = useMailSettings(); const { verifyOutboundPublicKeys, ktActivation } = useKeyTransparencyContext(); const saveVCardContact = useSaveVCardContact(); // Avoid nested ternary let isMimeTypeFixed: boolean; if (model?.isPGPInternal) { isMimeTypeFixed = false; } else { isMimeTypeFixed = model?.sign !== undefined ? model.sign : !!mailSettings?.Sign; } const hasPGPInline = model && mailSettings ? extractScheme(model, mailSettings) === PGP_INLINE : false; /** * Initialize the key model for the modal */ const prepare = async () => { const apiKeysConfig = await getPublicKeysEmailHelper({ email: emailAddress, includeInternalKeysWithE2EEDisabledForMail: true, // the keys are used in the context of calendar sharing, thus users may want to pin them api, ktActivation, verifyOutboundPublicKeys, silence: true, }); const pinnedKeysConfig = await getKeyInfoFromProperties(vCardContact, emailGroup || ''); const publicKeyModel = await getContactPublicKeyModel({ emailAddress, apiKeysConfig, pinnedKeysConfig: { ...pinnedKeysConfig, isContact: true }, }); setModel({ ...publicKeyModel, // Encryption enforces signing, so we can ignore the signing preference so that if the user // disables encryption, the global default signing setting is automatically selected. sign: publicKeyModel.encrypt ? undefined : publicKeyModel.sign, }); }; /** * Collect keys from the model to save * @param group attached to the current email address * @returns key properties to save in the vCard */ const getKeysProperties = (group: string, model: ContactPublicKeyModel) => { const allKeys = model?.isPGPInternal ? [...model.publicKeys.apiKeys] : [...model.publicKeys?.apiKeys, ...model.publicKeys.pinnedKeys]; const trustedKeys = allKeys.filter((publicKey) => model.trustedFingerprints.has(publicKey.getFingerprint())); const uniqueTrustedKeys = uniqueBy(trustedKeys, (publicKey) => publicKey.getFingerprint()); return Promise.all(uniqueTrustedKeys.map((publicKey, index) => toKeyProperty({ publicKey, group, index }))); }; /** * Save relevant key properties in the vCard */ const handleSubmit = async (model?: ContactPublicKeyModel) => { if (!model) { return; } const properties = getVCardProperties(vCardContact); const newProperties = properties.filter(({ field, group }) => { return !VCARD_KEY_FIELDS.includes(field) || (group && group !== emailGroup); }); newProperties.push(...(await getKeysProperties(emailGroup || '', model))); const mimeType = getMimeTypeVcard(model.mimeType); if (mimeType) { newProperties.push({ field: 'x-pm-mimetype', value: mimeType, group: emailGroup, uid: createContactPropertyUid(), }); } if (model.isPGPExternal) { const hasPinnedKeys = model.publicKeys.pinnedKeys.length > 0; const hasApiKeys = model.publicKeys.apiKeys.length > 0; // from WKD or other untrusted servers if ((hasPinnedKeys || hasApiKeys) && model.encrypt !== undefined) { newProperties.push({ field: hasPinnedKeys ? 'x-pm-encrypt' : 'x-pm-encrypt-untrusted', value: `${model.encrypt}`, group: emailGroup, uid: createContactPropertyUid(), }); } // Encryption automatically enables signing (but we do not store the info for non-pinned WKD keys). const sign = model.encrypt || model.sign; if (sign !== undefined) { newProperties.push({ field: 'x-pm-sign', value: `${sign}`, group: emailGroup, uid: createContactPropertyUid(), }); } if (model.scheme) { newProperties.push({ field: 'x-pm-scheme', value: model.scheme, group: emailGroup, uid: createContactPropertyUid(), }); } } const newVCardContact = fromVCardProperties(newProperties); try { await saveVCardContact(contactID, newVCardContact); await call(); createNotification({ text: c('Success').t`Preferences saved` }); } finally { rest.onClose?.(); } }; useEffect(() => { /** * On the first render, initialize the model */ if (!model) { void withLoadingPgpSettings(prepare()); return; } /** * When the list of trusted, expired or revoked keys change, * * update the list: * * re-check if the new keys can send * * re-order api keys (trusted take preference) * * move expired keys to the bottom of the list */ setModel((model?: ContactPublicKeyModel) => { if (!model) { return; } const { publicKeys, trustedFingerprints, obsoleteFingerprints, compromisedFingerprints, encryptionCapableFingerprints, } = model; const apiKeys = sortApiKeys({ keys: publicKeys.apiKeys, trustedFingerprints, obsoleteFingerprints, compromisedFingerprints, }); const pinnedKeys = sortPinnedKeys({ keys: publicKeys.pinnedKeys, obsoleteFingerprints, compromisedFingerprints, encryptionCapableFingerprints, }); const verifyingPinnedKeys = getVerifyingKeys(pinnedKeys, model.compromisedFingerprints); return { ...model, publicKeys: { apiKeys, pinnedKeys, verifyingPinnedKeys }, }; }); }, [ model?.trustedFingerprints, model?.obsoleteFingerprints, model?.encryptionCapableFingerprints, model?.compromisedFingerprints, ]); useEffect(() => { // take into account rules relating email format and cryptographic scheme if (!isMimeTypeFixed) { return; } // PGP/Inline should force the email format to plaintext if (hasPGPInline) { return setModel((model?: ContactPublicKeyModel) => { if (!model) { return; } return { ...model, mimeType: MIME_TYPES.PLAINTEXT }; }); } // If PGP/Inline is not selected, go back to automatic setModel((model?: ContactPublicKeyModel) => { if (!model) { return; } return { ...model, mimeType: MIME_TYPES_MORE.AUTOMATIC }; }); }, [isMimeTypeFixed, hasPGPInline]); return ( <ModalTwo size="large" className="contacts-modal" {...rest}> <ModalTwoHeader title={c('Title').t`Edit email settings`} titleClassName="text-ellipsis" subline={emailAddress} /> <ModalTwoContent> {!isMimeTypeFixed ? ( <Alert className="mb-4"> {c('Info') .t`Select the email format you want to be used by default when sending an email to this email address.`} </Alert> ) : null} {isMimeTypeFixed && hasPGPInline ? ( <Alert className="mb-4">{c('Info').t`PGP/Inline is only compatible with Plain Text format.`}</Alert> ) : null} {isMimeTypeFixed && !hasPGPInline ? ( <Alert className="mb-4"> {c('Info').t`PGP/MIME automatically sends the message using the current composer mode.`} </Alert> ) : null} <Row> <Label> {c('Label').t`Email format`} <Info className="ml-2" title={c('Tooltip') .t`Automatic indicates that the format in the composer is used to send to this user. Plain text indicates that the message will always be converted to plain text on send.`} /> </Label> <Field> <ContactMIMETypeSelect disabled={loadingSave || isMimeTypeFixed} value={model?.mimeType || ''} onChange={(mimeType: CONTACT_MIME_TYPES) => setModel((model?: ContactPublicKeyModel) => { if (!model) { return; } return { ...model, mimeType }; }) } /> </Field> </Row> <div className="mb-4"> <Collapsible disabled={loadingPgpSettings}> <CollapsibleHeader suffix={ <CollapsibleHeaderIconButton onClick={() => setShowPgpSettings(!showPgpSettings)}> <Icon name="chevron-down" /> </CollapsibleHeaderIconButton> } disableFullWidth onClick={() => setShowPgpSettings(!showPgpSettings)} className={clsx([ 'color-primary', loadingPgpSettings ? 'color-weak text-no-decoration' : 'text-underline', ])} > {showPgpSettings ? c('Action').t`Hide advanced PGP settings` : c('Action').t`Show advanced PGP settings`} </CollapsibleHeader> <CollapsibleContent className="mt-4"> {showPgpSettings && model ? ( <ContactPGPSettings model={model} setModel={setModel} mailSettings={mailSettings} /> ) : null} </CollapsibleContent> </Collapsible> </div> </ModalTwoContent> <ModalTwoFooter> <Button type="reset" onClick={rest.onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" loading={loadingSave} disabled={loadingSave || loadingPgpSettings} type="submit" onClick={() => withLoadingSave(handleSubmit(model))} data-testid="email-settings:save" > {c('Action').t`Save`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactEmailSettingsModal;
6,030
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/email/ContactKeysTable.tsx
import { Dispatch, Fragment, SetStateAction, useEffect, useState } from 'react'; import { format, isValid } from 'date-fns'; import { c } from 'ttag'; import { CryptoProxy, PublicKeyReference } from '@proton/crypto'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { dateLocale } from '@proton/shared/lib/i18n'; import { ContactPublicKeyModel } from '@proton/shared/lib/interfaces'; import { getFormattedAlgorithmNames } from '@proton/shared/lib/keys'; import { getVerifyingKeys } from '@proton/shared/lib/keys/publicKeys'; import clsx from '@proton/utils/clsx'; import move from '@proton/utils/move'; import uniqueBy from '@proton/utils/uniqueBy'; import { Badge, ContactKeyWarningIcon, DropdownActions, Table, TableBody, TableRow } from '../../../components'; import useActiveBreakpoint from '../../../hooks/useActiveBreakpoint'; interface Props { model: ContactPublicKeyModel; setModel: Dispatch<SetStateAction<ContactPublicKeyModel | undefined>>; } type LocalKeyModel = { publicKey: PublicKeyReference; armoredPublicKey: string; fingerprint: string; algo: string; creationTime: Date; expirationTime: any; isPrimary?: boolean; isWKD: boolean; isExpired: boolean; isRevoked: boolean; isTrusted: boolean; isObsolete: boolean; isCompromised: boolean; supportsEncryption: boolean; isUploaded: boolean; canBePrimary?: boolean; canBeTrusted: boolean; canBeUntrusted: boolean; }; const ContactKeysTable = ({ model, setModel }: Props) => { const [keys, setKeys] = useState<LocalKeyModel[]>([]); const { isNarrow, isTinyMobile } = useActiveBreakpoint(); const { emailAddress } = model; const totalApiKeys = model.publicKeys.apiKeys.length; // translator: Please translate as in the sentence "this key is the primary one" const primaryText = c('Key badge').t`Primary`; // translator: Please translate as in the sentence "this key is obsolete" const obsoleteText = c('Key badge').t`Obsolete`; // translator: Please translate as in the sentence "this key is compromised" const compromisedText = c('Key badge').t`Compromised`; // translator: WKD stands for Web Key Directory (https://wiki.gnupg.org/WKD). You might not need to translate it const wkdText = c('Key badge').t`WKD`; // translator: Please translate as in the sentence "this key is trusted" const trustedText = c('Key badge').t`Trusted`; // translator: Please translate as in the sentence "this key is revoked" const revokedText = c('Key badge').t`Revoked`; // translator: Please translate as in the sentence "this key is expired" const expiredText = c('Key badge').t`Expired`; /** * Extract keys info from model.publicKeys to define table body */ const parse = async () => { const allKeys = model.isPGPInternal ? [...model.publicKeys.apiKeys] : [...model.publicKeys.apiKeys, ...model.publicKeys.pinnedKeys]; const uniqueKeys = uniqueBy(allKeys, (publicKey) => publicKey.getFingerprint()); const parsedKeys = await Promise.all( uniqueKeys.map(async (publicKey, index) => { const armoredPublicKey = await CryptoProxy.exportPublicKey({ key: publicKey, format: 'armored', }); const fingerprint = publicKey.getFingerprint(); const creationTime = publicKey.getCreationTime(); const expirationTime = await publicKey.getExpirationTime(); const algoInfos = [ publicKey.getAlgorithmInfo(), ...publicKey.subkeys.map((subkey) => subkey.getAlgorithmInfo()), ]; const algo = getFormattedAlgorithmNames(algoInfos); const isExpired = await CryptoProxy.isExpiredKey({ key: publicKey }); const isRevoked = await CryptoProxy.isRevokedKey({ key: publicKey }); const isTrusted = model.trustedFingerprints.has(fingerprint); const supportsEncryption = model.encryptionCapableFingerprints.has(fingerprint); const isObsolete = model.obsoleteFingerprints.has(fingerprint); const isCompromised = model.compromisedFingerprints.has(fingerprint); const isPrimary = !index && supportsEncryption && !isObsolete && !isCompromised && (totalApiKeys ? true : model.encrypt); const isWKD = model.isPGPExternal && index < totalApiKeys; const isUploaded = index >= totalApiKeys; const canBePrimary = !!index && supportsEncryption && !isObsolete && !isCompromised && (index < totalApiKeys ? isTrusted : !totalApiKeys && model.encrypt); const canBeTrusted = !isTrusted && !isUploaded && !isCompromised; const canBeUntrusted = isTrusted && !isUploaded; return { publicKey, armoredPublicKey, fingerprint, algo, creationTime, expirationTime, isPrimary, isWKD, isExpired, isRevoked, isTrusted, supportsEncryption, isObsolete, isCompromised, isUploaded, canBePrimary, canBeTrusted, canBeUntrusted, }; }) ); setKeys(parsedKeys); }; useEffect(() => { void parse(); }, [model.publicKeys, model.trustedFingerprints, model.encrypt]); return ( <Table hasActions> <thead> <tr> <th scope="col" className="text-ellipsis" title={c('Table header').t`Fingerprint`}>{c( 'Table header' ).t`Fingerprint`}</th> {!isNarrow && ( <th scope="col" className="text-ellipsis" title={c('Table header').t`Created`}>{c( 'Table header' ).t`Created`}</th> )} {!isTinyMobile && ( <th scope="col" className="w-1/10 text-ellipsis" title={c('Table header').t`Expires`}>{c( 'Table header' ).t`Expires`}</th> )} {!isNarrow && ( <th scope="col" className="text-ellipsis" title={c('Table header').t`Type`}>{c('Table header') .t`Type`}</th> )} <th scope="col" className="text-ellipsis w-1/6" title={c('Table header').t`Status`}>{c( 'Table header' ).t`Status`}</th> <th scope="col" className={clsx(['text-ellipsis', isNarrow && 'w-2/5'])} title={c('Table header').t`Actions`} >{c('Table header').t`Actions`}</th> </tr> </thead> <TableBody> {keys.map( ({ fingerprint, algo, creationTime, expirationTime, isPrimary, isWKD, publicKey, armoredPublicKey, isExpired, isRevoked, isTrusted, supportsEncryption, isObsolete, isCompromised, isUploaded, canBePrimary, canBeTrusted, canBeUntrusted, }) => { const creation = new Date(creationTime); const expiration = new Date(expirationTime); const untrustKeyText = c('PGP Key info').t`We recommend that you "untrust" this key.`; const obsoleteTooltipText = c('PGP Key info') .t`${emailAddress} has marked this key as obsolete. This key can only be used for signature verification.`; let compromisedTooltipText = c('PGP Key info') .t`${emailAddress} has marked this key as compromised. This key cannot be used neither for encryption nor for signature verification.`; if (isTrusted) { compromisedTooltipText += ' ' + untrustKeyText; } const list = [ { text: c('Action').t`Download`, onClick: () => { const blob = new Blob([armoredPublicKey], { type: 'text/plain', }); const filename = `publickey - ${model.emailAddress} - 0x${fingerprint .slice(0, 8) .toUpperCase()}.asc`; downloadFile(blob, filename); }, }, ]; if (canBePrimary) { list.push({ text: c('Action').t`Use for sending`, onClick: () => { const apiKeyIndex = model.publicKeys.apiKeys.findIndex( (key) => key.getFingerprint() === fingerprint ); const pinnedKeyIndex = model.publicKeys.pinnedKeys.findIndex( (key) => key.getFingerprint() === fingerprint ); const reOrderedApiKeys = apiKeyIndex !== -1 ? move(model.publicKeys.apiKeys, apiKeyIndex, 0) : model.publicKeys.apiKeys; const reOrderedPinnedKeys = pinnedKeyIndex !== -1 ? move(model.publicKeys.pinnedKeys, pinnedKeyIndex, 0) : model.publicKeys.pinnedKeys; setModel({ ...model, publicKeys: { apiKeys: reOrderedApiKeys, pinnedKeys: reOrderedPinnedKeys, verifyingPinnedKeys: getVerifyingKeys( reOrderedApiKeys, model.compromisedFingerprints ), }, }); }, }); } if (canBeTrusted) { list.push({ text: c('Action').t`Trust`, onClick: () => { const trustedFingerprints = new Set(model.trustedFingerprints); trustedFingerprints.add(fingerprint); const trustedKey = model.publicKeys.apiKeys.find( (key) => key.getFingerprint() === fingerprint ); if (trustedKey) { setModel({ ...model, encrypt: true, publicKeys: { ...model.publicKeys, pinnedKeys: [...model.publicKeys.pinnedKeys, trustedKey], verifyingPinnedKeys: [ ...model.publicKeys.verifyingPinnedKeys, trustedKey, ], }, trustedFingerprints, }); } }, }); } if (canBeUntrusted) { list.push({ text: c('Action').t`Untrust`, onClick: () => { const trustedFingerprints = new Set(model.trustedFingerprints); trustedFingerprints.delete(fingerprint); const pinnedKeys = model.publicKeys.pinnedKeys.filter( (key) => key.getFingerprint() !== fingerprint ); const verifyingPinnedKeys = model.publicKeys.verifyingPinnedKeys.filter( (key) => key.getFingerprint() !== fingerprint ); setModel({ ...model, publicKeys: { ...model.publicKeys, pinnedKeys, verifyingPinnedKeys, }, trustedFingerprints, }); }, }); } if (isUploaded) { list.push({ text: c('Action').t`Remove`, onClick: () => { const trustedFingerprints = new Set(model.trustedFingerprints); const encryptionCapableFingerprints = new Set(model.encryptionCapableFingerprints); trustedFingerprints.delete(fingerprint); encryptionCapableFingerprints.delete(fingerprint); const pinnedKeys = model.publicKeys.pinnedKeys.filter( (publicKey) => publicKey.getFingerprint() !== fingerprint ); const hasEncryptionKeys = model.publicKeys.apiKeys.length > 0 || pinnedKeys.length > 0; setModel({ ...model, // If no more encryption keys are available, then we switch off the encryption toggle. encrypt: hasEncryptionKeys ? model.encrypt : undefined, trustedFingerprints, encryptionCapableFingerprints, publicKeys: { ...model.publicKeys, pinnedKeys, verifyingPinnedKeys: model.publicKeys.verifyingPinnedKeys.filter( (publicKey) => publicKey.getFingerprint() !== fingerprint ), }, }); }, }); } const cells = [ <div key={fingerprint} title={fingerprint} className="flex flex-nowrap"> <ContactKeyWarningIcon className="mr-2 flex-item-noshrink flex-item-centered-vert" publicKey={publicKey} emailAddress={model.emailAddress} isInternal={model.isPGPInternal} supportsEncryption={supportsEncryption} /> <span className="flex-item-fluid text-ellipsis">{fingerprint}</span> </div>, !isNarrow && (isValid(creation) ? format(creation, 'PP', { locale: dateLocale }) : '-'), !isTinyMobile && (isValid(expiration) ? format(expiration, 'PP', { locale: dateLocale }) : '-'), !isNarrow && algo, <Fragment key={fingerprint}> {isPrimary ? <Badge type="primary">{primaryText}</Badge> : null} {isObsolete && !isCompromised ? ( <Badge type="warning" url={getKnowledgeBaseUrl('/download-public-private-key')} tooltip={obsoleteTooltipText} > {obsoleteText} </Badge> ) : null} {isCompromised ? ( <Badge type="error" url={getKnowledgeBaseUrl('/download-public-private-key')} tooltip={compromisedTooltipText} > {compromisedText} </Badge> ) : null} {isWKD ? <Badge type="origin">{wkdText}</Badge> : null} {isTrusted ? <Badge type="success">{trustedText}</Badge> : null} {isRevoked ? <Badge type="error">{revokedText}</Badge> : null} {isExpired ? <Badge type="error">{expiredText}</Badge> : null} </Fragment>, <DropdownActions key={fingerprint} size="small" list={list} />, ].filter(Boolean); return <TableRow key={fingerprint} cells={cells} />; } )} </TableBody> </Table> ); }; export default ContactKeysTable;
6,031
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/email/ContactMIMETypeSelect.tsx
import { c } from 'ttag'; import { CONTACT_MIME_TYPES, MIME_TYPES, MIME_TYPES_MORE } from '@proton/shared/lib/constants'; import { Option, SelectTwo } from '../../../components'; import { SelectChangeEvent } from '../../../components/selectTwo/select'; interface Props { value: string; onChange: (mimeType: CONTACT_MIME_TYPES) => void; disabled: boolean; } const ContactMIMETypeSelect = ({ value, onChange, disabled }: Props) => { const handleChange = ({ value }: SelectChangeEvent<string>) => onChange(value as CONTACT_MIME_TYPES); return ( <SelectTwo value={value} disabled={disabled} onChange={handleChange}> <Option title={c('MIME type').t`Automatic`} value={MIME_TYPES_MORE.AUTOMATIC} /> <Option title={c('MIME type').t`Plain text`} value={MIME_TYPES.PLAINTEXT} /> </SelectTwo> ); }; export default ContactMIMETypeSelect;
6,032
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/email/ContactPGPSettings.tsx
import { ChangeEvent, Dispatch, SetStateAction } from 'react'; import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { CryptoProxy } from '@proton/crypto'; import { BRAND_NAME, CONTACT_PGP_SCHEMES } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { ContactPublicKeyModel, MailSettings } from '@proton/shared/lib/interfaces'; import { ArmoredKeyWithInfo } from '@proton/shared/lib/keys'; import { getIsValidForSending, getKeyEncryptionCapableStatus } from '@proton/shared/lib/keys/publicKeys'; import { Alert, Field, Info, Label, Row, Toggle } from '../../../components'; import { useNotifications } from '../../../hooks'; import SelectKeyFiles from '../../keys/shared/SelectKeyFiles'; import ContactKeysTable from './ContactKeysTable'; import ContactSchemeSelect from './ContactSchemeSelect'; import SignEmailsSelect from './SignEmailsSelect'; interface Props { model: ContactPublicKeyModel; setModel: Dispatch<SetStateAction<ContactPublicKeyModel | undefined>>; mailSettings?: MailSettings; } const ContactPGPSettings = ({ model, setModel, mailSettings }: Props) => { const { createNotification } = useNotifications(); const hasApiKeys = !!model.publicKeys.apiKeys.length; // internal or WKD keys const hasPinnedKeys = !!model.publicKeys.pinnedKeys.length; const isPrimaryPinned = hasApiKeys && model.trustedFingerprints.has(model.publicKeys.apiKeys[0].getFingerprint()); const noPinnedKeyCanSend = hasPinnedKeys && !model.publicKeys.pinnedKeys.some((publicKey) => getIsValidForSending(publicKey.getFingerprint(), model)); const noApiKeyCanSend = hasApiKeys && !model.publicKeys.apiKeys.some((publicKey) => getIsValidForSending(publicKey.getFingerprint(), model)); const askForPinning = hasPinnedKeys && hasApiKeys && (noPinnedKeyCanSend || !isPrimaryPinned); const hasCompromisedPinnedKeys = model.publicKeys.pinnedKeys.some((key) => model.compromisedFingerprints.has(key.getFingerprint()) ); const canUploadKeys = model.isPGPExternalWithoutWKDKeys; /** * Add / update keys to model * @param {Array<PublicKey>} keys */ const handleUploadKeys = async (keys: ArmoredKeyWithInfo[]) => { if (!keys.length) { return createNotification({ type: 'error', text: c('Error').t`Invalid public key file`, }); } const pinnedKeys = [...model.publicKeys.pinnedKeys]; const trustedFingerprints = new Set(model.trustedFingerprints); const encryptionCapableFingerprints = new Set(model.encryptionCapableFingerprints); // Each promise returns true if the corresponding key was processed successfully const successStatuses = await Promise.all( keys.map(async ({ keyIsPrivate, armoredKey }) => { if (keyIsPrivate) { // do not allow to upload private keys createNotification({ type: 'error', text: c('Error').t`Invalid public key file`, }); return false; } const publicKey = await CryptoProxy.importPublicKey({ armoredKey }); const fingerprint = publicKey.getFingerprint(); const canEncrypt = await getKeyEncryptionCapableStatus(publicKey); if (canEncrypt) { encryptionCapableFingerprints.add(fingerprint); } if (!trustedFingerprints.has(fingerprint)) { trustedFingerprints.add(fingerprint); pinnedKeys.push(publicKey); return true; } const indexFound = pinnedKeys.findIndex((publicKey) => publicKey.getFingerprint() === fingerprint); createNotification({ text: c('Info').t`Duplicate key updated`, type: 'warning' }); pinnedKeys.splice(indexFound, 1, publicKey); return true; }) ); setModel({ ...model, // automatically enable encryption on (successful) key upload encrypt: model.encrypt || successStatuses.some(Boolean), publicKeys: { ...model.publicKeys, pinnedKeys }, trustedFingerprints, encryptionCapableFingerprints, }); }; return ( <> {!hasApiKeys && ( <Alert className="mb-4"> {c('Info') .t`Setting up PGP allows you to send end-to-end encrypted emails with a non-${BRAND_NAME} user that uses a PGP compatible service.`} <div> <Href href={getKnowledgeBaseUrl('/how-to-use-pgp')}>{c('Link').t`Learn more`}</Href> </div> </Alert> )} {!!model.publicKeys.pinnedKeys.length && askForPinning && ( <Alert className="mb-4" type="error">{c('Info') .t`Address Verification with Trusted Keys is enabled for this address. To be able to send to this address, first trust public keys that can be used for sending.`}</Alert> )} {hasCompromisedPinnedKeys && ( <Alert className="mb-4" type="warning">{c('Info') .t`One or more of your trusted keys were marked "compromised" by their owner. We recommend that you "untrust" these keys.`}</Alert> )} {model.pgpAddressDisabled && ( <Alert className="mb-4" type="warning">{c('Info') .t`This address is disabled. To be able to send to this address, the owner must first enable the address.`}</Alert> )} {model.isInternalWithDisabledE2EEForMail && ( <Alert className="mb-4" type="warning">{c('Info') .t`The owner of this address has disabled end-to-end encryption. To be able to send encrypted emails to this address, the owner must re-enable end-to-end encryption.`}</Alert> )} {hasApiKeys && !hasPinnedKeys && !model.isInternalWithDisabledE2EEForMail && ( <Alert className="mb-4"> {c('Info') .t`To use Address Verification, you must trust one or more available public keys, including the one you want to use for sending. This prevents the encryption keys from being faked.`} <div> <Href href={getKnowledgeBaseUrl('/address-verification')}>{c('Link').t`Learn more`}</Href> </div> </Alert> )} {model.isPGPExternal && (noPinnedKeyCanSend || noApiKeyCanSend) && model.encrypt && ( <Alert className="mb-4" type="error"> {c('Info') .t`None of the uploaded keys are valid for encryption. To be able to send messages to this address, please upload a valid key or disable "Encrypt emails".`} <div> <Href href={getKnowledgeBaseUrl('/how-to-use-pgp')}>{c('Link').t`Learn more`}</Href> </div> </Alert> )} {model.isPGPExternal && ( <> <Row> <Label htmlFor="encrypt-toggle"> {c('Label').t`Encrypt emails`} <Info className="ml-2" title={c('Tooltip') .t`Email encryption forces email signature to help authenticate your sent messages`} /> </Label> <Field className="pt-2 flex flex-align-items-center"> <Toggle className="mr-2" id="encrypt-toggle" checked={model.encrypt} disabled={!hasPinnedKeys && !hasApiKeys} onChange={({ target }: ChangeEvent<HTMLInputElement>) => setModel({ ...model, encrypt: target.checked, }) } /> <div className="flex-item-fluid"> {model.encrypt && c('Info').t`Emails are automatically signed`} </div> </Field> </Row> <Row> <Label htmlFor="sign-select"> {c('Label').t`Sign emails`} <Info className="ml-2" title={c('Tooltip') .t`Digitally signing emails helps authenticating that messages are sent by you`} /> </Label> <Field> <SignEmailsSelect id="sign-select" value={model.encrypt ? true : model.sign} mailSettings={mailSettings} disabled={model.encrypt} onChange={(sign?: boolean) => setModel({ ...model, sign })} /> </Field> </Row> <Row> <Label> {c('Label').t`PGP scheme`} <Info className="ml-2" title={c('Tooltip') .t`Select the PGP scheme to be used when signing or encrypting to a user. Note that PGP/Inline forces plain text messages`} /> </Label> <Field> <ContactSchemeSelect value={model.scheme} mailSettings={mailSettings} onChange={(scheme: CONTACT_PGP_SCHEMES) => setModel({ ...model, scheme })} /> </Field> </Row> </> )} {canUploadKeys && ( <Row> <Label> {c('Label').t`Public keys`} { <Info className="ml-2" title={c('Tooltip') .t`Upload a public key to enable sending end-to-end encrypted emails to this email`} /> } </Label> <Field className="mt-2 md:mt-0"> <SelectKeyFiles onUpload={handleUploadKeys} multiple /> </Field> </Row> )} {!canUploadKeys && ( <Row> <Label>{c('Label').t`Public keys`}</Label> </Row> )} {(hasApiKeys || hasPinnedKeys) && <ContactKeysTable model={model} setModel={setModel} />} </> ); }; export default ContactPGPSettings;
6,033
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/email/ContactSchemeSelect.tsx
import { c } from 'ttag'; import { CONTACT_PGP_SCHEMES, PGP_SCHEMES, PGP_SCHEMES_MORE } from '@proton/shared/lib/constants'; import { PGP_SCHEME_TEXT } from '@proton/shared/lib/contacts/constants'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import { Option, SelectTwo } from '../../../components'; import { SelectChangeEvent } from '../../../components/selectTwo/select'; const { INLINE, MIME } = PGP_SCHEME_TEXT; const { PGP_MIME, PGP_INLINE } = PGP_SCHEMES; interface Props { value: string; mailSettings?: MailSettings; onChange: (value: CONTACT_PGP_SCHEMES) => void; } const ContactSchemeSelect = ({ value, mailSettings, onChange }: Props) => { const defaultValueText = mailSettings?.PGPScheme === PACKAGE_TYPE.SEND_PGP_INLINE ? INLINE : MIME; const handleChange = ({ value }: SelectChangeEvent<string>) => onChange(value as CONTACT_PGP_SCHEMES); return ( <SelectTwo value={value} onChange={handleChange} data-testid="email-settings:scheme-dropdown"> <Option title={c('Default encryption scheme').t`Use global default (${defaultValueText})`} value={PGP_SCHEMES_MORE.GLOBAL_DEFAULT} data-testid="scheme-dropdown:default" /> <Option title={MIME} value={PGP_MIME} data-testid="scheme-dropdown:pgp_mime" /> <Option title={INLINE} value={PGP_INLINE} data-testid="scheme-dropdown:pgp_inline" /> </SelectTwo> ); }; export default ContactSchemeSelect;
6,034
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/email/SignEmailsSelect.tsx
import { c } from 'ttag'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { SIGN } from '@proton/shared/lib/mail/mailSettings'; import { Option, SelectTwo } from '../../../components'; import { SelectChangeEvent } from '../../../components/selectTwo/select'; interface Props { id?: string; value?: boolean; mailSettings?: MailSettings; disabled?: boolean; onChange: (value: boolean | undefined) => void; } const SignEmailsSelect = ({ id, value, mailSettings, disabled, onChange }: Props) => { // An `undefined` value indicates the "default" option is selected. // However, `undefined` cannot be used as `Option` identifier, hence we convert to/from `null`. const handleChange = ({ value }: SelectChangeEvent<boolean | null>) => onChange(value === null ? undefined : value); const SIGN_LABEL = c('Signing preference for emails').t`Sign`; const DO_NOT_SIGN_LABEL = c('Signing preference for emails').t`Don't sign`; const globalDefaultText = mailSettings?.Sign === SIGN.ENABLED ? SIGN_LABEL : DO_NOT_SIGN_LABEL; return ( <SelectTwo id={id} value={value === undefined ? null : value} onChange={handleChange} disabled={disabled}> <Option title={c('Default signing preference').t`Use global default (${globalDefaultText})`} value={null} /> <Option title={SIGN_LABEL} value={true} /> <Option title={DO_NOT_SIGN_LABEL} value={false} /> </SelectTwo> ); }; export default SignEmailsSelect;
6,035
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupDeleteModal.tsx
import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { allSucceded } from '@proton/shared/lib/api/helpers/response'; import { deleteLabels } from '@proton/shared/lib/api/labels'; import { ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { Alert, ModalProps, Prompt } from '../../../components'; import { useApi, useContactGroups, useEventManager, useNotifications } from '../../../hooks'; export interface ContactGroupDeleteProps { groupIDs: string[]; onDelete?: () => void; onClose?: () => void; } type Props = ContactGroupDeleteProps & ModalProps; const ContactGroupDeleteModal = ({ groupIDs = [], onDelete, ...rest }: Props) => { const api = useApi(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [loading, withLoading] = useLoading(); const [groups = []] = useContactGroups(); const handleDelete = async () => { const apiSuccess = allSucceded(await api(deleteLabels(groupIDs))); await call(); onDelete?.(); rest.onClose?.(); if (!apiSuccess) { return createNotification({ text: c('Error').t`Some groups could not be deleted`, type: 'warning' }); } createNotification({ text: c('Success').ngettext(msgid`Contact group deleted`, `Contact groups deleted`, groupIDs.length), }); }; const count = groupIDs.length; const { Name = '' } = groups.find((group: ContactGroup) => group.ID === groupIDs[0]) || {}; const title = count === 1 ? c('Title').t`Delete ${Name}` : // translator: the variable is a positive integer (written in digits) always strictly bigger than 1 c('Title').ngettext(msgid`Delete ${count} contact group`, `Delete ${count} contact groups`, count); let alertText = c('Warning').t`Are you sure you want to permanently delete this contact group?`; if (count > 1) { alertText = c('Warning').t`Are you sure you want to permanently delete these contact groups?`; } let infoMessage = c('Info').t`Please note that addresses assigned to this group will NOT be deleted.`; if (count > 1) { infoMessage = c('Info').t`Please note that addresses assigned to these groups will NOT be deleted.`; } return ( <Prompt title={title} buttons={[ <Button color="danger" data-testid="delete-button" onClick={() => withLoading(handleDelete())} loading={loading} > {c('Action').t`Delete`} </Button>, <Button onClick={rest.onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > <Alert className="mb-4" type="info"> {infoMessage} </Alert> <Alert className="mb-4" type="error"> {alertText} </Alert> </Prompt> ); }; export default ContactGroupDeleteModal;
6,036
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupDetailsModal.scss
.contact-group-details-chip { block-size: 1em; inline-size: 1em; }
6,037
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupDetailsModal.test.tsx
import { LABEL_TYPE } from '@proton/shared/lib/constants'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { STATUS } from '@proton/shared/lib/models/cache'; import { cache, clearAll, minimalCache, render } from '../tests/render'; import ContactGroupDetailsModal, { ContactGroupDetailsProps } from './ContactGroupDetailsModal'; describe('ContactGroupDetailsModal', () => { const props: ContactGroupDetailsProps = { contactGroupID: 'ContactGroupID', onEdit: jest.fn(), onDelete: jest.fn(), onExport: jest.fn(), onUpgrade: jest.fn(), }; const group: ContactGroup = { ID: 'ContactGroupID', Name: 'GroupName', Color: 'GroupColor', Path: '/ContactGroupID', Display: 1, Exclusive: 1, Notify: 1, Order: 1, Type: LABEL_TYPE.CONTACT_GROUP, }; const contactEmail1: ContactEmail = { ID: 'ContactEmail1', Email: 'email1@test.com', Name: 'email1', Type: [], Defaults: 1, Order: 1, ContactID: 'ContactID', LabelIDs: ['ContactGroupID'], LastUsedTime: 1, }; const contactEmail2: ContactEmail = { ...contactEmail1, ID: 'ContactEmail2', Email: 'email2@test.com', Name: 'email2', }; const contactEmail3: ContactEmail = { ...contactEmail1, ID: 'ContactEmail3', Email: 'email3@test.com', Name: 'email3', }; beforeEach(clearAll); it('should display a contact group', async () => { minimalCache(); cache.set('Labels', { status: STATUS.RESOLVED, value: [group] }); cache.set('ContactEmails', { status: STATUS.RESOLVED, value: [contactEmail1, contactEmail2, contactEmail3] }); const { getByText } = render(<ContactGroupDetailsModal open={true} {...props} />, false); getByText(group.Name); getByText('3 email addresses'); getByText(contactEmail1.Name); getByText(contactEmail2.Name); getByText(contactEmail3.Name); }); });
6,038
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupDetailsModal.tsx
import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { Recipient } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import { Icon, ModalProps, ModalTwo } from '../../../components'; import ModalContent from '../../../components/modalTwo/ModalContent'; import ModalFooter from '../../../components/modalTwo/ModalFooter'; import ModalHeader from '../../../components/modalTwo/ModalHeader'; import Tooltip from '../../../components/tooltip/Tooltip'; import { useContactEmails, useContactGroups, useUser } from '../../../hooks'; import { ContactExportingProps } from '../modals/ContactExportingModal'; import RecipientDropdownItem from '../view/RecipientDropdownItem'; import { ContactGroupDeleteProps } from './ContactGroupDeleteModal'; import { ContactGroupEditProps } from './ContactGroupEditModal'; import './ContactGroupDetailsModal.scss'; export interface ContactGroupDetailsProps { contactGroupID: string; onEdit: (props: ContactGroupEditProps) => void; onDelete: (props: ContactGroupDeleteProps) => void; onExport: (props: ContactExportingProps) => void; onUpgrade: () => void; onCompose?: (recipients: Recipient[], attachments: File[]) => void; onCloseContactDetailsModal?: () => void; } type Props = ContactGroupDetailsProps & ModalProps; const ContactGroupDetailsModal = ({ contactGroupID, onEdit, onDelete, onExport, onUpgrade, onCompose, onCloseContactDetailsModal, ...rest }: Props) => { const [user] = useUser(); const [contactGroups = [], loadingGroups] = useContactGroups(); const [contactEmails = [], loadingEmails] = useContactEmails(); const loading = loadingGroups || loadingEmails; const group = contactGroups.find(({ ID }) => ID === contactGroupID); const emails = contactEmails.filter(({ LabelIDs = [] }: { LabelIDs: string[] }) => LabelIDs.includes(contactGroupID) ); const emailsCount = emails.length; const handleEdit = () => { if (!user.hasPaidMail) { onUpgrade(); return; } onEdit({ contactGroupID }); rest.onClose?.(); }; const handleDelete = () => { onDelete({ groupIDs: [contactGroupID] }); rest.onClose?.(); }; const handleExportContactGroup = () => { onExport({ contactGroupID }); }; const handleCompose = () => { if (onCompose) { const recipients = emails.map((email) => ({ Name: email.Name, Address: email.Email })); onCompose([...recipients], []); rest.onClose?.(); onCloseContactDetailsModal?.(); } }; const handleComposeSingle = (recipient: Recipient) => { if (onCompose) { onCompose([recipient], []); rest.onClose?.(); onCloseContactDetailsModal?.(); } }; const getComposeAction = (recipient: Recipient) => { return ( onCompose && ( <div className="mr-2"> <Tooltip title={c('Action').t`Compose`}> <Button color="weak" shape="ghost" icon onClick={() => handleComposeSingle(recipient)}> <Icon name="pen-square" alt={c('Action').t`Compose`} /> </Button> </Tooltip> </div> ) ); }; return ( <ModalTwo size="large" className="contacts-modal" {...rest}> <ModalHeader title={ <div className="flex flex-nowrap flex-align-items-center gap-2"> <span style={{ backgroundColor: group?.Color ?? '', '--w-custom': '2.125rem' }} className="rounded w-custom text-center flex-item-noshrink" > <Icon color="white" name="users" /> </span> <span className="text-ellipsis" title={group?.Name}> {group?.Name} </span> </div> } actions={[ <Tooltip title={c('Action').t`Edit`}> <Button icon shape="ghost" color="weak" onClick={handleEdit} disabled={loading} className="inline-flex ml-2" data-testid="group-summary:edit" > <Icon name="pen" alt={c('Action').t`Edit`} /> </Button> </Tooltip>, <Tooltip title={c('Action').t`Export contact group`}> <Button color="weak" shape="ghost" icon onClick={handleExportContactGroup} disabled={loading} className="inline-flex ml-2" data-testid="group-summary:export" > <Icon name="arrow-up-from-square" alt={c('Action').t`Export contact group`} /> </Button> </Tooltip>, <Tooltip title={c('Action').t`Delete`}> <Button color="weak" shape="ghost" icon onClick={handleDelete} disabled={loading} className="inline-flex ml-2" data-testid="group-summary:delete" > <Icon name="trash" alt={c('Action').t`Delete`} /> </Button> </Tooltip>, ]} /> <ModalContent> <h4 className="mb-4 color-weak text-lg"> {c('Title').ngettext( msgid`${emailsCount} email address`, `${emailsCount} email addresses`, emailsCount )} </h4> {emails.map((email) => { const recipient: Recipient = { Name: email.Name, Address: email.Email }; return ( <RecipientDropdownItem label={recipient.Name} recipient={recipient} displaySenderImage={false} closeDropdown={noop} additionalAction={getComposeAction(recipient)} simple key={email.Email} /> ); })} </ModalContent> <ModalFooter> <Button onClick={rest.onClose}>{c('Action').t`Close`}</Button> {onCompose && ( <Button color="norm" onClick={handleCompose} disabled={loading} className="inline-flex flex-justify-center" > <Icon name="pen-square" className="flex-align-self-center mr-2" alt={c('Action').t`New message`} /> {c('Action').t`New message`} </Button> )} </ModalFooter> </ModalTwo> ); }; export default ContactGroupDetailsModal;
6,039
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupEditModal.test.tsx
import { fireEvent, getByDisplayValue, waitFor } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import { ACCENT_COLORS } from '@proton/shared/lib/colors'; import { LABEL_TYPE } from '@proton/shared/lib/constants'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { MAX_RECIPIENTS } from '@proton/shared/lib/mail/mailSettings'; import { STATUS } from '@proton/shared/lib/models/cache'; import { api, cache, clearAll, getCard, minimalCache, mockedCryptoApi, render } from '../tests/render'; import ContactGroupEditModal, { ContactGroupEditProps } from './ContactGroupEditModal'; describe('ContactGroupEditModal', () => { const props: ContactGroupEditProps = { contactGroupID: 'ContactGroupID', selectedContactEmails: [], onDelayedSave: jest.fn(), }; const group: ContactGroup = { ID: 'ContactGroupID', Name: 'GroupName', Color: 'GroupColor', Path: '/ContactGroupID', Display: 1, Exclusive: 1, Notify: 1, Order: 1, Type: LABEL_TYPE.CONTACT_GROUP, }; const contactEmail1: ContactEmail = { ID: 'ContactEmail1', Email: 'email1@test.com', Name: 'email1', Type: [], Defaults: 1, Order: 1, ContactID: 'ContactID', LabelIDs: ['ContactGroupID'], LastUsedTime: 1, }; const contactEmail2: ContactEmail = { ...contactEmail1, ID: 'ContactEmail2', Email: 'email2@test.com', Name: 'email2', }; const contactEmail3: ContactEmail = { ...contactEmail1, ID: 'ContactEmail3', Email: 'email3@test.com', Name: 'email3', }; beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should display a contact group', async () => { minimalCache(); cache.set('Labels', { status: STATUS.RESOLVED, value: [group] }); cache.set('ContactEmails', { status: STATUS.RESOLVED, value: [contactEmail1, contactEmail2, contactEmail3] }); cache.set('MailSettings', { RecipientLimit: MAX_RECIPIENTS }); const updateSpy = jest.fn(); const createContactSpy = jest.fn(); const labelSpy = jest.fn(); const unlabelSpy = jest.fn(); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === `core/v4/labels/${group.ID}`) { updateSpy(args.data); return { Label: { ID: group.ID } }; } if (args.url === 'contacts/v4/contacts') { createContactSpy(args.data); return {}; } if (args.url === 'contacts/v4/contacts/emails/label') { labelSpy(args.data); return {}; } if (args.url === 'contacts/v4/contacts/emails/unlabel') { unlabelSpy(args.data); return {}; } }); const { getByTestId, getByText, getAllByText } = render( <ContactGroupEditModal open={true} {...props} />, false ); const name = document.getElementById('contactGroupName') as HTMLElement; fireEvent.change(name, { target: { value: 'NewName' } }); const colorDropdown = getByTestId('dropdown-button'); fireEvent.click(colorDropdown); const colorButton = document.getElementById('contactGroupColor') as HTMLElement; fireEvent.click(colorButton); const colorRadio = getByDisplayValue(document.body, ACCENT_COLORS[0]); fireEvent.click(colorRadio); const removeButtons = getAllByText('Remove'); fireEvent.click(removeButtons[2]); const email = document.getElementById('contactGroupEmail') as HTMLElement; fireEvent.change(email, { target: { value: 'email4@test.com' } }); const addButton = getByText('Add'); fireEvent.click(addButton); const saveButton = getByText('Save'); fireEvent.click(saveButton); await waitFor(() => { expect(updateSpy).toHaveBeenCalled(); }); await waitFor(() => { expect(createContactSpy).toHaveBeenCalled(); }); await waitFor(() => { expect(labelSpy).toHaveBeenCalled(); }); await waitFor(() => { expect(unlabelSpy).toHaveBeenCalled(); }); const updateData = updateSpy.mock.calls[0][0]; expect(updateData.Name).toBe('NewName'); expect(updateData.Color).toBe(ACCENT_COLORS[0]); const createContactData = createContactSpy.mock.calls[0][0]; const cards = createContactData.Contacts[0].Cards; const signed = getCard(cards); expect(signed).toContain('ITEM1.EMAIL;PREF=1:email4@test.com'); const labelData = labelSpy.mock.calls[0][0]; expect(labelData.ContactEmailIDs).toEqual([contactEmail1.ID, contactEmail2.ID]); const unlabelData = unlabelSpy.mock.calls[0][0]; expect(unlabelData.ContactEmailIDs).toEqual([contactEmail3.ID]); }); });
6,040
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupEditModal.tsx
import { ChangeEvent, FormEvent, useMemo, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button, Input } from '@proton/atoms'; import { getRandomAccentColor } from '@proton/shared/lib/colors'; import { hasReachedContactGroupMembersLimit } from '@proton/shared/lib/contacts/helpers/contactGroup'; import { validateEmailAddress } from '@proton/shared/lib/helpers/email'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts/Contact'; import { DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/mailSettings'; import diff from '@proton/utils/diff'; import isTruthy from '@proton/utils/isTruthy'; import { AddressesAutocompleteItem, Alert, Autocomplete, ColorPicker, Field, Label, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Row, getContactsAutocompleteItems, } from '../../../components'; import { useContactEmails, useContactGroups, useMailSettings } from '../../../hooks'; import useUpdateGroup from '../hooks/useUpdateGroup'; import ContactGroupTable from './ContactGroupTable'; export interface ContactGroupEditProps { contactGroupID?: string; selectedContactEmails?: ContactEmail[]; onDelayedSave?: (groupID: string) => void; } type Props = ContactGroupEditProps & ModalProps; const ContactGroupEditModal = ({ contactGroupID, selectedContactEmails = [], onDelayedSave, ...rest }: Props) => { const [mailSettings] = useMailSettings(); const [loading, setLoading] = useState(false); const [error, setError] = useState(false); const [contactGroups = []] = useContactGroups(); const contactEmails = useContactEmails()[0] || []; const [value, setValue] = useState(''); const updateGroup = useUpdateGroup(); const isValidEmail = useMemo(() => validateEmailAddress(value), [value]); const contactGroup = contactGroupID && contactGroups.find(({ ID }) => ID === contactGroupID); const existingContactEmails = contactGroupID ? contactEmails.filter(({ LabelIDs = [] }: { LabelIDs: string[] }) => LabelIDs.includes(contactGroupID)) : []; const title = contactGroupID ? c('Title').t`Edit contact group` : c('Title').t`Create new group`; const [model, setModel] = useState<{ name: string; color: string; contactEmails: ContactEmail[] }>({ name: contactGroupID && contactGroup ? contactGroup.Name : '', color: contactGroupID && contactGroup ? contactGroup.Color : getRandomAccentColor(), contactEmails: contactGroupID ? existingContactEmails : selectedContactEmails, }); const contactEmailIDs = model.contactEmails.map(({ ID }: ContactEmail) => ID); const canAddMoreContacts = hasReachedContactGroupMembersLimit(model.contactEmails.length, mailSettings); const contactsAutocompleteItems = useMemo(() => { return [...getContactsAutocompleteItems(contactEmails, ({ ID }) => !contactEmailIDs.includes(ID))]; }, [contactEmails, contactEmailIDs]); const handleChangeName = ({ target }: ChangeEvent<HTMLInputElement>) => setModel({ ...model, name: target.value }); const handleChangeColor = (color: string) => setModel({ ...model, color }); const handleAdd = () => { if (!isValidEmail) { return; } setModel((model) => ({ ...model, contactEmails: [...model.contactEmails, { Name: value, Email: value } as ContactEmail], })); setValue(''); }; const handleSelect = (newContactEmail: AddressesAutocompleteItem | string) => { if (!canAddMoreContacts) { setError(true); return; } if (typeof newContactEmail === 'string' || newContactEmail.type === 'major') { handleAdd(); } else { const newContact = contactEmails.find((contact: ContactEmail) => contact.ID === newContactEmail.value.ID); if (newContact) { setModel((model) => ({ ...model, contactEmails: [...model.contactEmails, newContact], })); } setValue(''); } setError(false); }; const handleAddContact = () => { if (!canAddMoreContacts) { setError(true); return; } handleAdd(); setError(false); }; const handleDeleteEmail = (contactEmail: string) => { const index = model.contactEmails.findIndex(({ Email }: ContactEmail) => Email === contactEmail); if (index > -1) { const copy = [...model.contactEmails]; copy.splice(index, 1); setModel({ ...model, contactEmails: copy }); } }; const handleSubmit = async (event: FormEvent) => { event.preventDefault(); event.stopPropagation(); try { setLoading(true); const toAdd = model.contactEmails.filter(({ ID }) => isTruthy(ID)); const toCreate = !onDelayedSave ? model.contactEmails.filter(({ ID }) => !isTruthy(ID)) : // If delayed save, the contact we are editing does not really exists yet, so we need to remove it from the to create model.contactEmails.filter( (contactEmail) => !isTruthy(contactEmail.ID) && !selectedContactEmails?.includes(contactEmail) ); const toRemove = contactGroupID ? diff(existingContactEmails, toAdd) : []; await updateGroup({ groupID: contactGroupID, name: model.name, color: model.color, toAdd, toRemove, toCreate, onDelayedSave, }); rest.onClose?.(); } catch (error: any) { setLoading(false); throw error; } }; const contactEmailsLength = model.contactEmails.length; const maxContacts = mailSettings?.RecipientLimit || DEFAULT_MAILSETTINGS.RecipientLimit; const cannotAddMoreContactText = c('Action').ngettext( msgid`At most ${maxContacts} contact is allowed per contact group`, `At most ${maxContacts} contacts are allowed per contact group`, maxContacts ); return ( <ModalTwo size="large" className="contacts-modal" as="form" onSubmit={handleSubmit} {...rest}> <ModalTwoHeader title={title} /> <ModalTwoContent> <Row> <Label htmlFor="contactGroupName">{c('Label for contact group name').t`Name`}</Label> <Field className="flex-item-fluid"> <Input id="contactGroupName" placeholder={c('Placeholder for contact group name').t`Name`} value={model.name} onChange={handleChangeName} /> </Field> </Row> <Row> <Label htmlFor="contactGroupColor">{c('Label for contact group color').t`Color`}</Label> <Field className="w-full"> <ColorPicker id="contactGroupColor" color={model.color} onChange={handleChangeColor} /> </Field> </Row> {contactsAutocompleteItems.length ? ( <div className="flex flex-nowrap mb-4 on-mobile-flex-column"> <Label htmlFor="contactGroupEmail">{c('Label').t`Add email address`}</Label> <div> <div className="flex on-mobile-flex-column"> <Field className="flex-item-fluid"> <Autocomplete id="contactGroupEmail" options={contactsAutocompleteItems} limit={6} value={value} onChange={setValue} getData={(value) => value.label} type="search" placeholder={c('Placeholder').t`Start typing an email address`} onSelect={handleSelect} autoComplete="off" /> </Field> <Button className="ml-0 md:ml-4 mt-2 md:mt-0" onClick={handleAddContact} disabled={!isValidEmail} data-testid="create-group:add-email" > {c('Action').t`Add`} </Button> </div> {!canAddMoreContacts && error && ( <Alert className="mb-4 mt-2" type="error"> {cannotAddMoreContactText} </Alert> )} </div> </div> ) : null} <ContactGroupTable contactEmails={model.contactEmails} onDelete={handleDeleteEmail} /> {contactEmailsLength ? ( <div className="text-center color-weak"> {c('Info').ngettext( msgid`${contactEmailsLength} Member`, `${contactEmailsLength} Members`, contactEmailsLength )} </div> ) : null} </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose}>{c('Action').t`Close`}</Button> <Button color="norm" type="submit" disabled={loading} data-testid="create-group:save"> {c('Action').t`Save`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactGroupEditModal;
6,041
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupLabels.tsx
import { MouseEvent } from 'react'; import { ContactGroup } from '@proton/shared/lib/interfaces/contacts/Contact'; import LabelStack, { LabelDescription } from '../../../components/labelStack/LabelStack'; interface Props { contactGroups: ContactGroup[]; isStacked?: boolean; className?: string; onDetails: (contactGroupID: string, onCloseContactDetailsModal?: () => void) => void; maxNumber?: number; leftToRight?: boolean; onCloseModal?: () => void; } const ContactGroupLabels = ({ contactGroups, isStacked = true, className, onDetails, leftToRight, maxNumber, onCloseModal, }: Props) => { const labels = contactGroups.reduce((acc: LabelDescription[], contactGroup: ContactGroup) => { return contactGroup ? [ ...acc, { name: contactGroup.Name, color: contactGroup.Color, title: contactGroup.Name, onClick: (event: MouseEvent) => { onDetails(contactGroup.ID, onCloseModal); event.stopPropagation(); }, }, ] : acc; }, []); return ( <LabelStack className={className} labels={labels} isStacked={isStacked} leftToRight={leftToRight} maxNumber={maxNumber} /> ); }; export default ContactGroupLabels;
6,042
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/group/ContactGroupTable.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import isTruthy from '@proton/utils/isTruthy'; import { Table, TableBody, TableCell, TableHeader, TableRow } from '../../../components'; interface Props { contactEmails: ContactEmail[]; onDelete?: (Email: string) => void; } const ContactGroupTable = ({ contactEmails, onDelete }: Props) => { return ( <div className="flex flex-column min-h-custom" style={{ '--min-h-custom': '11.25rem' }}> <Table className="border-none"> <TableHeader> <tr> <TableCell type="header">{c('Table header').t`Name`}</TableCell> <TableCell type="header">{c('Table header').t`Address`}</TableCell> {onDelete ? ( <TableCell type="header" className="w-1/5"> {c('Table header').t`Action`} </TableCell> ) : null} </tr> </TableHeader> {contactEmails.length ? ( <TableBody> {contactEmails.map(({ ID, Name, Email }) => { const cells = [ <div className="text-ellipsis max-w-full" key={ID} title={Name}> {Name} </div>, <div className="text-ellipsis max-w-full" key={ID} title={Email}> {Email} </div>, onDelete ? ( <Button key={ID || Email} onClick={() => onDelete(Email)} color="danger" shape="outline" size="small" > {c('Action').t`Remove`} </Button> ) : null, ].filter(isTruthy); return <TableRow key={ID || Email} cells={cells} />; })} </TableBody> ) : null} </Table> {!contactEmails.length ? ( <div className="flex flex-align-items-center flex-justify-center min-h-custom" style={{ '--min-h-custom': '9.375rem' }} > {c('Info').t`No contacts added yet`} </div> ) : null} </div> ); }; export default ContactGroupTable;
6,043
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/helpers/senderImage.ts
import { SenderImageMode, getLogo } from '@proton/shared/lib/api/images'; import { createUrl } from '@proton/shared/lib/fetch/helpers'; import { rootFontSize } from '@proton/shared/lib/helpers/dom'; export const getImageSize = () => { if (window.devicePixelRatio >= 4) { return 128; } if (window.devicePixelRatio > 1) { return 64; } /* If the user has changed the default font size (via browser settings or accessibility settings) then increase the image definition */ const fontSize = rootFontSize(); if (fontSize > 16) { return 64; } return 32; }; export const getSenderImageUrl = ( apiUrl: string, UID: string, emailAddress: string, size?: number, bimiSelector?: string, mode?: SenderImageMode ) => { const config = getLogo(emailAddress, size, bimiSelector, mode, UID); const prefixedUrl = `${apiUrl}/${config.url}`; const url = createUrl(prefixedUrl, config.params); return url.toString(); };
6,044
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useApplyGroups.tsx
import { useCallback } from 'react'; import { c } from 'ttag'; import { useModalTwo } from '@proton/components/components'; import { labelContactEmails, unLabelContactEmails } from '@proton/shared/lib/api/contacts'; import { hasReachedContactGroupMembersLimit } from '@proton/shared/lib/contacts/helpers/contactGroup'; import { Contact, ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { useApi, useContactEmails, useContactGroups, useContacts, useEventManager, useMailSettings, useNotifications, } from '../../../hooks'; import ContactGroupLimitReachedModal, { ContactGroupLimitReachedProps } from '../modals/ContactGroupLimitReachedModal'; import { SelectEmailsProps } from '../modals/SelectEmailsModal'; /** * Collect contacts having multiple emails * Used for <SelectEmailsModal /> */ export const collectContacts = (contactEmails: ContactEmail[] = [], contacts: Contact[]) => { return contactEmails.reduce( (acc, { ContactID }) => { acc.duplicate[ContactID] = (acc.duplicate[ContactID] || 0) + 1; if (acc.duplicate[ContactID] === 2) { const contact = contacts.find(({ ID }: { ID: string }) => ID === ContactID); if (contact) { acc.contacts.push(contact); } } return acc; }, { contacts: [] as Contact[], duplicate: Object.create(null), } ); }; /** * Returns a reusable action to apply or remove groups to a list of contact emails */ const useApplyGroups = ( onLock?: (lock: boolean) => void, setLoading?: (loading: boolean) => void, onSelectEmails?: (props: SelectEmailsProps) => Promise<ContactEmail[]> ) => { const [mailSettings] = useMailSettings(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const api = useApi(); const contacts = useContacts()[0] || []; const userContactEmails = useContactEmails()[0] || []; const [groups = []] = useContactGroups(); const [contactGroupLimitReachedModal, handleShowContactGroupLimitReachedModal] = useModalTwo< ContactGroupLimitReachedProps, void >(ContactGroupLimitReachedModal, false); const applyGroups = useCallback( async (contactEmails: ContactEmail[], changes: { [groupID: string]: boolean }, preventNotification = false) => { const { contacts: collectedContacts } = collectContacts(contactEmails, contacts); // contact emails in contacts with only one email (and then, skipping the modal) const simpleEmails = contactEmails.filter( (contactEmail) => !collectedContacts.find((contact) => contactEmail.ContactID === contact.ID) ); // contact emails in contacts with multiple email (and then, passing through the modal) let selectedEmails: ContactEmail[] = []; if (collectedContacts.length) { const groupIDs = Object.entries(changes) .filter(([, isChecked]) => isChecked) .map(([groupID]) => groupID); if (groupIDs.length) { setLoading?.(false); selectedEmails = (await onSelectEmails?.({ groupIDs, contacts: collectedContacts, onLock })) || []; setLoading?.(true); } } // When removing a group, we remove it for all emails selected const listForRemoving = [...contactEmails]; // When adding a group, we do it only for the selected ones const listForAdding = [...simpleEmails, ...selectedEmails]; const groupEntries = Object.entries(changes); const cannotAddContactInGroupIDs: string[] = []; await Promise.all( groupEntries.map(([groupID, isChecked]) => { const contactGroup = groups.find((group) => group.ID === groupID); const contactGroupName = contactGroup?.Name; if (isChecked) { const groupExistingMembers = groupID && userContactEmails.filter(({ LabelIDs = [] }: { LabelIDs: string[] }) => LabelIDs.includes(groupID) ); const toLabel = listForAdding .filter(({ LabelIDs = [] }) => !LabelIDs.includes(groupID)) .map(({ ID }) => ID); if (!toLabel.length) { return Promise.resolve(); } // Cannot add more than 100 contacts in a contact group const canAddContact = hasReachedContactGroupMembersLimit( groupExistingMembers.length + toLabel.length, mailSettings, false ); if (!canAddContact) { cannotAddContactInGroupIDs.push(groupID); return Promise.resolve(); } if (!preventNotification && contactGroupName) { const notificationText = c('Info').t`Contact assigned to group ${contactGroupName}`; createNotification({ text: notificationText }); } return api(labelContactEmails({ LabelID: groupID, ContactEmailIDs: toLabel })); } const toUnlabel = listForRemoving .filter(({ LabelIDs = [] }) => LabelIDs.includes(groupID)) .map(({ ID }) => ID); if (!toUnlabel.length) { return Promise.resolve(); } if (!preventNotification && contactGroupName) { const notificationText = c('Info').t`Contact unassigned to group ${contactGroupName}`; createNotification({ text: notificationText }); } return api(unLabelContactEmails({ LabelID: groupID, ContactEmailIDs: toUnlabel })); }) ); if (cannotAddContactInGroupIDs.length > 0) { void handleShowContactGroupLimitReachedModal({ groupIDs: cannotAddContactInGroupIDs }); } await call(); }, [contacts, userContactEmails] ); return { applyGroups, contactGroupLimitReachedModal }; }; export default useApplyGroups;
6,045
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useContact.ts
import { useCallback, useContext } from 'react'; import { getContact } from '@proton/shared/lib/api/contacts'; import { Contact } from '@proton/shared/lib/interfaces/contacts/Contact'; import { useApi, useCachedModelResult } from '../../../hooks'; import ContactProviderContext from '../ContactProviderContext'; const useContact = (contactID: string) => { const cache = useContext(ContactProviderContext); const api = useApi(); const miss = useCallback(() => { return api<{ Contact: Contact[] }>(getContact(contactID)).then(({ Contact }) => Contact); }, []); return useCachedModelResult(cache, contactID, miss); }; export default useContact;
6,046
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useContactConditionally.ts
import { useCallback, useContext } from 'react'; import { getContact } from '@proton/shared/lib/api/contacts'; import { Contact } from '@proton/shared/lib/interfaces/contacts/Contact'; import { useApi, useCachedModelResult } from '../../../hooks'; import ContactProviderContext from '../ContactProviderContext'; const useContactConditionally = (contactID?: string) => { const cache = useContext(ContactProviderContext); const api = useApi(); const miss = useCallback(async () => { if (!contactID) { return; } const { Contact } = await api<{ Contact: Contact[] }>(getContact(contactID)); return Contact; }, [contactID]); return useCachedModelResult(cache, contactID, miss); }; export default useContactConditionally;
6,047
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useContactList.ts
import { useMemo } from 'react'; import { toMap } from '@proton/shared/lib/helpers/object'; import { normalize } from '@proton/shared/lib/helpers/string'; import { ContactEmail, ContactFormatted } from '@proton/shared/lib/interfaces/contacts'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { useContactEmails, useContactGroups, useContacts } from '../../../hooks'; import { useItemsSelection } from '../../items'; interface Props { search?: string; contactID?: string; contactGroupID?: string; } const useContactList = ({ search, contactID, contactGroupID }: Props) => { const [contactEmails, loadingContactEmails] = useContactEmails(); const [contacts = [], loadingContacts] = useContacts(); const [contactGroups = [], loadingContactGroups] = useContactGroups(); const normalizedSearch = normalize(search, true); const { contactGroupName, totalContactsInGroup } = useMemo<{ contactGroupName?: string; totalContactsInGroup?: number; }>(() => { if (!contactGroups.length || !contactGroupID) { return Object.create(null); } const contactGroup = contactGroups.find(({ ID }) => ID === contactGroupID); return { contactGroupName: contactGroup?.Name, totalContactsInGroup: contacts.filter(({ LabelIDs = [] }) => LabelIDs.includes(contactGroupID)).length, }; }, [contacts, contactGroups, contactGroupID]); const contactEmailsMap = useMemo(() => { if (!Array.isArray(contactEmails)) { return {}; } return contactEmails.reduce<SimpleMap<ContactEmail[]>>((acc, contactEmail) => { const { ContactID } = contactEmail; if (!acc[ContactID]) { acc[ContactID] = []; } (acc[ContactID] as ContactEmail[]).push(contactEmail); return acc; }, Object.create(null)); }, [contactEmails]); const contactGroupsMap = useMemo(() => toMap(contactGroups), [contactGroups]); const filteredContacts = useMemo(() => { if (!Array.isArray(contacts)) { return []; } return contacts.filter(({ Name, ID, LabelIDs }) => { const emails = contactEmailsMap[ID] ? (contactEmailsMap[ID] as ContactEmail[]).map(({ Email }) => Email).join(' ') : ''; const searchFilter = normalizedSearch.length ? normalize(`${Name} ${emails}`, true).includes(normalizedSearch) : true; const groupFilter = contactGroupID ? LabelIDs.includes(contactGroupID) : true; return searchFilter && groupFilter; }); }, [contacts, contactGroupID, normalizedSearch, contactEmailsMap]); const formattedContacts = useMemo<ContactFormatted[]>(() => { return filteredContacts.map((contact) => { const { ID } = contact; return { ...contact, emails: (contactEmailsMap[ID] || []).map(({ Email }) => Email), }; }); }, [filteredContacts, contactEmailsMap]); const contactIDs = useMemo(() => formattedContacts.map((contact) => contact.ID), [formattedContacts]); const { checkedIDs, selectedIDs, handleCheck, handleCheckAll, handleCheckOne, handleCheckOnlyOne, handleCheckRange, } = useItemsSelection(contactID, contactIDs, [contactID, contactGroupID]); const hasCheckedAllFiltered = useMemo(() => { const filteredContactsLength = filteredContacts.length; const checkedIDsLength = checkedIDs.length; return !!filteredContactsLength && checkedIDsLength === filteredContactsLength; }, [filteredContacts, checkedIDs]); const loading = loadingContacts || loadingContactEmails || loadingContactGroups; return { loading, checkedIDs, selectedIDs, handleCheck, handleCheckAll, handleCheckOne, handleCheckOnlyOne, handleCheckRange, contactEmailsMap, contactGroupName, contactGroupsMap, totalContactsInGroup, formattedContacts, filteredContacts, contacts, contactGroups, hasCheckedAllFiltered, }; }; export default useContactList;
6,048
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useContactMergeModals.tsx
import { useModalTwo } from '../../../components/modalTwo/useModalTwo'; import ContactMergeDetailsModal, { ContactMergeDetailsModalProps } from '../merge/ContactMergeDetailsModal'; import ContactMergeModal, { ContactMergeModalProps, ContactMergeProps } from '../merge/ContactMergeModal'; import ContactMergePreviewModal, { ContactMergePreviewModalProps } from '../merge/ContactMergePreviewModal'; export const useContactMergeModals = () => { const [contactMergeModal, handleShowContactMergeModal] = useModalTwo<ContactMergeModalProps, void>( ContactMergeModal, false ); const [contactMergePreviewModal, handleShowContactMergePreviewModal] = useModalTwo< ContactMergePreviewModalProps, void >(ContactMergePreviewModal, false); const [contactMergeDetailsModal, handleShowContactMergeDetailsModal] = useModalTwo< ContactMergeDetailsModalProps, void >(ContactMergeDetailsModal, false); const handleMergeDetails = (contactID: string) => { void handleShowContactMergeDetailsModal({ contactID }); }; const handleMergePreview = (props: ContactMergePreviewModalProps) => { void handleShowContactMergePreviewModal(props); }; const handleMerge = (props: ContactMergeProps) => { void handleShowContactMergeModal({ ...props, onMergeDetails: handleMergeDetails, onMergePreview: handleMergePreview, }); }; const modals = ( <> {contactMergeModal} {contactMergePreviewModal} {contactMergeDetailsModal} </> ); return { modals, onMerge: handleMerge, }; };
6,049
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useContactModals.tsx
import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import noop from '@proton/utils/noop'; import { useModalTwo } from '../../../components/modalTwo/useModalTwo'; import ContactEditModal, { ContactEditModalProps, ContactEditProps } from '../edit/ContactEditModal'; import ContactEmailSettingsModal, { ContactEmailSettingsProps } from '../email/ContactEmailSettingsModal'; import ContactGroupDeleteModal, { ContactGroupDeleteProps } from '../group/ContactGroupDeleteModal'; import ContactGroupDetailsModal, { ContactGroupDetailsProps } from '../group/ContactGroupDetailsModal'; import ContactGroupEditModal, { ContactGroupEditProps } from '../group/ContactGroupEditModal'; import ContactClearDataConfirmModal, { ContactClearDataConfirmModalProps, ContactClearDataConfirmProps, } from '../modals/ContactClearDataConfirmModal'; import ContactClearDataExecutionModal, { ContactClearDataExecutionProps, } from '../modals/ContactClearDataExecutionModal'; import ContactDecryptionErrorModal, { ContactDecryptionErrorModalProps, ContactDecryptionErrorProps, } from '../modals/ContactDecryptionErrorModal'; import ContactDeleteModal, { ContactDeleteProps } from '../modals/ContactDeleteModal'; import ContactExportingModal, { ContactExportingProps } from '../modals/ContactExportingModal'; import ContactGroupLimitReachedModal, { ContactGroupLimitReachedProps } from '../modals/ContactGroupLimitReachedModal'; import ContactImageModal, { ContactImageProps } from '../modals/ContactImageModal'; import ContactResignExecutionModal from '../modals/ContactResignExecutionModal'; import ContactSignatureErrorModal, { ContactSignatureErrorModalProps, ContactSignatureErrorProps, } from '../modals/ContactSignatureErrorModal'; import ContactUpgradeModal from '../modals/ContactUpgradeModal'; import SelectEmailsModal, { SelectEmailsProps } from '../modals/SelectEmailsModal'; import ContactDetailsModal, { ContactDetailsProps } from '../view/ContactDetailsModal'; interface Props { onMailTo?: (email: string) => void; onCompose?: (recipients: Recipient[], attachments: File[]) => void; onChange?: () => void; } export const useContactModals = ({ onMailTo = noop, onCompose, onChange }: Props = {}) => { const [contactDetailsModal, handleShowContactDetailsModal] = useModalTwo<ContactDetailsProps, void>( ContactDetailsModal, false ); const [contactEditModal, handleShowContactEditModal] = useModalTwo<ContactEditProps & ContactEditModalProps, void>( ContactEditModal, false ); const [contactDeleteModal, handleShowContactDeleteModal] = useModalTwo<ContactDeleteProps, void>( ContactDeleteModal, false ); const [contactEmailSettingsModal, handleShowContactEmailSettingsModal] = useModalTwo< ContactEmailSettingsProps, void >(ContactEmailSettingsModal, false); const [contactExportingModal, handleShowContactExportingModal] = useModalTwo<ContactExportingProps, void>( ContactExportingModal, false ); const [contactGroupDeleteModal, handleShowContactGroupDeleteModal] = useModalTwo<ContactGroupDeleteProps, void>( ContactGroupDeleteModal, false ); const [contactGroupEditModal, handleShowContactGroupEditModal] = useModalTwo<ContactGroupEditProps, void>( ContactGroupEditModal, false ); const [contactGroupDetailsModal, handleShowContactGroupDetailsModal] = useModalTwo<ContactGroupDetailsProps, void>( ContactGroupDetailsModal, false ); const [contactUpgradeModal, handleShowContactUpgradeModal] = useModalTwo<void, void>(ContactUpgradeModal, false); const [contactImageModal, handleShowContactImageModal] = useModalTwo<ContactImageProps, void>( ContactImageModal, false ); const [contactSignatureErrorModal, handleShowContactSignatureErrorModal] = useModalTwo< ContactSignatureErrorProps & ContactSignatureErrorModalProps, void >(ContactSignatureErrorModal, false); const [contactResignExecutionModal, handleShowContactResignExecutionModal] = useModalTwo<void, void>( ContactResignExecutionModal, false ); const [contactDecryptionErrorModal, handleShowContactDecryptionErrorModal] = useModalTwo< ContactDecryptionErrorProps & ContactDecryptionErrorModalProps, void >(ContactDecryptionErrorModal, false); const [contactClearDataConfirmModal, handleShowContactClearDataConfirmModal] = useModalTwo< ContactClearDataConfirmProps & ContactClearDataConfirmModalProps, void >(ContactClearDataConfirmModal, false); const [contactClearDataExecutionModal, handleShowContactClearDataExecutionModal] = useModalTwo< ContactClearDataExecutionProps, void >(ContactClearDataExecutionModal, false); const [contactSelectEmailsModal, handleShowContactSelectEmailsModal] = useModalTwo< SelectEmailsProps, ContactEmail[] >(SelectEmailsModal); const [contactGroupLimitReachedModal, handleShowContactGroupLimitReachedModal] = useModalTwo< ContactGroupLimitReachedProps, void >(ContactGroupLimitReachedModal, false); const handleUpgrade = () => { void handleShowContactUpgradeModal(); }; const handleSelectImage = (props: ContactImageProps) => { void handleShowContactImageModal(props); }; const handleResign = () => { void handleShowContactResignExecutionModal(); }; const handleSignatureError = (contactID: string) => { void handleShowContactSignatureErrorModal({ contactID, onResign: handleResign }); }; const handleClearData = (props: ContactClearDataExecutionProps) => { void handleShowContactClearDataExecutionModal(props); }; const handleClearDataConfirm = (props: ContactClearDataConfirmProps) => { void handleShowContactClearDataConfirmModal({ ...props, onClearData: handleClearData }); }; const handleDecryptionError = (contactID: string) => { void handleShowContactDecryptionErrorModal({ contactID, onClearDataConfirm: handleClearDataConfirm }); }; const handleGroupEdit = (props: ContactGroupEditProps) => { void handleShowContactGroupEditModal(props); }; const handleContactLimitReached = (props: ContactGroupLimitReachedProps) => { return handleShowContactGroupLimitReachedModal(props); }; const handleEdit = (props: ContactEditProps) => { void handleShowContactEditModal({ ...props, onChange, onUpgrade: handleUpgrade, onSelectImage: handleSelectImage, onGroupEdit: handleGroupEdit, onLimitReached: handleContactLimitReached, }); }; const handleDelete = (props: ContactDeleteProps) => { void handleShowContactDeleteModal({ ...props, onDelete: (...args) => { onChange?.(); props.onDelete?.(...args); }, }); }; const handleEmailSettings = (props: ContactEmailSettingsProps) => { void handleShowContactEmailSettingsModal(props); }; const handleExport = (props: ContactExportingProps = {}) => { void handleShowContactExportingModal(props); }; const handleGroupDelete = (props: ContactGroupDeleteProps) => { void handleShowContactGroupDeleteModal(props); }; const handleGroupDetails = (contactGroupID: string, onCloseContactDetailsModal?: () => void) => { void handleShowContactGroupDetailsModal({ contactGroupID, onEdit: handleGroupEdit, onDelete: handleGroupDelete, onExport: handleExport, onUpgrade: handleUpgrade, onCompose: onCompose, onCloseContactDetailsModal, // We want to close the contact details modal onCompose if we opened group details modal from contact details modal }); }; const handleDetails = (contactID: string) => { void handleShowContactDetailsModal({ contactID, onMailTo, onEdit: handleEdit, onDelete: handleDelete, onEmailSettings: handleEmailSettings, onGroupDetails: handleGroupDetails, onGroupEdit: handleGroupEdit, onUpgrade: handleUpgrade, onSignatureError: handleSignatureError, onDecryptionError: handleDecryptionError, }); }; const handleSelectEmails = (props: SelectEmailsProps) => { return handleShowContactSelectEmailsModal(props); }; const modals = ( <> {contactDetailsModal} {contactEditModal} {contactDeleteModal} {contactEmailSettingsModal} {contactExportingModal} {contactGroupDetailsModal} {contactGroupEditModal} {contactGroupDeleteModal} {contactUpgradeModal} {contactImageModal} {contactSignatureErrorModal} {contactResignExecutionModal} {contactDecryptionErrorModal} {contactClearDataConfirmModal} {contactClearDataExecutionModal} {contactSelectEmailsModal} {contactGroupLimitReachedModal} </> ); return { modals, onEdit: handleEdit, onDetails: handleDetails, onDelete: handleDelete, onEmailSettings: handleEmailSettings, onExport: handleExport, onGroupDetails: handleGroupDetails, onGroupEdit: handleGroupEdit, onGroupDelete: handleGroupDelete, onUpgrade: handleUpgrade, onSignatureError: handleSignatureError, onDecryptionError: handleDecryptionError, onSelectEmails: handleSelectEmails, onLimitReached: handleContactLimitReached, }; };
6,050
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useSaveVCardContact.tsx
import { useCallback } from 'react'; import { c } from 'ttag'; import { addContacts, updateContact } from '@proton/shared/lib/api/contacts'; import { API_CODES } from '@proton/shared/lib/constants'; import { CATEGORIES, OVERWRITE } from '@proton/shared/lib/contacts/constants'; import { prepareVCardContacts } from '@proton/shared/lib/contacts/encrypt'; import { DecryptedKey } from '@proton/shared/lib/interfaces'; import { Api } from '@proton/shared/lib/interfaces/Api'; import { AddContactsApiResponses, UpdateContactApiResponse } from '@proton/shared/lib/interfaces/contacts/ContactApi'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { useApi, useNotifications, useUserKeys } from '../../../hooks'; const { THROW_ERROR_IF_CONFLICT } = OVERWRITE; const { INCLUDE, IGNORE } = CATEGORIES; const { SINGLE_SUCCESS } = API_CODES; const handleContactRequest = async ( api: Api, contactID: string | undefined, vCardContact: VCardContact, userKeysList: DecryptedKey[] ) => { const Contacts = await prepareVCardContacts([vCardContact], userKeysList[0]); if (contactID) { const { Code } = await api<UpdateContactApiResponse>(updateContact(contactID, { Cards: Contacts[0].Cards })); return Code; } else { const labels = vCardContact.categories?.length ? INCLUDE : IGNORE; const { Responses: [{ Response: { Code = null } = {} }], } = await api<AddContactsApiResponses>( addContacts({ Contacts, Overwrite: THROW_ERROR_IF_CONFLICT, Labels: labels, }) ); return Code; } }; export const useSaveVCardContact = () => { const api = useApi(); const { createNotification } = useNotifications(); const [userKeysList, loadingUserKeys] = useUserKeys(); const saveVCardContact = useCallback( async (contactID: string | undefined, vCardContact: VCardContact) => { const code = await handleContactRequest(api, contactID, vCardContact, userKeysList); if (code !== SINGLE_SUCCESS) { createNotification({ text: c('Error').t`Contact could not be saved`, type: 'error' }); throw new Error('Contact could not be saved'); } }, [api, userKeysList, loadingUserKeys] ); return saveVCardContact; };
6,051
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useSenderImage.ts
import { useRef } from 'react'; import { useTheme } from '@proton/components'; import { useAuthentication, useConfig } from '@proton/components/hooks'; import { getImageSize, getSenderImageUrl } from '../helpers/senderImage'; /** * Return the sender image URL for a given email address * @param emailAddress email address to get the sender image for * @param bimiSelector * @returns the sender image URL */ const useSenderImage = (emailAddress: string, bimiSelector?: string) => { const theme = useTheme(); const imageSizeRef = useRef(getImageSize()); const mode = theme.information.dark ? 'dark' : 'light'; const { UID } = useAuthentication(); const { API_URL } = useConfig(); return emailAddress ? getSenderImageUrl(API_URL, UID, emailAddress, imageSizeRef.current, bimiSelector, mode) : ''; }; export default useSenderImage;
6,052
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useUpdateGroup.tsx
import { useCallback } from 'react'; import { c } from 'ttag'; import { addContacts, labelContactEmails, unLabelContactEmails } from '@proton/shared/lib/api/contacts'; import { createContactGroup, updateLabel } from '@proton/shared/lib/api/labels'; import { CATEGORIES, OVERWRITE } from '@proton/shared/lib/contacts/constants'; import { prepareVCardContacts } from '@proton/shared/lib/contacts/encrypt'; import { createContactPropertyUid } from '@proton/shared/lib/contacts/properties'; import { Label } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { useApi, useEventManager, useNotifications, useUserKeys } from '../../../hooks'; export type UpdateGroupOptions = { groupID: string | undefined; name: string; color: string; toAdd: ContactEmail[]; toRemove: ContactEmail[]; toCreate: ContactEmail[]; onDelayedSave?: (groupID: string) => void; }; const useUpdateGroup = () => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [userKeysList] = useUserKeys(); return useCallback( async ({ groupID, name, color, toAdd, toRemove, toCreate, onDelayedSave }: UpdateGroupOptions) => { // Update contact group const contactGroupParams = { Name: name, Color: color }; const { Label: { ID: LabelID }, } = await api<{ Label: Label }>( groupID ? updateLabel(groupID, contactGroupParams) : createContactGroup(contactGroupParams) ); if (onDelayedSave) { onDelayedSave(LabelID); } // Create new contacts if (toCreate.length) { const vCardContacts = toCreate.map(({ Email }) => ({ fn: [{ field: 'fn', value: Email, uid: createContactPropertyUid() }], email: [{ field: 'email', value: Email, group: 'item1', uid: createContactPropertyUid() }], categories: [{ field: 'categories', value: name, group: 'item1', uid: createContactPropertyUid() }], })); const Contacts = await prepareVCardContacts(vCardContacts, userKeysList[0]); await api( addContacts({ Contacts, Overwrite: OVERWRITE.THROW_ERROR_IF_CONFLICT, Labels: CATEGORIES.INCLUDE, }) ); } // Label and unlabel existing contact emails await Promise.all( [ toAdd.length && api(labelContactEmails({ LabelID, ContactEmailIDs: toAdd.map(({ ID }) => ID) })), toRemove.length && api(unLabelContactEmails({ LabelID, ContactEmailIDs: toRemove.map(({ ID }) => ID) })), ].filter(Boolean) ); await call(); createNotification({ text: groupID ? c('Notification').t`Contact group updated` : c('Notification').t`Contact group created`, }); }, [] ); }; export default useUpdateGroup;
6,053
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/hooks/useVCardContact.tsx
import { useEffect, useRef, useState } from 'react'; import { CryptoProcessingError, prepareVCardContact } from '@proton/shared/lib/contacts/decrypt'; import { DecryptedKey } from '@proton/shared/lib/interfaces'; import { Contact } from '@proton/shared/lib/interfaces/contacts/Contact'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { splitKeys } from '@proton/shared/lib/keys'; export type VCardContactModel = { ID?: string; vCardContact?: VCardContact; errors?: (CryptoProcessingError | Error)[]; isVerified?: boolean; }; interface Props { contact: Contact; userKeysList: DecryptedKey[]; } const useVCardContact = ({ contact, userKeysList, }: Props): VCardContactModel & { isLoading: boolean; onReload: () => void } => { const ref = useRef(''); const [model, setModel] = useState<VCardContactModel>(); const [forceRefresh, setForceRefresh] = useState({}); useEffect(() => { if (contact && userKeysList.length) { const prepare = async () => { ref.current = contact.ID; const { publicKeys, privateKeys } = splitKeys(userKeysList); const { vCardContact, errors, isVerified } = await prepareVCardContact(contact, { publicKeys, privateKeys, }); if (ref.current !== contact.ID) { return; } setModel({ ID: contact.ID, vCardContact, errors, isVerified }); }; void prepare(); } }, [contact, userKeysList, forceRefresh]); const handleForceRefresh = () => { setModel({}); setForceRefresh({}); }; const isLoading = !model?.ID; return { ...model, isLoading, onReload: handleForceRefresh }; }; export default useVCardContact;
6,054
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/ContactImportModal.test.tsx
import { fireEvent, waitFor } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import { API_CODES } from '@proton/shared/lib/constants'; import range from '@proton/utils/range'; import { api, clearAll, getCard, mockedCryptoApi, render } from '../tests/render'; import ContactImportModal from './ContactImportModal'; jest.mock('../../../hooks/useFeature', () => () => ({ feature: {}, update: jest.fn() })); describe('ContactImportModal', () => { beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should succeed to import a simple CSV file', async () => { const csv = `first name,last name,email-address ,nickname,organization,birthday,home phone,work phone,mobile phone,city,state,zip,country,Job title,personal web page,business website,group membership,Timezone,notes,home John,Smith,johnsmith@protonmail.com,,Smith Inc.,,123-456-789,,,New Orleans,LA,94958,USA,Head honcho,,,,GMT-7,, Jane,Doe,jane@example.com,,Example UK,,,(44)12345678,(44)12345678,Brighton,East Sussex,BR7 7HT,UK,,www.customdomain.com,,Brighton kite Flyers,GMT,Likes to party!, Peter,Rabbit,peter@pm.me,Carrot,,03/12/1969,856-264-4130,123-456-789,123-456-789,Bridgeport,NJ,8014,USA,,,www.customdomain.com,,GMT-4,, Botman,,botman@pm.me,,,,,,,Skopje,,,,,,,,,,Partizanska`; const file = new File([csv], 'test.csv', { type: 'text/csv' }); const saveRequestSpy = jest.fn(); const Responses = range(0, 4).map((i) => ({ Index: 0, Response: { Code: API_CODES.SINGLE_SUCCESS, Contact: { ID: `ContactID${i}`, ContactEmails: [] } }, })); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts') { saveRequestSpy(args.data); return { Responses }; } }); const { getByText } = render(<ContactImportModal open={true} />); const input = document.querySelector('input[type="file"]') as HTMLInputElement; fireEvent.change(input, { target: { files: [file] } }); let importButton = getByText('Import', { selector: 'button' }); fireEvent.click(importButton); await waitFor(() => getByText('We have detected', { exact: false })); importButton = getByText('Import', { selector: 'button' }); fireEvent.click(importButton); await waitFor(() => getByText('4/4', { exact: false })); const sentData = saveRequestSpy.mock.calls[0][0]; const contact0Cards = sentData.Contacts[0].Cards; const signed0 = getCard(contact0Cards, false); expect(signed0).toContain('FN;PREF=1:John Smith'); expect(signed0).toContain('ITEM1.EMAIL;TYPE=;PREF=1:johnsmith@protonmail.com'); const encrypted0 = getCard(contact0Cards, true); expect(encrypted0).toContain('ADR;TYPE=;PREF=1:;;;New Orleans;LA;94958;USA'); expect(encrypted0).toContain('ORG:Smith Inc.'); expect(encrypted0).toContain('TEL;TYPE=home;PREF=1:123-456-789'); expect(encrypted0).toContain('TITLE:Head honcho'); expect(encrypted0).toContain('TZ:GMT-7'); const contact1Cards = sentData.Contacts[1].Cards; const signed1 = getCard(contact1Cards, false); expect(signed1).toContain('FN;PREF=1:Jane Doe'); expect(signed1).toContain('ITEM1.EMAIL;TYPE=;PREF=1:jane@example.com'); const encrypted1 = getCard(contact1Cards, true); expect(encrypted1).toContain('ADR;TYPE=;PREF=1:;;;Brighton;East Sussex;BR7 7HT;UK'); expect(encrypted1).toContain('NOTE:Likes to party!'); expect(encrypted1).toContain('ORG:Example UK'); expect(encrypted1).toContain('TEL;TYPE=work;PREF=1:(44)12345678'); expect(encrypted1).toContain('TEL;TYPE=cell;PREF=2:(44)12345678'); expect(encrypted1).toContain('URL:www.customdomain.com'); expect(encrypted1).toContain('TZ:GMT'); const contact2Cards = sentData.Contacts[2].Cards; const signed2 = getCard(contact2Cards, false); expect(signed2).toContain('FN;PREF=1:Peter Rabbit'); expect(signed2).toContain('ITEM1.EMAIL;TYPE=;PREF=1:peter@pm.me'); const encrypted2 = getCard(contact2Cards, true); expect(encrypted2).toContain('ADR;TYPE=;PREF=1:;;;Bridgeport;NJ;8014;USA'); expect(encrypted2).toContain('NOTE:nickname: Carrot'); expect(encrypted2).toContain('BDAY:19690312'); expect(encrypted2).toContain('TEL;TYPE=home;PREF=1:856-264-4130'); expect(encrypted2).toContain('TEL;TYPE=work;PREF=2:123-456-789'); expect(encrypted2).toContain('TEL;TYPE=cell;PREF=3:123-456-789'); expect(encrypted2).toContain('URL:www.customdomain.com'); expect(encrypted2).toContain('TZ:GMT-4'); const contact3Cards = sentData.Contacts[3].Cards; const signed3 = getCard(contact3Cards, false); expect(signed3).toContain('FN;PREF=1:Botman'); expect(signed3).toContain('ITEM1.EMAIL;TYPE=;PREF=1:botman@pm.me'); const encrypted3 = getCard(contact3Cards, true); expect(encrypted3).toContain('ADR;TYPE=;PREF=1:;;;Skopje;;;'); expect(encrypted3).toContain('NOTE:home: Partizanska'); }); });
6,055
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/ContactImportModal.tsx
import { useState } from 'react'; import { IMPORT_STEPS, ImportContactsModel } from '@proton/shared/lib/interfaces/contacts/Import'; import { ModalProps, ModalTwo } from '../../../components'; import ContactImportAttaching from './steps/ContactImportAttaching'; import ContactImportCsv from './steps/ContactImportCsv'; import ContactImportGroups from './steps/ContactImportGroups'; import ContactImportSummary from './steps/ContactImportSummary'; import ContactImportWarning from './steps/ContactImportWarning'; import ContactImporting from './steps/ContactImporting'; export const getInitialState = (): ImportContactsModel => ({ step: IMPORT_STEPS.ATTACHING, parsedVcardContacts: [], importedContacts: [], totalEncrypted: 0, totalImported: 0, errors: [], categories: [], loading: false, }); interface Props extends ModalProps {} const ContactImportModal = ({ ...rest }: Props) => { const [model, setModel] = useState<ImportContactsModel>(getInitialState()); let ModalContent; if (model.step <= IMPORT_STEPS.ATTACHED) { ModalContent = ContactImportAttaching; } else if (model.step === IMPORT_STEPS.IMPORT_CSV) { ModalContent = ContactImportCsv; } else if (model.step <= IMPORT_STEPS.WARNING) { ModalContent = ContactImportWarning; } else if (model.step === IMPORT_STEPS.IMPORTING) { ModalContent = ContactImporting; } else if (model.step === IMPORT_STEPS.SUMMARY) { ModalContent = ContactImportSummary; } else { ModalContent = ContactImportGroups; } return ( <ModalTwo size="large" className="contacts-modal" {...rest}> <ModalContent model={model} setModel={setModel} onClose={rest.onClose} /> </ModalTwo> ); }; export default ContactImportModal;
6,056
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/encryptAndSubmit.ts
import { addContacts, labelContactEmails, labelContacts } from '@proton/shared/lib/api/contacts'; import { processApiRequestsSafe } from '@proton/shared/lib/api/helpers/safeApiRequests'; import { createContactGroup } from '@proton/shared/lib/api/labels'; import { getRandomAccentColor } from '@proton/shared/lib/colors'; import { API_CODES, HOUR } from '@proton/shared/lib/constants'; import { CATEGORIES, OVERWRITE } from '@proton/shared/lib/contacts/constants'; import { prepareVCardContact } from '@proton/shared/lib/contacts/encrypt'; import { IMPORT_CONTACT_ERROR_TYPE, ImportContactError } from '@proton/shared/lib/contacts/errors/ImportContactError'; import { extractContactImportCategories, getContactId, splitErrors } from '@proton/shared/lib/contacts/helpers/import'; import { getContactCategories, getContactEmails } from '@proton/shared/lib/contacts/properties'; import { prepareForSaving } from '@proton/shared/lib/contacts/surgery'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Api, KeyPair, Label, SimpleMap } from '@proton/shared/lib/interfaces'; import { IMPORT_GROUPS_ACTION, ImportCategories, ImportedContact } from '@proton/shared/lib/interfaces/contacts'; import { AddContactsApiResponse, AddContactsApiResponses } from '@proton/shared/lib/interfaces/contacts/ContactApi'; import { EncryptedContact, ImportContactsModel } from '@proton/shared/lib/interfaces/contacts/Import'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import chunk from '@proton/utils/chunk'; import noop from '@proton/utils/noop'; import uniqueBy from '@proton/utils/uniqueBy'; const { SINGLE_SUCCESS } = API_CODES; const BATCH_SIZE = 10; const encryptContact = async (contact: VCardContact, { privateKey, publicKey }: KeyPair) => { try { const prepared = prepareForSaving(contact); const contactEncrypted = await prepareVCardContact(prepared, { privateKey, publicKey }); return { contact: contactEncrypted, contactId: getContactId(prepared), contactEmails: getContactEmails(prepared), categories: getContactCategories(prepared), }; } catch (error: any) { const contactId = getContactId(contact); return new ImportContactError(IMPORT_CONTACT_ERROR_TYPE.ENCRYPTION_ERROR, contactId); } }; const submitContacts = async ({ contacts, labels, overwrite, api, isImport, }: { contacts: EncryptedContact[]; labels: CATEGORIES; overwrite: OVERWRITE; api: Api; isImport?: boolean; }) => { // submit the data let responses: AddContactsApiResponse[] = []; try { const { Responses } = await api<AddContactsApiResponses>({ ...addContacts({ Contacts: contacts.map(({ contact }) => contact), Overwrite: overwrite, Labels: labels, Import: isImport ? 1 : 0, }), timeout: HOUR, silence: true, }); responses = Responses; } catch (error: any) { const { Code = 0, Error = `${error}` } = error.data || {}; responses = contacts.map((contact, index) => ({ Index: index, Response: { Code, Error }, })); } return responses.map((response) => { const { Index, Response: { Error: errorMessage, Code, Contact }, } = response; if (Code !== SINGLE_SUCCESS || !Contact) { const error = new Error(errorMessage); const { contactId } = contacts[Index]; return new ImportContactError(IMPORT_CONTACT_ERROR_TYPE.EXTERNAL_ERROR, contactId, error); } const contact = contacts[Index]; return { contactID: Contact.ID, contactEmailIDs: Contact.ContactEmails.map((contactEmail) => contactEmail.ID), categories: extractContactImportCategories(Contact, contact), }; }); }; interface ProcessData { contacts: VCardContact[]; labels: CATEGORIES; overwrite: OVERWRITE; keyPair: KeyPair; api: Api; signal: AbortSignal; isImport?: boolean; onProgress: (encrypted: EncryptedContact[], imported: ImportedContact[], errors: ImportContactError[]) => void; } export const processContactsInBatches = async ({ contacts, labels, overwrite, keyPair, api, signal, isImport, onProgress, }: ProcessData) => { const batches = chunk(contacts, BATCH_SIZE); const promises = []; const imported: ImportedContact[][] = []; for (let i = 0; i < batches.length; i++) { // The API requests limit for the submit route are 100 calls per 10 seconds // We play it safe by enforcing a 100ms minimum wait between API calls. During this wait we encrypt the contacts if (signal.aborted) { return []; } const batchedContacts = batches[i]; const [result] = await Promise.all([ Promise.all(batchedContacts.map((contacts) => encryptContact(contacts, keyPair))), wait(100), ]); const { errors, rest: encrypted } = splitErrors(result); if (signal.aborted) { return []; } onProgress(encrypted, [], errors); if (encrypted.length) { const promise = submitContacts({ contacts: encrypted, labels, overwrite, isImport, api }).then( (result: (ImportedContact | ImportContactError)[]) => { const { errors, rest: importedSuccess } = splitErrors(result); imported.push(importedSuccess); onProgress([], importedSuccess, errors); } ); promises.push(promise); } } await Promise.all(promises); return imported.flat(); }; export const submitCategories = async (categories: ImportCategories[], api: Api) => { // First create new contact groups if needed. Store label IDs in a map const newCategories = uniqueBy( categories.filter(({ action }) => action === IMPORT_GROUPS_ACTION.CREATE), ({ targetName }) => targetName ); const newLabelIDsMap: SimpleMap<string> = {}; const createRequests = newCategories.map(({ targetName }) => { return async () => { try { const { Label: { ID }, } = await api<{ Label: Label }>( createContactGroup({ Name: targetName, Color: getRandomAccentColor(), }) ); newLabelIDsMap[targetName] = ID; } catch (e: any) { // let the process continue, but an error growler will be displayed noop(); } }; }); // the routes called in requests do not have any specific jail limit // the limit per user session is 25k requests / 900s await processApiRequestsSafe(createRequests, 1000, 100 * 1000); // label contacts const labelRequests: (() => Promise<any>)[] = []; categories.forEach(({ action, targetGroup, targetName, contactEmailIDs, contactIDs }) => { if (action === IMPORT_GROUPS_ACTION.IGNORE) { return; } if (action === IMPORT_GROUPS_ACTION.MERGE) { const labelID = targetGroup.ID; if (contactEmailIDs.length) { labelRequests.push(() => api(labelContactEmails({ LabelID: labelID, ContactEmailIDs: contactEmailIDs })).catch(noop) ); } if (contactIDs.length) { labelRequests.push(() => api(labelContacts({ LabelID: labelID, ContactIDs: contactIDs })).catch(noop)); } return; } if (action === IMPORT_GROUPS_ACTION.CREATE) { const labelID = newLabelIDsMap[targetName]; if (labelID && contactEmailIDs.length) { labelRequests.push(() => api(labelContactEmails({ LabelID: labelID, ContactEmailIDs: contactEmailIDs })).catch(noop) ); } if (labelID && contactIDs.length) { labelRequests.push(() => api(labelContacts({ LabelID: labelID, ContactIDs: contactIDs })).catch(noop)); } } }); // the routes called in requests do not have any specific jail limit // the limit per user session is 25k requests / 900s return processApiRequestsSafe(labelRequests, 1000, 100 * 1000); }; export const extractTotals = (model: ImportContactsModel) => { const { parsedVcardContacts, totalEncrypted, totalImported, errors } = model; const totalToImport = parsedVcardContacts.length; const totalToProcess = 2 * totalToImport; // count encryption and submission equivalently for the progress const totalErrors = errors.length; const totalProcessed = totalEncrypted + totalImported + totalErrors; return { totalToImport, totalToProcess, totalImported, totalProcessed }; };
6,057
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportAttaching.tsx
import { ChangeEvent, Dispatch, FormEvent, SetStateAction } from 'react'; import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { Alert, AttachedFile, Dropzone, FileInput, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, SettingsLink, } from '@proton/components'; import { APPS } from '@proton/shared/lib/constants'; import { MAX_CONTACTS_PER_USER, MAX_IMPORT_CONTACTS_STRING, MAX_IMPORT_FILE_SIZE, MAX_IMPORT_FILE_SIZE_STRING, } from '@proton/shared/lib/contacts/constants'; import { ImportFatalError } from '@proton/shared/lib/contacts/errors/ImportFatalError'; import { IMPORT_ERROR_TYPE, ImportFileError } from '@proton/shared/lib/contacts/errors/ImportFileError'; import { prepare, readCsv } from '@proton/shared/lib/contacts/helpers/csv'; import { getIsAcceptedExtension, getSupportedContacts, splitErrors } from '@proton/shared/lib/contacts/helpers/import'; import { extractVcards, readVcf } from '@proton/shared/lib/contacts/vcard'; import { splitExtension } from '@proton/shared/lib/helpers/file'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { EXTENSION, IMPORT_STEPS, ImportContactsModel } from '@proton/shared/lib/interfaces/contacts/Import'; import { useFeature } from '../../../../hooks'; import { FeatureCode } from '../../../features'; import { getInitialState } from '../ContactImportModal'; const { CSV, VCF } = EXTENSION; interface Props { model: ImportContactsModel; setModel: Dispatch<SetStateAction<ImportContactsModel>>; onClose?: () => void; } const ContactImportAttaching = ({ model, setModel, onClose }: Props) => { const { feature: featureUsedContactsImport, update: updateUsedContactsImport } = useFeature( FeatureCode.UsedContactsImport ); const handleClear = () => { setModel(getInitialState()); }; const handleFiles = (files: File[]) => { const [fileAttached] = files; const filename = fileAttached.name; const [, ext] = splitExtension(filename); const extension = ext.toLowerCase(); if (!fileAttached.size) { throw new ImportFileError(IMPORT_ERROR_TYPE.FILE_EMPTY, filename); } if (!getIsAcceptedExtension(extension) || !fileAttached) { throw new ImportFileError(IMPORT_ERROR_TYPE.NO_CSV_OR_VCF_FILE, filename); } if (fileAttached.size > MAX_IMPORT_FILE_SIZE) { throw new ImportFileError(IMPORT_ERROR_TYPE.FILE_TOO_BIG, filename); } setModel({ ...model, step: IMPORT_STEPS.ATTACHED, fileAttached, extension, failure: undefined }); }; const onAddFiles = (files: File[]) => { try { if (!files) { throw new ImportFileError(IMPORT_ERROR_TYPE.NO_FILE_SELECTED); } handleFiles(files); } catch (e: any) { setModel({ ...model, failure: e }); } }; const handleAttach = ({ target }: ChangeEvent<HTMLInputElement>) => { try { if (!target.files) { throw new ImportFileError(IMPORT_ERROR_TYPE.NO_FILE_SELECTED); } handleFiles([...target.files]); } catch (e: any) { setModel({ ...model, failure: e }); } }; const handleSubmit = async (event: FormEvent) => { event.preventDefault(); event.stopPropagation(); const { fileAttached, extension } = model; if (!fileAttached) { throw new Error('No file'); } try { setModel({ ...model, loading: true }); if (extension === CSV) { const parsedCsvContacts = await readCsv(fileAttached); const preVcardsContacts = prepare(parsedCsvContacts); if (!preVcardsContacts.length) { throw new ImportFileError(IMPORT_ERROR_TYPE.NO_CONTACTS, fileAttached.name); } if (preVcardsContacts.length > MAX_CONTACTS_PER_USER) { throw new ImportFileError(IMPORT_ERROR_TYPE.TOO_MANY_CONTACTS, fileAttached.name); } setModel({ ...model, step: IMPORT_STEPS.IMPORT_CSV, preVcardsContacts, failure: undefined, loading: false, }); } else if (extension === VCF) { const vcards = extractVcards(await readVcf(fileAttached)); if (vcards.length > MAX_CONTACTS_PER_USER) { throw new ImportFileError(IMPORT_ERROR_TYPE.TOO_MANY_CONTACTS, fileAttached.name); } const { errors, rest: parsedVcardContacts } = splitErrors(getSupportedContacts(vcards)); const step = errors.length || !parsedVcardContacts.length ? IMPORT_STEPS.WARNING : IMPORT_STEPS.IMPORTING; setModel({ ...model, step, parsedVcardContacts, errors, failure: undefined, loading: false, }); } else { throw new ImportFileError(IMPORT_ERROR_TYPE.NO_CSV_OR_VCF_FILE); } if (featureUsedContactsImport?.Value === false) { void updateUsedContactsImport(true); } } catch (e: any) { const failure = e instanceof ImportFileError ? e : new ImportFatalError(e); setModel({ ...getInitialState(), failure, }); } }; const easySwitchLink = ( <SettingsLink app={APPS.PROTONMAIL} path="/easy-switch" target="_blank">{c('description') .t`use the Easy Switch import assistant`}</SettingsLink> ); const learnMoreLink = <Href href={getKnowledgeBaseUrl('/adding-contacts')}>{c('Link').t`Learn more`}</Href>; return ( <form className="modal-two-dialog-container h-full" onSubmit={handleSubmit}> <ModalTwoHeader title={c('Title').t`Import contacts`} /> <ModalTwoContent> {model.failure ? ( <Alert className="mb-4" type="error"> {model.failure?.message} </Alert> ) : ( <> <p className="mb-2">{c('Description') .jt`To import your contacts from Google or Outlook, ${easySwitchLink}.`}</p> <p className="mt-0">{c('Description') .jt`For import via CSV and VCF file, ensure the file does not exceed ${MAX_IMPORT_FILE_SIZE_STRING} or ${MAX_IMPORT_CONTACTS_STRING} contacts. If your file is bigger, please split it into smaller files. ${learnMoreLink}.`}</p> </> )} <Dropzone onDrop={onAddFiles} size="small" shape="flashy"> <div className="flex flex-align-items-center flex-justify-center border p-4 rounded-xl"> {model.fileAttached ? ( <AttachedFile file={model.fileAttached} iconName="users" clear={c('Action').t`Delete`} onClear={handleClear} /> ) : ( <FileInput accept=".csv, .vcf" id="import-contacts" onChange={handleAttach}> {c('Action').t`Choose a file or drag it here`} </FileInput> )} </div> </Dropzone> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" disabled={model.step === IMPORT_STEPS.ATTACHING} loading={model.loading} type="submit" > {c('Action').t`Import`} </Button> </ModalTwoFooter> </form> ); }; export default ContactImportAttaching;
6,058
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportCsv.tsx
import { Dispatch, FormEvent, SetStateAction, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ImportFatalError } from '@proton/shared/lib/contacts/errors/ImportFatalError'; import { toVCardContacts } from '@proton/shared/lib/contacts/helpers/csv'; import { getHasPreVcardsContacts } from '@proton/shared/lib/contacts/helpers/import'; import { modifyContactField, modifyContactType, toggleContactChecked, } from '@proton/shared/lib/contacts/helpers/importCsv'; import { IMPORT_STEPS, ImportContactsModel } from '@proton/shared/lib/interfaces/contacts/Import'; import { Alert, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Table } from '../../../../components'; import { useNotifications } from '../../../../hooks'; import ContactImportCsvTableBody from './ContactImportCsvTableBody'; import ContactImportCsvTableHeader from './ContactImportCsvTableHeader'; interface Props { model: ImportContactsModel; setModel: Dispatch<SetStateAction<ImportContactsModel>>; onClose?: () => void; } const ImportCsvModalContent = ({ model, setModel, onClose }: Props) => { const { createNotification } = useNotifications(); const [contactIndex, setContactIndex] = useState(0); if (!getHasPreVcardsContacts(model)) { throw new ImportFatalError(new Error('No CSV contacts found')); } const { preVcardsContacts } = model; const handleClickPrevious = () => setContactIndex((index) => index - 1); const handleClickNext = () => setContactIndex((index) => index + 1); const handleToggle = (groupIndex: number) => (index: number) => { if (preVcardsContacts[0][groupIndex][index].combineInto === 'fn-main') { // do not allow to uncheck first name and last name simultaneously const preVcards = preVcardsContacts[0][groupIndex]; const firstNameIndex = preVcards.findIndex(({ header }) => header.toLowerCase() === 'first name'); const lastNameIndex = preVcards.findIndex(({ header }) => header.toLowerCase() === 'last name'); const isFirstNameChecked = firstNameIndex !== -1 && preVcards[firstNameIndex].checked; const isLastNameChecked = lastNameIndex !== -1 && preVcards[lastNameIndex].checked; if ((!isFirstNameChecked && index === lastNameIndex) || (!isLastNameChecked && index === firstNameIndex)) { return createNotification({ type: 'error', text: c('Error notification').t`First name and last name cannot be unchecked at the same time`, }); } } setModel({ ...model, preVcardsContacts: preVcardsContacts.map((contact) => toggleContactChecked(contact, [groupIndex, index])), }); }; const handleChangeField = (groupIndex: number) => (newField: string) => setModel({ ...model, preVcardsContacts: preVcardsContacts.map((contact) => modifyContactField(contact, groupIndex, newField)), }); const handleChangeType = (groupIndex: number) => (newType: string) => setModel({ ...model, preVcardsContacts: preVcardsContacts.map((contact) => modifyContactType(contact, groupIndex, newType)), }); const handleSubmit = (event: FormEvent) => { event.preventDefault(); event.stopPropagation(); const { errors, rest: parsedVcardContacts } = toVCardContacts(model.preVcardsContacts || []); setModel({ ...model, step: IMPORT_STEPS.IMPORTING, parsedVcardContacts, errors, }); }; return ( <form className="modal-two-dialog-container h-full" onSubmit={handleSubmit}> <ModalTwoHeader title={c('Title').t`Import contacts`} /> <ModalTwoContent> <Alert className="mb-4"> {c('Description of the purpose of the import CSV modal') .t`We have detected the following fields in the CSV file you uploaded. Check the ones you want to import.`} </Alert> <Alert className="mb-4"> {c('Description of the purpose of the import CSV modal') .t`Also, we have automatically matched CSV fields with vCard fields. You can review and change this matching manually.`} </Alert> <Table> <ContactImportCsvTableHeader disabledPrevious={contactIndex === 0} disabledNext={preVcardsContacts.length === 0 || contactIndex + 1 === preVcardsContacts.length} onNext={handleClickNext} onPrevious={handleClickPrevious} /> <ContactImportCsvTableBody contact={preVcardsContacts && preVcardsContacts[contactIndex]} onToggle={handleToggle} onChangeField={handleChangeField} onChangeType={handleChangeType} /> </Table> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" disabled={!model.preVcardsContacts?.length} type="submit"> {c('Action').t`Import`} </Button> </ModalTwoFooter> </form> ); }; export default ImportCsvModalContent;
6,059
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportCsvSelectField.tsx
import { getAllFields } from '@proton/shared/lib/helpers/contacts'; import { Label, Option, SelectTwo } from '../../../../components'; import { SelectChangeEvent } from '../../../../components/selectTwo/select'; interface Props { value?: string; disabled?: boolean; avoidFiltering?: boolean; onChangeField?: (field: string) => void; } const ContactImportCsvSelectField = ({ value = '', disabled, avoidFiltering, onChangeField }: Props) => { const fields = getAllFields(); const filteredFields = fields.filter(({ value }) => { return value !== 'firstName' && value !== 'lastName'; }); const handleChangeField = ({ value }: SelectChangeEvent<string>) => { if (value === 'firstName' || value === 'lastName') { onChangeField?.('n'); } else { onChangeField?.(value); } }; return ( <Label className="pt-0"> <SelectTwo value={value} onChange={handleChangeField} disabled={disabled}> {(avoidFiltering ? fields : filteredFields).map((field) => ( <Option key={field.value} title={field.text} value={field.value} /> ))} </SelectTwo> </Label> ); }; export default ContactImportCsvSelectField;
6,060
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportCsvSelectType.tsx
import { getAllTypes } from '@proton/shared/lib/helpers/contacts'; import { Label, Option, SelectTwo } from '../../../../components'; import { SelectChangeEvent } from '../../../../components/selectTwo/select'; interface Props { field?: string; value: string; onChangeType: (type: string) => void; } const ContactImportCsvSelectType = ({ field = '', value, onChangeType }: Props) => { const types = getAllTypes(); const handleChangeType = ({ value }: SelectChangeEvent<string>) => onChangeType(value); return ( <Label className="pt-0"> <SelectTwo value={value} onChange={handleChangeType}> {types[field as keyof typeof types].map((type) => ( <Option key={type.value} title={type.text} value={type.value} /> ))} </SelectTwo> </Label> ); }; export default ContactImportCsvSelectType;
6,061
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportCsvTableBody.tsx
import { PreVcardsContact } from '@proton/shared/lib/interfaces/contacts/Import'; import ContactImportCsvTableRows from './ContactImportCsvTableRows'; interface Props { contact?: PreVcardsContact; onToggle: (groupIndex: number) => (index: number) => void; onChangeField: (groupIndex: number) => (field: string) => void; onChangeType: (groupIndex: number) => (type: string) => void; } const ContactImportCsvTableBody = ({ contact, onToggle, onChangeField, onChangeType }: Props) => { return ( <tbody> {contact && contact.map((preVcards, i) => ( <ContactImportCsvTableRows key={`${preVcards[0].header}${i.toString()}`} preVcards={preVcards} onToggle={onToggle(i)} onChangeField={onChangeField(i)} onChangeType={onChangeType(i)} /> ))} </tbody> ); }; export default ContactImportCsvTableBody;
6,062
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportCsvTableHeader.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon, TableCell } from '../../../../components'; interface Props { disabledPrevious: boolean; disabledNext: boolean; onPrevious: () => void; onNext: () => void; } const ContactImportCsvTableHeader = ({ disabledPrevious = true, disabledNext = true, onPrevious, onNext, ...rest }: Props) => { return ( <thead {...rest}> <tr> <TableCell type="header" className="w-1/6 text-center"> {c('TableHeader').t`Import`} </TableCell> <TableCell type="header" className="text-center">{c('TableHeader').t`CSV field`}</TableCell> <TableCell type="header" className="text-center">{c('TableHeader').t`vCard field`}</TableCell> <TableCell type="header" className="w-3/10 text-center"> <div className="inline-flex"> <span className="flex-item-centered-vert mr-2">{c('TableHeader').t`Values`}</span> <span className="flex flex-nowrap"> <Button icon disabled={disabledPrevious} onClick={onPrevious}> <Icon name="chevron-left" className="flex-item-noshrink" /> </Button> <Button icon disabled={disabledNext} onClick={onNext}> <Icon name="chevron-right" className="flex-item-noshrink" /> </Button> </span> </div> </TableCell> </tr> </thead> ); }; export default ContactImportCsvTableHeader;
6,063
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportCsvTableRows.tsx
import { toVCard } from '@proton/shared/lib/contacts/helpers/csv'; import { display as getDisplay } from '@proton/shared/lib/contacts/helpers/csvFormat'; import { PreVcardsProperty } from '@proton/shared/lib/interfaces/contacts/Import'; import { Checkbox } from '../../../../components'; import ContactImportCsvSelectField from './ContactImportCsvSelectField'; import ContactImportCsvSelectType from './ContactImportCsvSelectType'; import ContactImportCsvTableRowsNField from './ContactImportCsvTableRowsNField'; interface Props { preVcards: PreVcardsProperty; onToggle: (index: number) => void; onChangeField: (field: string) => void; onChangeType: (type: string) => void; } const ContactImportCsvTableRows = ({ preVcards, onToggle, onChangeField, onChangeType }: Props) => { const { field, params } = toVCard(preVcards) || {}; const display = preVcards[0]?.custom ? getDisplay.custom(preVcards) : getDisplay[field as string](preVcards); if (field === 'categories') { // Do not display CATEGORIES vcard fields since they cannot be edited from the contact modal return null; } return ( <> {field === 'n' ? ( <ContactImportCsvTableRowsNField preVcards={preVcards} onToggle={onToggle} /> ) : ( preVcards.map(({ checked, header }, i) => ( // eslint-disable-next-line react/no-array-index-key <tr key={i}> <td className="text-center"> <Checkbox checked={checked} onChange={() => onToggle(i)} /> </td> <td>{header}</td> {i === 0 ? ( <> <td rowSpan={preVcards.length}> <div className="flex"> <ContactImportCsvSelectField value={field} onChangeField={onChangeField} /> {params?.type !== undefined ? ( <ContactImportCsvSelectType field={field} value={params.type} onChangeType={onChangeType} /> ) : null} </div> </td> <td rowSpan={preVcards.length} className="text-ellipsis" title={display}> {display} </td> </> ) : null} </tr> )) )} </> ); }; export default ContactImportCsvTableRows;
6,064
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportCsvTableRowsNField.tsx
import { ContactValue } from '@proton/shared/lib/interfaces/contacts'; import { PreVcardsProperty } from '@proton/shared/lib/interfaces/contacts/Import'; import { Checkbox } from '../../../../components'; import ContactImportCsvSelectField from './ContactImportCsvSelectField'; interface Props { preVcards: PreVcardsProperty; onToggle: (index: number) => void; } const RowDisplay = ({ checked, onToggle, header, value, selectValue, }: { checked: boolean; onToggle: () => void; header: string; value: ContactValue; selectValue: 'firstName' | 'lastName'; }) => { return ( <tr key={selectValue}> <td className="text-center"> <Checkbox checked={checked} onChange={onToggle} /> </td> <td>{header}</td> <td> <div className="flex"> <ContactImportCsvSelectField value={selectValue} disabled avoidFiltering /> </div> </td> <td className="text-ellipsis" title={value.toString()}> {checked && value} </td> </tr> ); }; // The N field is a special case, it contains two values: firstName and lastName // other values are not supported (additional name, prefix, suffix) // We override the default behavior of ContactImportCsvTableRows // to display two fields instead of one to support first and last name const ContactImportCsvTableRowsNField = ({ preVcards, onToggle }: Props) => { const firstName = preVcards.find(({ header }) => header === 'First Name'); const lastName = preVcards.find(({ header }) => header === 'Last Name'); return ( <> {firstName ? ( <RowDisplay selectValue="firstName" checked={firstName.checked} onToggle={() => onToggle(0)} header={firstName.header} value={firstName.value} /> ) : null} {lastName ? ( <RowDisplay selectValue="lastName" checked={lastName.checked} onToggle={() => onToggle(1)} header={lastName.header} value={lastName.value} /> ) : null} </> ); }; export default ContactImportCsvTableRowsNField;
6,065
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportGroups.tsx
import { ChangeEvent, Dispatch, FormEvent, SetStateAction } from 'react'; import { c, msgid } from 'ttag'; import { Button, Input } from '@proton/atoms'; import { FORBIDDEN_LABEL_NAMES } from '@proton/shared/lib/constants'; import { omit } from '@proton/shared/lib/helpers/object'; import { normalize } from '@proton/shared/lib/helpers/string'; import { ContactGroup, IMPORT_GROUPS_ACTION, ImportContactsModel } from '@proton/shared/lib/interfaces/contacts'; import isTruthy from '@proton/utils/isTruthy'; import { Alert, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Option, SelectTwo } from '../../../../components'; import { useApi, useEventManager } from '../../../../hooks'; import { submitCategories } from '../encryptAndSubmit'; interface SelectGroupActionProps { action: IMPORT_GROUPS_ACTION; index: number; canMerge: boolean; onChange: (action: IMPORT_GROUPS_ACTION, index: number) => void; } const SelectGroupAction = ({ action, index, canMerge, onChange }: SelectGroupActionProps) => { const actionOptions = [ canMerge && { text: c('Option').t`Add to existing group`, value: IMPORT_GROUPS_ACTION.MERGE }, { text: c('Option').t`Create new group`, value: IMPORT_GROUPS_ACTION.CREATE }, { text: c('Option').t`Ignore group`, value: IMPORT_GROUPS_ACTION.IGNORE }, ].filter(isTruthy); return ( <SelectTwo id="contact-group-action-select" value={action} onChange={({ value }) => onChange(value as IMPORT_GROUPS_ACTION, index)} title={c('Title').t`Select action to take on contact group`} > {actionOptions.map(({ text, value }) => ( <Option key={value} value={value} title={text} /> ))} </SelectTwo> ); }; interface SelectGroupProps { targetGroup: ContactGroup; targetName: string; contactGroups?: ContactGroup[]; action: IMPORT_GROUPS_ACTION; index: number; error?: string; onChangeTargetGroup: (targetGroup: ContactGroup, index: number) => void; onChangeTargetName: (targetName: string, index: number) => void; onError: (error: string, index: number) => void; } const SelectGroup = ({ targetGroup, targetName, contactGroups = [], action, index, error, onChangeTargetGroup, onChangeTargetName, onError, }: SelectGroupProps) => { const groupNames = contactGroups.map(({ Name }) => Name); const groupsOptions = contactGroups.map((group) => ({ text: group.Name, value: group, })); const handleChangeGroupName = ({ target }: ChangeEvent<HTMLInputElement>) => { // Clear previous errors onError('', index); const name = target.value; if (!name) { onError(c('Error').t`You must set a name`, index); } else if (groupNames.includes(name)) { onError(c('Error').t`A group with this name already exists`, index); } else if (FORBIDDEN_LABEL_NAMES.includes(normalize(name))) { onError(c('Error').t`Invalid name`, index); } onChangeTargetName(target.value, index); }; if (action === IMPORT_GROUPS_ACTION.CREATE) { return ( <Input id="contact-group-create" placeholder={c('Placeholder').t`Name`} maxLength={100} title={c('Title').t`Add contact group name`} error={error} value={targetName} onChange={handleChangeGroupName} /> ); } if (action === IMPORT_GROUPS_ACTION.MERGE) { return ( <SelectTwo id="contact-group-select" value={targetGroup} onChange={({ value }) => onChangeTargetGroup(value, index)} title={c('Title').t`Select contact group`} > {groupsOptions.map(({ text, value }) => ( <Option key={value.Name} value={value} title={text} /> ))} </SelectTwo> ); } return null; }; interface Props { model: ImportContactsModel; setModel: Dispatch<SetStateAction<ImportContactsModel>>; onClose?: () => void; } const ContactImportGroups = ({ model, setModel, onClose }: Props) => { const api = useApi(); const { call } = useEventManager(); const { categories } = model; const cannotSave = categories.some( ({ error, action, targetName }) => !!error || (action === IMPORT_GROUPS_ACTION.CREATE && !targetName) ); const handleChangeAction = (action: IMPORT_GROUPS_ACTION, index: number) => { setModel((model) => ({ ...model, categories: model.categories.map((category, j) => { if (index !== j) { return category; } return { ...omit(category, ['error']), action }; }), })); }; const handleChangeTargetGroup = (targetGroup: ContactGroup, index: number) => { setModel((model) => ({ ...model, categories: model.categories.map((category, j) => { if (index !== j) { return category; } return { ...category, targetGroup }; }), })); }; const handleChangeTargetName = (targetName: string, index: number) => { setModel((model) => ({ ...model, categories: model.categories.map((category, j) => { if (index !== j) { return category; } return { ...category, targetName }; }), })); }; const handleSetError = (error: string, index: number) => { setModel((model) => ({ ...model, categories: model.categories.map((category, j) => { if (index !== j) { return category; } return { ...category, error }; }), })); }; const handleSubmit = async (event: FormEvent) => { event.preventDefault(); event.stopPropagation(); setModel((model) => ({ ...model, loading: true })); await submitCategories(model.categories, api); await call(); setModel((model) => ({ ...model, loading: false })); onClose?.(); }; const rows = categories.map(({ name, totalContacts, action, targetGroup, targetName, error }, index) => { const totalContactsString = c('Import contact groups info').ngettext( msgid`${totalContacts} contact`, `${totalContacts} contacts`, totalContacts ); const categoryString = `${name} (${totalContactsString})`; return ( <div key={name} className="flex flex-nowrap flex-item-fluid flex-align-items-center on-tiny-mobile-flex-column mb-4" > <div className="flex-item-fluid text-ellipsis mr-4" title={categoryString}> {categoryString} </div> <div className="flex-item-fluid mr-0 md:mr-1"> <SelectGroupAction action={action} index={index} canMerge={!!model.contactGroups?.length} onChange={handleChangeAction} /> </div> <div className="flex-item-fluid w-3/10"> <SelectGroup contactGroups={model.contactGroups} action={action} targetGroup={targetGroup} targetName={targetName} error={error} index={index} onChangeTargetGroup={handleChangeTargetGroup} onChangeTargetName={handleChangeTargetName} onError={handleSetError} /> </div> </div> ); }); return ( <form className="modal-two-dialog-container h-full" onSubmit={handleSubmit}> <ModalTwoHeader title={c('Title').t`Warning`} /> <ModalTwoContent> <Alert className="mb-4"> {c('Description') .t`It looks like the contact list you are importing contains some groups. Please review how these groups should be imported.`} </Alert> {rows} </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" disabled={cannotSave} loading={model.loading} type="submit"> {c('Action').t`Save`} </Button> </ModalTwoFooter> </form> ); }; export default ContactImportGroups;
6,066
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportSummary.tsx
import { Dispatch, FormEvent, SetStateAction } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { getImportCategoriesModel, haveCategories } from '@proton/shared/lib/contacts/helpers/import'; import { IMPORT_STEPS, ImportContactsModel } from '@proton/shared/lib/interfaces/contacts/Import'; import { Alert, DynamicProgress, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../../components'; import { useUser } from '../../../../hooks'; import { useGetContactGroups } from '../../../../hooks/useCategories'; import { extractTotals } from '../encryptAndSubmit'; import ContactImportWarningErrorDetails from './ContactImportWarningErrorDetails'; interface GetMessageParams { isSuccess: boolean; isPartialSuccess: boolean; totalImported: number; totalToImport: number; } const getAlertMessage = ({ isSuccess, isPartialSuccess, totalImported, totalToImport }: GetMessageParams) => { if (isSuccess) { return totalImported === 1 ? c('Import contact') .t`Contact successfully imported. The imported contact will now appear in your contact list.` : // translator: "Contacts" below is meant as multiple (more than one) contacts generically. The exact number of contacts imported is mentioned elsewhere c('Import contact') .t`Contacts successfully imported. The imported contacts will now appear in your contact list.`; } if (isPartialSuccess) { return c('Import contact') .t`An error occurred while encrypting and adding your contacts. ${totalImported} out of ${totalToImport} contacts successfully imported.`; } return totalImported === 1 ? c('Import contact') .t`An error occurred while encrypting and adding your contact. No contact could be imported.` : // translator: "Contacts" below is meant as multiple (more than one) contacts generically. The exact number of contacts we tried to import is mentioned elsewhere c('Import contact') .t`An error occurred while encrypting and adding your contacts. No contact could be imported.`; }; const getDisplayMessage = ({ isSuccess, isPartialSuccess, totalImported, totalToImport }: GetMessageParams) => { if (!isSuccess && !isPartialSuccess) { return ''; } return c('Import contact').ngettext( msgid`${totalImported}/${totalToImport} contact encrypted and added to your contact list`, `${totalImported}/${totalToImport} contacts encrypted and added to your contact list`, totalToImport ); }; const getAlertType = ({ isSuccess, isPartialSuccess }: Pick<GetMessageParams, 'isSuccess' | 'isPartialSuccess'>) => { if (isSuccess) { return 'info'; } if (isPartialSuccess) { return 'warning'; } return 'error'; }; interface Props { model: ImportContactsModel; setModel: Dispatch<SetStateAction<ImportContactsModel>>; onClose?: () => void; } const ContactImportSummary = ({ model, setModel, onClose }: Props) => { const [user] = useUser(); const getContactGroups = useGetContactGroups(); const { totalToImport, totalToProcess, totalImported, totalProcessed } = extractTotals(model); const isSuccess = totalImported === totalToImport; const isPartialSuccess = totalImported > 0 && !isSuccess; const canImportGroups = haveCategories(model.importedContacts) && user.hasPaidMail; const handleSubmit = async (event: FormEvent) => { event.preventDefault(); event.stopPropagation(); if (canImportGroups) { setModel((model) => ({ ...model, loading: true })); const contactGroups = await getContactGroups(); setModel((model) => ({ ...model, step: IMPORT_STEPS.IMPORT_GROUPS, loading: false, contactGroups, categories: getImportCategoriesModel(model.importedContacts, contactGroups), })); } else { onClose?.(); } }; const alertMessage = getAlertMessage({ isSuccess, isPartialSuccess, totalImported, totalToImport }); const displayMessage = getDisplayMessage({ isSuccess, isPartialSuccess, totalImported, totalToImport }); const alertType = getAlertType({ isSuccess, isPartialSuccess }); return ( <form className="modal-two-dialog-container h-full" onSubmit={handleSubmit}> <ModalTwoHeader title={c('Title').t`Import contacts`} /> <ModalTwoContent> <Alert className="mb-4" type={alertType}> {alertMessage} </Alert> <DynamicProgress id="progress-import-contacts" value={totalProcessed} display={displayMessage} max={totalToProcess} loading={false} success={isSuccess} partialSuccess={isPartialSuccess} /> <ContactImportWarningErrorDetails errors={model.errors} /> </ModalTwoContent> <ModalTwoFooter> {canImportGroups ? <Button onClick={onClose}>{c('Action').t`Close`}</Button> : null} <Button color="norm" loading={model.loading} type="submit" className="ml-auto"> {canImportGroups ? c('Action').t`Next` : c('Action').t`Close`} </Button> </ModalTwoFooter> </form> ); }; export default ContactImportSummary;
6,067
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportWarning.tsx
import { Dispatch, FormEvent, SetStateAction } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CONTACTS_APP_NAME } from '@proton/shared/lib/constants'; import { IMPORT_STEPS, ImportContactsModel } from '@proton/shared/lib/interfaces/contacts/Import'; import { Alert, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../../components'; import ErrorDetails from './ContactImportWarningErrorDetails'; interface Props { model: ImportContactsModel; setModel: Dispatch<SetStateAction<ImportContactsModel>>; onClose?: () => void; } const ContactImportWarning = ({ model, setModel, onClose }: Props) => { const contactsDiscarded = model.errors; const totalSupported = model.parsedVcardContacts.length; const totalContactsDiscarded = contactsDiscarded.length; const totalContacts = totalSupported + totalContactsDiscarded; const forNow = <strong key="for-now">{c('Import contacts warning').t`for now`}</strong>; const summary = totalContactsDiscarded === totalContacts ? c('Import warning').t`No contact can be imported. Click for details` : c('Import warning') .t`${totalContactsDiscarded} out of ${totalContacts} contacts will not be imported. Click for details`; const handleSubmit = (event: FormEvent) => { event.preventDefault(); event.stopPropagation(); setModel({ ...model, step: IMPORT_STEPS.IMPORTING, errors: [] }); }; return ( <form className="modal-two-dialog-container h-full" onSubmit={handleSubmit}> <ModalTwoHeader title={c('Title').t`Warning`} /> <ModalTwoContent> <Alert className="mb-4" type="warning"> <div>{c('Import contacts warning').jt`${CONTACTS_APP_NAME} does not support ${forNow}:`}</div> <ul> <li>{c('Import calendar warning').t`vCard versions < 3.0`}</li> </ul> </Alert> <ErrorDetails summary={summary} errors={model.errors} /> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" disabled={!model.parsedVcardContacts?.length} type="submit"> {c('Action').t`Import`} </Button> </ModalTwoFooter> </form> ); }; export default ContactImportWarning;
6,068
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImportWarningErrorDetails.tsx
import { c } from 'ttag'; import { ImportContactError } from '@proton/shared/lib/contacts/errors/ImportContactError'; import { Bordered, Details, Summary } from '../../../../components'; const ErrorDetail = ({ error, ...rest }: { error: ImportContactError }) => { const { contactId } = error; return ( <div {...rest}> <span>{c('Import contact error').t`Contact ${contactId}: `}</span> <span className="color-danger">{error.message}</span> </div> ); }; interface Props { summary?: string; errors: ImportContactError[]; } const ContactImportWarningErrorDetails = ({ errors, summary = c('Info on errors').t`Click for details` }: Props) => { if (!errors.length) { return null; } return ( <Details> <Summary>{summary}</Summary> <Bordered className="rounded"> {errors.map((error, i) => ( <ErrorDetail error={error} key={error.contactId + i.toString()} /> ))} </Bordered> </Details> ); }; export default ContactImportWarningErrorDetails;
6,069
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/import/steps/ContactImporting.tsx
import { Dispatch, SetStateAction, useEffect } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getApiWithAbort } from '@proton/shared/lib/api/helpers/customConfig'; import { CATEGORIES, OVERWRITE } from '@proton/shared/lib/contacts/constants'; import { ImportContactError } from '@proton/shared/lib/contacts/errors/ImportContactError'; import { ImportFatalError } from '@proton/shared/lib/contacts/errors/ImportFatalError'; import { EncryptedContact, IMPORT_STEPS, ImportContactsModel, ImportedContact, } from '@proton/shared/lib/interfaces/contacts/Import'; import { splitKeys } from '@proton/shared/lib/keys/keys'; import { Alert, DynamicProgress, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../../components'; import { useApi, useBeforeUnload, useEventManager, useGetUserKeys } from '../../../../hooks'; import { extractTotals, processContactsInBatches } from '../encryptAndSubmit'; interface Props { model: ImportContactsModel; setModel: Dispatch<SetStateAction<ImportContactsModel>>; onClose?: () => void; } const ContactImporting = ({ model, setModel, onClose }: Props) => { const api = useApi(); const { call } = useEventManager(); const getUserKeys = useGetUserKeys(); useBeforeUnload(c('Alert').t`By leaving now, some contacts may not be imported`); const handleFinish = async (importedContacts: ImportedContact[]) => { setModel((model) => ({ ...model, importedContacts, step: IMPORT_STEPS.SUMMARY })); await call(); }; useEffect(() => { // Prepare api for allowing cancellation in the middle of the import const abortController = new AbortController(); const { signal } = abortController; const setModelWithAbort = (set: (model: ImportContactsModel) => ImportContactsModel) => { if (signal.aborted) { return; } setModel(set); }; const handleImportProgress = ( encrypted: EncryptedContact[], imported: ImportedContact[], errors: ImportContactError[] ) => { setModelWithAbort((model) => ({ ...model, totalEncrypted: model.totalEncrypted + encrypted.length, totalImported: model.totalImported + imported.length, importedContacts: [...model.importedContacts, ...imported], errors: [...model.errors, ...errors], })); }; const process = async () => { try { const { privateKeys: [privateKey], publicKeys: [publicKey], } = splitKeys(await getUserKeys()); const keyPair = { privateKey, publicKey }; const importedContacts = await processContactsInBatches({ contacts: model.parsedVcardContacts, labels: CATEGORIES.IGNORE, overwrite: OVERWRITE.OVERWRITE_CONTACT, keyPair, api: getApiWithAbort(api, signal), signal, onProgress: handleImportProgress, isImport: true, }); if (signal.aborted) { return; } void handleFinish(importedContacts); } catch (error: any) { setModelWithAbort(() => ({ step: IMPORT_STEPS.ATTACHING, parsedVcardContacts: [], importedContacts: [], totalEncrypted: 0, totalImported: 0, errors: [], categories: [], loading: false, failure: new ImportFatalError(error), })); if (signal.aborted) { return; } void handleFinish([]); } }; void process(); return () => { abortController.abort(); }; }, []); const { totalToImport, totalToProcess, totalImported, totalProcessed } = extractTotals(model); return ( <> <ModalTwoHeader title={c('Title').t`Import contacts`} /> <ModalTwoContent> <Alert className="mb-4"> {c('Description') .t`Encrypting and importing contacts... This may take a few minutes. When the process is completed, you can close this modal.`} </Alert> <DynamicProgress id="progress-import-contacts" value={totalProcessed} display={c('Import calendar').t`Encrypting and adding contacts: ${totalImported}/${totalToImport}`} max={totalToProcess} loading /> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" disabled type="submit"> {c('Action').t`Continue`} </Button> </ModalTwoFooter> </> ); }; export default ContactImporting;
6,070
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/lists/ContactGroupRow.tsx
import { CSSProperties, ChangeEvent, MouseEvent, useState } from 'react'; import tinycolor from 'tinycolor2'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms/Button'; import genAccentShades from '@proton/colors/gen-accent-shades'; import { Icon } from '@proton/components/components/icon'; import { Tooltip } from '@proton/components/components/tooltip'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import clsx from '@proton/utils/clsx'; import ItemCheckbox from '../../items/ItemCheckbox'; import { ContactRowItemFirstLine, ContactRowItemSecondLine } from './ContactRowItem'; interface Props { checked: boolean; onClick: (ID: string) => void; onCheck: (event: ChangeEvent) => void; style: CSSProperties; groupsEmailsMap: SimpleMap<ContactEmail[]>; group: ContactGroup; index: number; onFocus: (index: number) => void; isDrawer?: boolean; onCompose?: (recipients: Recipient[], attachments: File[]) => void; } const ContactGroupRow = ({ checked, style, groupsEmailsMap, group, onClick, onCheck, index, onFocus, isDrawer = false, onCompose, }: Props) => { const { ID, Name, Color } = group; const [hasFocus, setHasFocus] = useState(false); const addressCount = groupsEmailsMap[ID]?.length || 0; const colors = genAccentShades(tinycolor(Color)).map((c) => c.toHexString()); const handleFocus = () => { setHasFocus(true); onFocus(index); }; const handleBlur = () => { setHasFocus(false); }; const handleCompose = (e: MouseEvent<HTMLButtonElement>) => { e.stopPropagation(); const recipients: Recipient[] = groupsEmailsMap[ID]?.map((contact) => ({ Name: contact.Name, Address: contact.Email })) || []; onCompose?.([...recipients], []); }; const title = addressCount === 0 ? c('Info').t`No email address` : c('Info').ngettext(msgid`${addressCount} email address`, `${addressCount} email addresses`, addressCount); return ( <div key={ID} style={style} onClick={() => onClick(ID)} className={clsx([ 'item-container item-contact flex cursor-pointer bg-global-white', hasFocus && 'item-is-focused', isDrawer && 'item-in-drawer', ])} onFocus={handleFocus} onBlur={handleBlur} tabIndex={-1} data-element-id={group.ID} data-shortcut-target="contact-container" data-testid={`group-item:${group.Name}`} > <div className="flex flex-nowrap w-full h-full my-auto flex-align-items-start"> <ItemCheckbox ID={ID} name={Name} checked={checked} onChange={onCheck} iconName="users" color={checked ? colors[2] : Color} /> <div className="flex-item-fluid ml-2 conversation-titlesender"> <ContactRowItemFirstLine ID={ID} Name={Name} /> <ContactRowItemSecondLine title={title}> {addressCount === 0 ? c('Info').t`No email address` : c('Info').ngettext( msgid`${addressCount} email address`, `${addressCount} email addresses`, addressCount )} </ContactRowItemSecondLine> </div> {onCompose && addressCount > 0 && ( <div className="item-hover-action-buttons"> <Tooltip title={c('Action').t`Compose`}> <Button color="weak" shape="ghost" icon onClick={handleCompose}> <Icon name="pen-square" alt={c('Action').t`Compose`} /> </Button> </Tooltip> </div> )} </div> </div> ); }; export default ContactGroupRow;
6,071
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/lists/ContactRow.tsx
import { CSSProperties, ChangeEvent, DragEvent, MouseEvent, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Icon, Tooltip } from '@proton/components/components'; import { addPlus } from '@proton/shared/lib/helpers/string'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactFormatted, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import clsx from '@proton/utils/clsx'; import { Copy } from '../../../components/button'; import { useNotifications } from '../../../hooks'; import { ItemCheckbox } from '../../items'; import ContactGroupLabels from '../group/ContactGroupLabels'; import { ContactRowItemFirstLine, ContactRowItemSecondLine } from './ContactRowItem'; interface Props { checked: boolean; onClick: (ID: string) => void; onCheck: (event: ChangeEvent) => void; style: CSSProperties; hasPaidMail: boolean; contactGroupsMap: SimpleMap<ContactGroup>; contact: ContactFormatted; draggable?: boolean; onDragStart?: (event: DragEvent) => void; onDragEnd?: (event: DragEvent) => void; dragged?: boolean; index: number; onFocus: (index: number) => void; onGroupDetails: (contactGroupID: string) => void; isDrawer?: boolean; onCompose?: (recipients: Recipient[], attachments: File[]) => void; } const ContactRow = ({ checked, style, hasPaidMail, contactGroupsMap, contact, onClick, onCheck, draggable, onDragStart, onDragEnd, dragged, index, onFocus, onGroupDetails, isDrawer = false, onCompose, }: Props) => { const { createNotification } = useNotifications(); const { ID, Name, LabelIDs = [], emails = [] } = contact; const [hasFocus, setHasFocus] = useState(false); const contactGroups = contact.LabelIDs.map((ID) => contactGroupsMap[ID] as ContactGroup); const handleFocus = () => { setHasFocus(true); onFocus(index); }; const handleBlur = () => { setHasFocus(false); }; const handleCopyEmail = () => { if (emails[0]) { createNotification({ type: 'success', text: c('Success').t`Email address copied to clipboard`, }); } }; const handleCompose = (e: MouseEvent<HTMLButtonElement>) => { e.stopPropagation(); if (onCompose && emails[0]) { const recipient: Recipient = { Name: contact.Name, Address: emails[0] }; onCompose([recipient], []); } }; return ( <div style={style} key={ID} onClick={() => onClick(ID)} draggable={draggable} onDragStart={onDragStart} onDragEnd={onDragEnd} className={clsx( 'item-container item-contact flex cursor-pointer bg-global-white group-hover-opacity-container', isDrawer && 'item-in-drawer', dragged && 'item-dragging', hasFocus && 'item-is-focused' )} onFocus={handleFocus} onBlur={handleBlur} tabIndex={-1} data-element-id={contact.ID} data-shortcut-target="contact-container" data-testid={`contact-item:${Name}`} > <div className="flex flex-nowrap w-full h-full my-auto flex-align-items-start"> <ItemCheckbox ID={ID} name={Name} checked={checked} onChange={onCheck} /> <div className="flex-item-fluid ml-2 conversation-titlesender"> <ContactRowItemFirstLine ID={ID} Name={Name} className={!!LabelIDs.length ? 'pr-4' : ''} /> <ContactRowItemSecondLine title={emails.join(', ')}> {emails.length ? ( addPlus(emails as any) ) : ( <span className="placeholder">{c('Info').t`No email address`}</span> )} </ContactRowItemSecondLine> {hasPaidMail && contactGroups && ( <ContactGroupLabels contactGroups={contactGroups} className="mt-0.5" onDetails={onGroupDetails} leftToRight maxNumber={4} /> )} </div> {emails[0] && ( <span className="flex gap-4"> {onCompose && ( <div className="item-hover-action-buttons"> <Tooltip title={c('Action').t`Compose`}> <Button color="weak" shape="ghost" icon onClick={handleCompose}> <Icon name="pen-square" alt={c('Action').t`Compose`} /> </Button> </Tooltip> </div> )} <div className="item-hover-action-buttons"> <Copy value={emails[0]} className={clsx(isDrawer && 'mr-1')} onCopy={handleCopyEmail} tooltipText={c('Action').t`Copy email to clipboard`} shape="ghost" /> </div> </span> )} </div> </div> ); }; export default ContactRow;
6,072
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/lists/ContactRowItem.tsx
import { ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; interface ContactRowItemFirstLineProps { ID: string; Name: string; className?: string; } export const ContactRowItemFirstLine = ({ ID, Name, className }: ContactRowItemFirstLineProps) => { return ( <div className="flex flex-nowrap flex-align-items-center item-firstline max-w-full"> <div className={clsx('flex flex-item-fluid w-0', className)}> <span role="heading" aria-level={2} className="text-bold inline-block max-w-full text-ellipsis" id={ID}> {Name} </span> </div> </div> ); }; interface ContactRowItemSecondLineProps { title: string; children: ReactNode; } export const ContactRowItemSecondLine = ({ title, children }: ContactRowItemSecondLineProps) => { return ( <div className="item-secondline max-w-full text-ellipsis text-sm" title={title}> {children} </div> ); };
6,073
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/lists/ContactsGroupsList.tsx
import { ChangeEvent, useMemo, useRef } from 'react'; import { AutoSizer, List } from 'react-virtualized'; import { rootFontSize } from '@proton/shared/lib/helpers/dom'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import clsx from '@proton/utils/clsx'; import { useContactFocus } from '../../../hooks/useContactFocus'; import { useContactHotkeys } from '../../../hooks/useContactHotkeys'; import ContactGroupRow from './ContactGroupRow'; interface Props { groups: ContactGroup[]; groupsEmailsMap: SimpleMap<ContactEmail[]>; onCheckOne: (event: ChangeEvent, contactID: string) => void; isDesktop: boolean; checkedIDs: string[]; onClick: (contactID: string) => void; isDrawer?: boolean; onCompose?: (recipients: Recipient[], attachments: File[]) => void; } const ContactsGroupsList = ({ groups, groupsEmailsMap, onCheckOne, isDesktop = true, checkedIDs, onClick, isDrawer = false, onCompose, }: Props) => { const listRef = useRef<List>(null); const listContainerRef = useRef<HTMLDivElement>(null); const contactRowHeightComfort = 4 * rootFontSize(); // 4 * 16 = we want 64px by default const contactGroupIDs: string[] = useMemo(() => { return groups.map((group) => group.ID); }, [groups]); const handleElement = (id: string) => onClick(id); const { focusIndex, getFocusedId, setFocusIndex, handleFocus } = useContactFocus({ elementIDs: contactGroupIDs, listRef: listContainerRef, }); const elementRef = useContactHotkeys( { elementIDs: contactGroupIDs, focusIndex, }, { getFocusedId, setFocusIndex, handleElement, } ); return ( <div ref={elementRef} className={clsx(isDesktop ? 'items-column-list' : 'items-column-list--mobile')}> <div ref={listContainerRef} className="items-column-list-inner items-column-list-inner--border-none"> <AutoSizer> {({ height, width }) => ( <List className="contacts-list outline-none" ref={listRef} rowRenderer={({ index, style, key }) => ( <ContactGroupRow style={style} key={key} checked={checkedIDs.includes(groups[index].ID)} groupsEmailsMap={groupsEmailsMap} group={groups[index]} onClick={onClick} onCheck={(event) => onCheckOne(event, groups[index].ID)} index={index} onFocus={handleFocus} isDrawer={isDrawer} onCompose={onCompose} /> )} rowCount={groups.length} height={height} width={width - 1} rowHeight={contactRowHeightComfort} tabIndex={-1} /> )} </AutoSizer> </div> </div> ); }; export default ContactsGroupsList;
6,074
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/lists/ContactsList.tsx
import { ChangeEvent, useMemo, useRef } from 'react'; import { AutoSizer, List } from 'react-virtualized'; import { rootFontSize } from '@proton/shared/lib/helpers/dom'; import { Recipient, UserModel } from '@proton/shared/lib/interfaces'; import { ContactFormatted, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import clsx from '@proton/utils/clsx'; import { useContactFocus } from '../../../hooks/useContactFocus'; import { useContactHotkeys } from '../../../hooks/useContactHotkeys'; import { useItemsDraggable } from '../../items'; import ContactRow from './ContactRow'; interface Props { contacts: ContactFormatted[]; contactGroupsMap: SimpleMap<ContactGroup>; onCheckOne: (event: ChangeEvent, contactID: string) => void; user: UserModel; isDesktop: boolean; onCheck: (contactIDs: string[], checked: boolean, replace: boolean) => void; checkedIDs: string[]; onClick: (contactID: string) => void; activateDrag?: boolean; onGroupDetails: (contactGroupID: string) => void; isDrawer?: boolean; onCompose?: (recipients: Recipient[], attachments: File[]) => void; } const ContactsList = ({ contacts, contactGroupsMap, onCheckOne, user, isDesktop = true, onCheck, checkedIDs, onClick, activateDrag = true, onGroupDetails, isDrawer = false, onCompose, }: Props) => { const listRef = useRef<List>(null); const listContainerRef = useRef<HTMLDivElement>(null); const contactIDs: string[] = useMemo(() => { return contacts.map((contact) => contact.ID); }, [contacts]); const handleElement = (id: string) => onClick(id); const { focusIndex, getFocusedId, setFocusIndex, handleFocus } = useContactFocus({ elementIDs: contactIDs, listRef: listContainerRef, }); const elementRef = useContactHotkeys( { elementIDs: contactIDs, focusIndex, }, { getFocusedId, setFocusIndex, handleElement, } ); // Useless if activateDrag is false but hook has to be run anyway const { draggedIDs, handleDragStart, handleDragEnd } = useItemsDraggable( contacts, checkedIDs, onCheck, (draggedIDs: string[]) => { return `${draggedIDs.length} contacts`; } ); const contactRowHeightComfort = 4 * rootFontSize() + 8; // 4 * 16 = we want 72px by default return ( <div ref={elementRef} className={clsx(isDesktop ? 'items-column-list' : 'items-column-list--mobile')}> <div ref={listContainerRef} className="items-column-list-inner items-column-list-inner--border-none"> <AutoSizer> {({ height, width }) => ( <List className="contacts-list outline-none" ref={listRef} rowRenderer={({ index, style, key }) => ( <ContactRow style={style} key={key} checked={checkedIDs.includes(contacts[index].ID)} hasPaidMail={!!user.hasPaidMail} contactGroupsMap={contactGroupsMap} contact={contacts[index]} onClick={onClick} onCheck={(event) => onCheckOne(event, contacts[index].ID)} draggable={activateDrag} onDragStart={(event) => handleDragStart?.(event, contacts[index])} onDragEnd={handleDragEnd} dragged={draggedIDs.includes(contacts[index].ID)} index={index} onFocus={handleFocus} onGroupDetails={onGroupDetails} isDrawer={isDrawer} onCompose={onCompose} /> )} rowCount={contacts.length} height={height} width={width} rowHeight={contactRowHeightComfort} tabIndex={-1} /> )} </AutoSizer> </div> </div> ); }; export default ContactsList;
6,075
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/ContactMergeDetailsModal.tsx
import { useMemo } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import useContactList from '@proton/components/containers/contacts/hooks/useContactList'; import { toMap } from '@proton/shared/lib/helpers/object'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import noop from '@proton/utils/noop'; import { Loader, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components'; import { useAddresses, useContactGroups, useUserKeys } from '../../../hooks'; import useContact from '../hooks/useContact'; import useVCardContact from '../hooks/useVCardContact'; import ContactView from '../view/ContactView'; export interface ContactMergeDetailsModalProps { contactID: string; } type Props = ContactMergeDetailsModalProps & ModalProps; const ContactMergeDetailsModal = ({ contactID, ...rest }: Props) => { const [userKeysList] = useUserKeys(); const [contact] = useContact(contactID); const { vCardContact, isLoading, errors } = useVCardContact({ contact, userKeysList }); const { loading: loadingContactEmails, contactEmailsMap } = useContactList({}); const [addresses = [], loadingAddresses] = useAddresses(); const ownAddresses = useMemo(() => addresses.map(({ Email }) => Email), [addresses]); const [contactGroups = [], loadingContactGroups] = useContactGroups(); const contactGroupsMap = useMemo(() => toMap(contactGroups), [contactGroups]); if (!isLoading && !vCardContact && vCardContact === undefined) { return null; } return ( <ModalTwo size="large" className="contacts-modal" {...rest}> <ModalTwoHeader title={c('Title').t`Contact Details`} /> <ModalTwoContent> {isLoading || loadingContactEmails || loadingAddresses || loadingContactGroups ? ( <Loader /> ) : ( <ContactView vCardContact={vCardContact!} errors={errors} contactID={contactID} isPreview contactEmails={contactEmailsMap[contactID] as ContactEmail[]} contactGroupsMap={contactGroupsMap} ownAddresses={ownAddresses} onReload={noop} onEdit={noop} onEmailSettings={noop} onGroupDetails={noop} onGroupEdit={noop} onUpgrade={noop} onSignatureError={noop} onDecryptionError={noop} /> )} </ModalTwoContent> <ModalTwoFooter> <Button color="norm" className="ml-auto" onClick={rest.onClose}>{c('Action').t`Close`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactMergeDetailsModal;
6,076
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/ContactMergeErrorContent.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, Icon, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components'; interface Props { model: { errorOnMerge?: boolean; errorOnLoad?: boolean; }; onClose?: () => void; } const ContactMergeErrorContent = ({ model, onClose }: Props) => { const error = model.errorOnLoad ? c('Warning').t`Some of the contacts to be merged display errors. Please review them individually` : c('Warning').t`Contacts could not be merged`; return ( <> <ModalTwoHeader title={c('Title').t`Contact Details`} /> <ModalTwoContent> <Alert type="warning"> <Icon name="exclamation-circle" className="mr-4" /> <span className="mr-4">{error}</span> </Alert> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> </ModalTwoFooter> </> ); }; export default ContactMergeErrorContent;
6,077
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/ContactMergeModal.tsx
import { useEffect, useMemo, useState } from 'react'; import { ContactFormatted, ContactMergeModel } from '@proton/shared/lib/interfaces/contacts'; import { ModalProps, ModalTwo } from '../../../components'; import { useEventManager } from '../../../hooks'; import { ContactMergePreviewModalProps } from './ContactMergePreviewModal'; import ContactMergeTableContent from './ContactMergeTableContent'; import ContactMergingContent from './ContactMergingContent'; export interface ContactMergeProps { contacts: ContactFormatted[][]; onMerged: () => void; } export interface ContactMergeModalProps { onMergeDetails: (contactID: string) => void; onMergePreview: (props: ContactMergePreviewModalProps) => void; } type Props = ContactMergeProps & ContactMergeModalProps & ModalProps; const ContactMergeModal = ({ contacts, onMerged, onMergeDetails, onMergePreview, ...rest }: Props) => { const { call } = useEventManager(); const [isMerging, setIsMerging] = useState(false); const [mergeFinished, setMergeFinished] = useState(false); const [model, setModel] = useState<ContactMergeModel>(() => ({ orderedContacts: contacts, isChecked: contacts.flat().reduce<{ [ID: string]: boolean }>((acc, { ID }) => { acc[ID] = true; return acc; }, {}), beDeleted: contacts.flat().reduce<{ [ID: string]: boolean }>((acc, { ID }) => { acc[ID] = false; return acc; }, {}), })); const { orderedContacts, isChecked, beDeleted } = model; useEffect(() => { // close the modal if all contacts have been merged from preview if (!orderedContacts.flat().length) { onMerged?.(); rest.onClose?.(); } }, [orderedContacts]); // beMergedModel = { 'ID of be-merged contact': [IDs to be merged] } // beDeletedModel = { 'ID of be-deleted contact': 'ID to navigate to in case it is the current ID' } const { beMergedModel, beDeletedModel, totalBeMerged, totalBeDeleted } = useMemo( () => orderedContacts.reduce<{ beMergedModel: { [ID: string]: string[] }; beDeletedModel: { [ID: string]: string }; totalBeMerged: number; totalBeDeleted: number; }>( (acc, group) => { const groupIDs = group.map(({ ID }) => ID); const beMergedIDs = groupIDs .map((ID) => isChecked[ID] && !beDeleted[ID] && ID) .filter(Boolean) as string[]; const beDeletedIDs = groupIDs.map((ID) => beDeleted[ID] && ID).filter(Boolean) as string[]; const willBeMerged = beMergedIDs.length > 1; if (willBeMerged) { acc.beMergedModel[beMergedIDs[0]] = beMergedIDs; acc.totalBeMerged += beMergedIDs.length; } for (const ID of beDeletedIDs) { // route to merged contact or to /contacts if no associated contact is merged acc.beDeletedModel[ID] = willBeMerged ? beMergedIDs[0] : ''; acc.totalBeDeleted += 1; } return acc; }, { beMergedModel: {}, beDeletedModel: {}, totalBeMerged: 0, totalBeDeleted: 0 } ), [orderedContacts, isChecked, beDeleted] ); const handleStartMerge = () => { setIsMerging(true); }; const handleMergingFinish = async () => { await call(); setMergeFinished(true); }; const handleMerged = () => { onMerged?.(); rest.onClose?.(); }; return ( <ModalTwo size="large" className="contacts-modal" {...rest}> {isMerging ? ( <ContactMergingContent mergeFinished={mergeFinished} onFinish={handleMergingFinish} onMerged={handleMerged} onClose={rest.onClose} beMergedModel={beMergedModel} beDeletedModel={beDeletedModel} totalBeMerged={totalBeMerged} totalBeDeleted={totalBeDeleted} /> ) : ( <ContactMergeTableContent model={model} updateModel={setModel} onSubmit={handleStartMerge} onClose={rest.onClose} beMergedModel={beMergedModel} beDeletedModel={beDeletedModel} totalBeMerged={totalBeMerged} totalBeDeleted={totalBeDeleted} onMergeDetails={onMergeDetails} onMergePreview={onMergePreview} /> )} </ModalTwo> ); }; export default ContactMergeModal;
6,078
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/ContactMergePreviewModal.tsx
import { Dispatch, SetStateAction, useEffect, useMemo, useState } from 'react'; import { useLoading } from '@proton/hooks'; import { getContact } from '@proton/shared/lib/api/contacts'; import { processApiRequestsSafe } from '@proton/shared/lib/api/helpers/safeApiRequests'; import { prepareVCardContact } from '@proton/shared/lib/contacts/decrypt'; import { merge } from '@proton/shared/lib/contacts/helpers/merge'; import { Contact, ContactMergeModel } from '@proton/shared/lib/interfaces/contacts'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { splitKeys } from '@proton/shared/lib/keys/keys'; import { ModalProps, ModalTwo } from '../../../components'; import { useApi, useEventManager, useUserKeys } from '../../../hooks'; import ContactMergeErrorContent from './ContactMergeErrorContent'; import ContactMergeViewContent from './ContactMergeViewContent'; import MergingModalContent from './ContactMergingContent'; export interface ContactMergePreviewModalProps { beMergedModel: { [ID: string]: string[] }; beDeletedModel: { [ID: string]: string }; updateModel: Dispatch<SetStateAction<ContactMergeModel>>; } type Props = ContactMergePreviewModalProps & ModalProps; const ContactMergePreviewModal = ({ beMergedModel, beDeletedModel, updateModel, ...rest }: Props) => { const { call } = useEventManager(); const api = useApi(); const [userKeysList] = useUserKeys(); const { privateKeys, publicKeys } = useMemo(() => splitKeys(userKeysList), [userKeysList]); const [loading, withLoading] = useLoading(true); const [isMerging, setIsMerging] = useState(false); const [mergeFinished, setMergeFinished] = useState(false); const [model, setModel] = useState<{ mergedVCardContact?: VCardContact; errorOnMerge?: boolean; errorOnLoad?: boolean; }>({}); const [beMergedIDs] = Object.values(beMergedModel); const beDeletedIDs = Object.keys(beDeletedModel); const handleRemoveMerged = () => { const beRemovedIDs = beMergedIDs.slice(1).concat(beDeletedIDs); updateModel((model) => ({ ...model, orderedContacts: model.orderedContacts .map((group) => group.filter(({ ID }) => !beRemovedIDs.includes(ID))) .filter((group) => group.length > 1), })); }; useEffect(() => { const mergeContacts = async () => { try { const requests = beMergedIDs.map((ID: string) => async () => { const { Contact } = await api<{ Contact: Contact }>(getContact(ID)); const { vCardContact, errors } = await prepareVCardContact(Contact, { privateKeys, publicKeys }); if (errors.length) { setModel({ ...model, errorOnLoad: true }); throw new Error('Error decrypting contact'); } return vCardContact; }); const beMergedContacts = await processApiRequestsSafe(requests); const mergedVCardContact = merge(beMergedContacts.map((vCardContact) => vCardContact)); setModel({ ...model, mergedVCardContact }); } catch (e: any) { setModel({ ...model, errorOnMerge: true }); } }; void withLoading(mergeContacts()); }, []); const hasError = model.errorOnLoad || model.errorOnMerge; const handleStartMerge = () => { setIsMerging(true); }; const handleMergingFinish = async () => { handleRemoveMerged(); await call(); setMergeFinished(true); }; return ( <ModalTwo size="large" className="contacts-modal" {...rest}> {hasError ? ( <ContactMergeErrorContent model={model} onClose={rest.onClose} /> ) : ( <> {isMerging ? ( <MergingModalContent alreadyMerged={model.mergedVCardContact} mergeFinished={mergeFinished} beMergedModel={beMergedModel} beDeletedModel={beDeletedModel} totalBeMerged={beMergedIDs.length} totalBeDeleted={beDeletedIDs.length} onFinish={handleMergingFinish} onMerged={rest.onClose} onClose={rest.onClose} /> ) : ( <ContactMergeViewContent contact={model.mergedVCardContact} loading={loading} beMergedIDs={beMergedIDs} onSubmit={handleStartMerge} onClose={rest.onClose} /> )} </> )} </ModalTwo> ); }; export default ContactMergePreviewModal;
6,079
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/ContactMergeTableContent.tsx
import { Dispatch, SetStateAction } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ContactFormatted, ContactMergeModel } from '@proton/shared/lib/interfaces/contacts'; import move from '@proton/utils/move'; import { Alert, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components'; import { ContactMergePreviewModalProps } from './ContactMergePreviewModal'; import MergeTable from './table/MergeTable'; interface Props { model: ContactMergeModel; updateModel: Dispatch<SetStateAction<ContactMergeModel>>; onSubmit: () => void; onClose?: () => void; beMergedModel: { [ID: string]: string[] }; beDeletedModel: { [ID: string]: string }; totalBeMerged: number; totalBeDeleted: number; onMergeDetails: (contactID: string) => void; onMergePreview: (props: ContactMergePreviewModalProps) => void; } /** * Re-order elements in an array inside a group of arrays */ const moveInGroup = ( collection: ContactFormatted[][], groupIndex: number, { oldIndex, newIndex }: { oldIndex: number; newIndex: number } ) => { return collection.map((group, i) => { if (i === groupIndex) { return move(group, oldIndex, newIndex); } return group; }); }; const ContactMergeTableContent = ({ model, updateModel, onSubmit, onClose, beMergedModel, beDeletedModel, totalBeMerged, totalBeDeleted, onMergeDetails, onMergePreview, }: Props) => { const { orderedContacts, isChecked, beDeleted } = model; const isDeleteOnly = totalBeMerged <= 0 && totalBeDeleted > 0; const handleToggleCheck = (ID: string) => { updateModel((model) => ({ ...model, isChecked: { ...isChecked, [ID]: !isChecked[ID] }, })); }; const handleToggleDelete = (ID: string) => { updateModel((model) => ({ ...model, beDeleted: { ...beDeleted, [ID]: !beDeleted[ID] }, })); }; const handleSortEnd = (groupIndex: number) => ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => { updateModel((model) => ({ ...model, orderedContacts: moveInGroup(orderedContacts, groupIndex, { oldIndex, newIndex }), })); }; const handlePreview = (beMergedID: string, beDeletedIDs: string[]) => { const beMergedModelSingle = { [beMergedID]: beMergedModel[beMergedID] }; const beDeletedModelSingle = beDeletedIDs.reduce<{ [ID: string]: string }>((acc, ID) => { acc[ID] = beDeletedModel[ID]; return acc; }, {}); onMergePreview({ beMergedModel: beMergedModelSingle, beDeletedModel: beDeletedModelSingle, updateModel, }); }; return ( <> <ModalTwoHeader title={c('Title').t`Merge contacts`} /> <ModalTwoContent> <Alert className="mb-4"> {c('Description') .t`Use Drag and Drop to rank merging priority between contacts. Uncheck the contacts you do not want to merge.`} </Alert> <Alert className="mb-4" type="warning"> {c('Description') .t`You can mark for deletion the contacts that you do not want neither to merge nor to keep. Deletion will only take place after the merge button is clicked`} </Alert> <MergeTable onSortEnd={handleSortEnd} contacts={orderedContacts} isChecked={isChecked} beDeleted={beDeleted} onClickCheckbox={handleToggleCheck} onClickDetails={onMergeDetails} onToggleDelete={handleToggleDelete} onClickPreview={handlePreview} /> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose} data-testid="merge-model-cancel-button">{c('Action').t`Cancel`}</Button> {isDeleteOnly ? ( <Button color="norm" onClick={onSubmit}>{c('Action').t`Continue`}</Button> ) : ( <Button color="norm" disabled={!totalBeMerged} onClick={onSubmit} data-testid="merge-model-merge-button" > {c('Action').t`Merge`} </Button> )} </ModalTwoFooter> </> ); }; export default ContactMergeTableContent;
6,080
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/ContactMergeViewContent.tsx
import { useMemo } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { toMap } from '@proton/shared/lib/helpers/object'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import noop from '@proton/utils/noop'; import { Loader, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components'; import { useAddresses, useContactGroups } from '../../../hooks'; import useContactList from '../hooks/useContactList'; import ContactView from '../view/ContactView'; interface Props { contact?: VCardContact; loading: boolean; beMergedIDs: string[]; onSubmit: () => void; onClose?: () => void; } const ContactMergeViewContent = ({ contact, loading: loadingContact, beMergedIDs, onSubmit, onClose }: Props) => { const [addresses = [], loadingAddresses] = useAddresses(); const ownAddresses = useMemo(() => addresses.map(({ Email }) => Email), [addresses]); const { loading: loadingContacts, contactEmailsMap } = useContactList({}); const contactEmails = beMergedIDs.flatMap((contactID) => contactEmailsMap[contactID] as ContactEmail[]); const [contactGroups = [], loadingContactGroups] = useContactGroups(); const contactGroupsMap = useMemo(() => toMap(contactGroups), [contactGroups]); const loading = loadingContact || loadingAddresses || loadingContacts || loadingContactGroups; return ( <> <ModalTwoHeader title={c('Title').t`Contact Details`} /> <ModalTwoContent> {loading ? ( <Loader /> ) : ( <ContactView vCardContact={contact as VCardContact} contactID="" contactEmails={contactEmails} contactGroupsMap={contactGroupsMap} ownAddresses={ownAddresses} onReload={noop} onEdit={noop} onEmailSettings={noop} onGroupDetails={noop} onGroupEdit={noop} onUpgrade={noop} onSignatureError={noop} onDecryptionError={noop} isPreview /> )} </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Close`}</Button> <Button color="norm" disabled={!contact} onClick={onSubmit}> {c('Action').t`Merge`} </Button> </ModalTwoFooter> </> ); }; export default ContactMergeViewContent;
6,081
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/ContactMergingContent.test.tsx
import { render, waitFor } from '@testing-library/react'; import { prepareVCardContact } from '@proton/shared/lib/contacts/encrypt'; import useApi from '../../../hooks/useApi'; import ContactMergingContent from './ContactMergingContent'; const encrypt = prepareVCardContact as jest.Mock; jest.mock('../../../hooks/useApi', () => { const apiMock = jest.fn(({ url, method }) => { if (method === 'get') { const parts = url.split('/'); return Promise.resolve({ Contact: { ID: parts[parts.length - 1] } }); } if (method === 'post') { return Promise.resolve({ Responses: [{ Response: { Code: 1000, Contact: { ID: 'id1' } } }] }); } if (method === 'put') { return Promise.resolve(); } }); return () => apiMock; }); jest.mock('../../../hooks/useUserKeys', () => { return { useUserKeys: () => [[]], }; }); jest.mock('@proton/shared/lib/contacts/decrypt', () => { return { prepareVCardContact: jest.fn(({ ID }) => { return Promise.resolve({ vCardContact: { nickname: [{ field: 'nickname', value: ID }] }, errors: [] }); }), }; }); jest.mock('@proton/shared/lib/contacts/encrypt', () => { return { prepareVCardContact: jest.fn(() => { return Promise.resolve({ Cards: ['something encrypted'] }); }), }; }); window.ResizeObserver = window.ResizeObserver || jest.fn().mockImplementation(() => ({ disconnect: jest.fn(), observe: jest.fn(), unobserve: jest.fn(), })); describe('ContactMergingContent', () => { const id1 = 'id1'; const id2 = 'id2'; it('should perform a simple merge', async () => { render( <ContactMergingContent // userKeysList={[]} mergeFinished={false} beMergedModel={{ [id1]: [id1, id2] }} beDeletedModel={{}} totalBeMerged={1} totalBeDeleted={1} onFinish={jest.fn()} /> ); const apiMock = useApi() as jest.Mock; await waitFor(() => { expect(apiMock).toHaveBeenCalledTimes(4); // 2 gets, 1 update, 1 delete }); const encryptedProps = encrypt.mock.calls[0][0]; expect(encryptedProps.nickname[0].field).toBe('nickname'); expect(encryptedProps.nickname[0].value).toBe(id1); expect(encryptedProps.nickname[1].field).toBe('nickname'); expect(encryptedProps.nickname[1].value).toBe(id2); const updateCall = apiMock.mock.calls[2]; expect(updateCall[0].data.Contacts[0].Cards[0]).toBe('something encrypted'); const deleteCall = apiMock.mock.calls[3]; expect(deleteCall[0].data.IDs).toEqual([id2]); }); });
6,082
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/ContactMergingContent.tsx
import { useEffect, useMemo, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { addContacts, deleteContacts, getContact } from '@proton/shared/lib/api/contacts'; import { getApiWithAbort } from '@proton/shared/lib/api/helpers/customConfig'; import { processApiRequestsSafe } from '@proton/shared/lib/api/helpers/safeApiRequests'; import { API_CODES } from '@proton/shared/lib/constants'; import { ADD_CONTACTS_MAX_SIZE, API_SAFE_INTERVAL, CATEGORIES, OVERWRITE } from '@proton/shared/lib/contacts/constants'; import { prepareVCardContact as decrypt } from '@proton/shared/lib/contacts/decrypt'; import { prepareVCardContact as encrypt } from '@proton/shared/lib/contacts/encrypt'; import { splitEncryptedContacts } from '@proton/shared/lib/contacts/helpers/import'; import { merge } from '@proton/shared/lib/contacts/helpers/merge'; import { combineProgress } from '@proton/shared/lib/contacts/helpers/progress'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Contact as ContactType, SimpleEncryptedContact } from '@proton/shared/lib/interfaces/contacts'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { splitKeys } from '@proton/shared/lib/keys/keys'; import chunk from '@proton/utils/chunk'; import { Alert, DynamicProgress, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components'; import { useApi, useUserKeys } from '../../../hooks'; const { OVERWRITE_CONTACT } = OVERWRITE; const { INCLUDE, IGNORE } = CATEGORIES; const { SINGLE_SUCCESS } = API_CODES; type Signal = { signal: AbortSignal }; interface Props { alreadyMerged?: VCardContact; mergeFinished: boolean; onFinish: () => void; onMerged?: () => void; onClose?: () => void; beMergedModel: { [ID: string]: string[] }; beDeletedModel: { [ID: string]: string }; totalBeMerged: number; totalBeDeleted: number; } const ContactMergingContent = ({ alreadyMerged, mergeFinished, onFinish, onMerged, onClose, beMergedModel = {}, beDeletedModel = {}, totalBeMerged = 0, totalBeDeleted = 0, }: Props) => { const api = useApi(); const [userKeysList] = useUserKeys(); const { privateKeys, publicKeys } = useMemo(() => splitKeys(userKeysList), [userKeysList]); const [loading, withLoading] = useLoading(true); const [model, setModel] = useState<{ mergedAndEncrypted: string[]; failedOnMergeAndEncrypt: string[]; submitted: string[]; failedOnSubmit: string[]; deleted: string[]; }>({ mergedAndEncrypted: [], failedOnMergeAndEncrypt: [], submitted: [], failedOnSubmit: [], deleted: [], }); const isDeleteOnly = totalBeMerged <= 0 && totalBeDeleted > 0; useEffect(() => { // Prepare api for allowing cancellation in the middle of the merge const abortController = new AbortController(); const apiWithAbort = getApiWithAbort(api, abortController.signal); /** * Get a contact from its ID and decrypt it. Return contact as a list of properties */ const getDecryptedContact = async (ID: string, { signal }: Signal): Promise<VCardContact> => { if (signal.aborted) { return { fn: [] }; } const { Contact } = await apiWithAbort<{ Contact: ContactType }>(getContact(ID)); const { vCardContact, errors: contactErrors } = await decrypt(Contact, { privateKeys, publicKeys, }); if (contactErrors.length) { throw new Error(`Error decrypting contact ${ID}`); } return vCardContact; }; /** * Get and decrypt a group of contacts to be merged. Return array of decrypted contacts */ const getDecryptedGroup = (groupIDs: string[] = [], { signal }: Signal) => { return processApiRequestsSafe( groupIDs.map((ID) => () => getDecryptedContact(ID, { signal })), 3, 1000 ); }; /** * Encrypt a contact already merged. Useful for the case of `preview merge` */ const encryptAlreadyMerged = async ({ signal }: Signal) => { if (signal.aborted) { return []; } // beMergedModel only contains one entry in this case const [[beMergedID, groupIDs]] = Object.entries(beMergedModel); const beSubmittedContacts: SimpleEncryptedContact[] = []; if (!alreadyMerged) { throw new Error('Contact already merged is undefined'); } try { const encryptedMergedContact = await encrypt(alreadyMerged, { privateKey: privateKeys[0], publicKey: publicKeys[0], }); beSubmittedContacts.push({ contact: encryptedMergedContact, contactId: beMergedID }); if (!signal.aborted) { setModel((model) => ({ ...model, mergedAndEncrypted: [...model.mergedAndEncrypted, ...groupIDs] })); } } catch { if (!signal.aborted) { setModel((model) => ({ ...model, failedOnMergeAndEncrypt: [...model.failedOnMergeAndEncrypt, ...groupIDs], })); } } return beSubmittedContacts; }; /** * Merge groups of contacts characterized by their ID. Return the encrypted merged contacts * to be submitted plus the IDs of the contacts to be deleted after the merge */ const mergeAndEncrypt = async ({ signal }: Signal) => { const beSubmittedContacts: SimpleEncryptedContact[] = []; for (const [beMergedID, groupIDs] of Object.entries(beMergedModel)) { if (signal.aborted) { return []; } try { const decryptedGroup = await getDecryptedGroup(groupIDs, { signal }); const encryptedMergedContact = await encrypt(merge(decryptedGroup), { privateKey: privateKeys[0], publicKey: publicKeys[0], }); beSubmittedContacts.push({ contact: encryptedMergedContact, contactId: beMergedID }); if (!signal.aborted) { setModel((model) => ({ ...model, mergedAndEncrypted: [...model.mergedAndEncrypted, ...groupIDs], })); } } catch (error) { if (!signal.aborted) { setModel((model) => ({ ...model, failedOnMergeAndEncrypt: [...model.failedOnMergeAndEncrypt, ...groupIDs], })); } } } return beSubmittedContacts; }; /** * Submit a batch of merged contacts to the API */ const submitBatch = async ( { contacts = [], labels }: { contacts: SimpleEncryptedContact[]; labels: number }, { signal }: Signal ) => { if (signal.aborted || !contacts.length) { return; } const beDeletedBatchIDs = []; const responses = ( await apiWithAbort<{ Responses: { Response: { Code: number; Contact?: ContactType } }[] }>( addContacts({ Contacts: contacts.map(({ contact }) => contact), Overwrite: OVERWRITE_CONTACT, Labels: labels, }) ) ).Responses.map(({ Response }: any) => Response); if (signal.aborted) { return; } for (const [index, { Code }] of responses.entries()) { const ID = contacts[index].contactId; const groupIDs = beMergedModel[ID]; const beDeletedAfterMergeIDs = groupIDs.slice(1); if (Code === SINGLE_SUCCESS) { if (!signal.aborted) { setModel((model) => ({ ...model, submitted: [...model.submitted, ...groupIDs] })); } beDeletedBatchIDs.push(...beDeletedAfterMergeIDs); } else if (!signal.aborted) { setModel((model) => ({ ...model, failedOnSubmit: [...model.failedOnSubmit, ...groupIDs] })); } } if (!signal.aborted && !!beDeletedBatchIDs.length) { await apiWithAbort(deleteContacts(beDeletedBatchIDs)); } }; /** * Submit all merged contacts to the API */ const submitContacts = async ( { contacts = [], labels }: { contacts: SimpleEncryptedContact[]; labels: number }, { signal }: Signal ) => { if (signal.aborted) { return; } // divide contacts and indexMap in batches const contactBatches = chunk(contacts, ADD_CONTACTS_MAX_SIZE); const apiCalls = contactBatches.length; for (let i = 0; i < apiCalls; i++) { // avoid overloading API in the case submitBatch is too fast await Promise.all([ submitBatch({ contacts: contactBatches[i], labels }, { signal }), // tripling the safe interval as there are reports of hitting jails on production (the proper solution would be a dynamic rate) wait(3 * API_SAFE_INTERVAL), ]); } }; /** * Delete contacts marked for deletion */ const deleteMarkedForDeletion = async ({ signal }: Signal) => { const beDeletedIDs = Object.keys(beDeletedModel); if (!signal.aborted && !!beDeletedIDs.length) { setModel((model) => ({ ...model, deleted: [...model.deleted, ...beDeletedIDs] })); await apiWithAbort(deleteContacts(beDeletedIDs)); } }; /** * All steps of the merge process */ const mergeContacts = async ({ signal }: Signal) => { const beSubmittedContacts = !alreadyMerged ? await mergeAndEncrypt({ signal }) : await encryptAlreadyMerged({ signal }); const { withCategories, withoutCategories } = splitEncryptedContacts(beSubmittedContacts); await submitContacts({ contacts: withCategories, labels: INCLUDE }, { signal }); await submitContacts({ contacts: withoutCategories, labels: IGNORE }, { signal }); await deleteMarkedForDeletion({ signal }); if (!signal.aborted) { onFinish(); } }; void withLoading(mergeContacts(abortController)); return () => { abortController.abort(); }; }, []); // Allocate 90% of the progress to merging and encrypting, 10% to sending to API const combinedProgress = combineProgress([ { allocated: 0.9, successful: model.mergedAndEncrypted.length, failed: model.failedOnMergeAndEncrypt.length, total: totalBeMerged, }, { allocated: 0.1, successful: model.submitted.length, failed: model.failedOnSubmit.length, total: totalBeMerged - model.failedOnMergeAndEncrypt.length, }, ]); const successDelete = model.deleted.length === totalBeDeleted; const successMerge = model.failedOnMergeAndEncrypt.length + model.failedOnSubmit.length !== totalBeMerged; const progressMessage = c('Progress bar description').t`Progress: ${combinedProgress}%`; let endMessage; if (successDelete && !successMerge) { endMessage = c('Progress bar description').ngettext( msgid`${model.deleted.length} out of ${totalBeDeleted} contact successfully deleted.`, `${model.deleted.length} out of ${totalBeDeleted} contacts successfully deleted.`, totalBeDeleted ); } else if (successMerge) { endMessage = c('Progress bar description').ngettext( msgid`${model.submitted.length} out of ${totalBeMerged} contact successfully merged.`, `${model.submitted.length} out of ${totalBeMerged} contacts successfully merged.`, totalBeMerged ); } else { endMessage = c('Progress bar description').t`No contacts merged.`; } return ( <> <ModalTwoHeader title={isDeleteOnly ? c('Title').t`Deleting contacts` : c('Title').t`Merging contacts`} /> <ModalTwoContent> <Alert className="mb-4"> {totalBeMerged > 0 ? c('Description') .t`Merging contacts... This may take a few minutes. When the process is completed, you can close this modal.` : c('Description') .t`Deleting contacts... This may take a few minutes. When the process is completed, you can close this modal.`} </Alert> <DynamicProgress id="progress-merge-contacts" loading={loading} value={combinedProgress} max={100} success={successMerge || successDelete} display={loading ? progressMessage : endMessage} data-testid="merge-model:progress-merge-contacts" /> </ModalTwoContent> <ModalTwoFooter> {!mergeFinished && <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>} <Button color="norm" loading={!mergeFinished} onClick={onMerged} data-testid="merge-model:close-button" className="ml-auto" > {c('Action').t`Close`} </Button> </ModalTwoFooter> </> ); }; export default ContactMergingContent;
6,083
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/table/EmailsTableCell.tsx
import clsx from '@proton/utils/clsx'; interface Props { emails: string[]; contactID: string; highlightedID: string; greyedOut: boolean; } const EmailsTableCell = ({ contactID, emails = [], highlightedID, greyedOut }: Props) => { return ( <div className={clsx([ 'flex', 'flex-align-items-center', 'max-w-full', greyedOut && 'color-weak', contactID === highlightedID && 'text-bold', ])} > <span className="inline-block text-ellipsis">{emails.map((email) => `<${email}>`).join(', ')}</span> </div> ); }; export default EmailsTableCell;
6,084
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/table/MergeTable.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ContactFormatted } from '@proton/shared/lib/interfaces/contacts'; import { Block, OrderableTable, TableCell } from '../../../../components'; import MergeTableBody from './MergeTableBody'; import '../../../../components/orderableTable/OrderableTableHeader.scss'; const MergeTableHeader = () => { return ( <thead className="orderableTableHeader"> <tr> <TableCell type="header"> </TableCell> <TableCell type="header">{c('TableHeader').t`Display name`}</TableCell> <TableCell type="header" className="w-1/6">{c('TableHeader').t`First name`}</TableCell> <TableCell type="header" className="w-1/6">{c('TableHeader').t`Last name`}</TableCell> <TableCell type="header">{c('TableHeader').t`Address`}</TableCell> <TableCell type="header">{c('TableHeader').t`Actions`}</TableCell> </tr> </thead> ); }; interface Props { contacts: ContactFormatted[][]; isChecked: { [ID: string]: boolean }; beDeleted: { [ID: string]: boolean }; onClickCheckbox: (ID: string) => void; onClickDetails: (ID: string) => void; onToggleDelete: (ID: string) => void; onClickPreview: (beMergedID: string, beDeletedIDs: string[]) => void; onSortEnd: (groupIndex: number) => ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => void; } const MergeTable = ({ contacts = [], isChecked = {}, beDeleted = {}, onClickCheckbox, onClickDetails, onToggleDelete, onClickPreview, onSortEnd, }: Props) => { return ( <> {contacts.map((group, i) => { const activeIDs = group .map(({ ID }) => isChecked[ID] && !beDeleted[ID] && ID) .filter(Boolean) as string[]; const beDeletedIDs = group.map(({ ID }) => beDeleted[ID] && ID).filter(Boolean) as string[]; const beMergedIDs = activeIDs.length > 1 ? activeIDs : []; return ( <Block key={`${group && group[0].Name}`} className="mb-8 flex flex-column flex-align-items-center"> <OrderableTable onSortEnd={onSortEnd(i)} className="mb-4" helperClass="row--orderable"> <MergeTableHeader /> <MergeTableBody contacts={group} highlightedID={beMergedIDs[0]} isChecked={isChecked} beDeleted={beDeleted} onClickCheckbox={onClickCheckbox} onClickDetails={onClickDetails} onToggleDelete={onToggleDelete} /> </OrderableTable> <Button className="aligcenter" disabled={!beMergedIDs.length} type="button" onClick={() => onClickPreview(beMergedIDs[0], beDeletedIDs)} data-testid="merge-model:preview-contact-button" > {c('Action').t`Preview contact`} </Button> </Block> ); })} </> ); }; export default MergeTable;
6,085
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/table/MergeTableBody.tsx
import { ComponentProps, useEffect, useRef, useState } from 'react'; import { ContactFormatted } from '@proton/shared/lib/interfaces/contacts'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { OrderableTableBody } from '../../../../components'; import MergeTableBodyRow from './MergeTableBodyRow'; interface Props extends Omit<ComponentProps<typeof OrderableTableBody>, 'colSpan'> { contacts: ContactFormatted[]; vcardContacts?: VCardContact[]; highlightedID: string; isChecked: { [ID: string]: boolean }; beDeleted: { [ID: string]: boolean }; onClickCheckbox: (ID: string) => void; onClickDetails: (ID: string) => void; onToggleDelete: (ID: string) => void; } const MergeTableBody = ({ contacts, highlightedID, isChecked, beDeleted, onClickCheckbox, onClickDetails, onToggleDelete, ...rest }: Props) => { const ref = useRef<any>(null); const observerRef = useRef<IntersectionObserver | null>(null); const [isIntersecting, setIsIntersecting] = useState(false); useEffect(() => { observerRef.current = new IntersectionObserver(([entry]) => setIsIntersecting(entry.isIntersecting)); }, []); useEffect(() => { if (!observerRef.current || !ref.current) { return; } observerRef.current.observe(ref.current?.node); return () => { if (observerRef.current) { observerRef.current.disconnect(); } }; }, [ref]); return ( <OrderableTableBody colSpan={4} {...rest} data-testid="merge-model:merge-table"> {contacts.map((Contact, i) => ( <MergeTableBodyRow ref={ref} index={i} key={Contact.ID} ID={Contact.ID} Contact={Contact} highlightedID={highlightedID} isChecked={isChecked} beDeleted={beDeleted} onClickCheckbox={onClickCheckbox} onClickDetails={onClickDetails} onToggleDelete={onToggleDelete} isIntersecting={isIntersecting} /> ))} </OrderableTableBody> ); }; export default MergeTableBody;
6,086
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/table/MergeTableBodyRow.tsx
import { ComponentProps, Ref, forwardRef } from 'react'; import { c } from 'ttag'; import { useUserKeys } from '@proton/components/hooks/useUserKeys'; import { ContactFormatted } from '@proton/shared/lib/interfaces/contacts'; import { DropdownActions, OrderableTableBody, OrderableTableRow, TableRow } from '../../../../components'; import useContactConditionally from '../../hooks/useContactConditionally'; import useVCardContact from '../../hooks/useVCardContact'; import EmailsTableCell from './EmailsTableCell'; import NameTableCell from './NameTableCell'; interface Props extends Omit<ComponentProps<typeof OrderableTableBody>, 'colSpan'> { index: number; ID: string; Contact: ContactFormatted; highlightedID: string; isChecked: { [ID: string]: boolean }; beDeleted: { [ID: string]: boolean }; onClickCheckbox: (ID: string) => void; onClickDetails: (ID: string) => void; onToggleDelete: (ID: string) => void; isIntersecting: boolean; } const MergeTableBodyRow = ( { index, ID, Contact, highlightedID, isChecked, beDeleted, onClickCheckbox, onClickDetails, onToggleDelete, isIntersecting, }: Props, ref: Ref<any> ) => { const { Name, emails } = Contact; const [userKeysList] = useUserKeys(); // Allow to control when we fetch contacts and avoid fetching them when the row is not visible const [contact] = useContactConditionally(isIntersecting ? ID : undefined); const { vCardContact } = useVCardContact({ contact, userKeysList }); const deleted = beDeleted[ID]; const options = [ !deleted && { text: c('Action').t`View`, onClick() { onClickDetails(ID); }, }, { text: deleted ? c('Action').t`Unmark for deletion` : c('Action').t`Mark for deletion`, onClick() { onToggleDelete(ID); }, }, ].filter(Boolean) as { text: string; onClick: () => void }[]; const givenName = vCardContact?.n?.value.givenNames?.join(' ')?.trim() ?? '-'; const familyName = vCardContact?.n?.value.familyNames?.join(' ')?.trim() ?? '-'; const cells = [ <NameTableCell key="displayName" name={Name} contactID={ID} highlightedID={highlightedID} checked={isChecked[ID]} deleted={deleted} greyedOut={deleted} onToggle={onClickCheckbox} />, <span className="max-w-full inline-block text-ellipsis">{givenName}</span>, <span className="max-w-full inline-block text-ellipsis">{familyName}</span>, <EmailsTableCell key="email" contactID={ID} highlightedID={highlightedID} emails={emails} greyedOut={deleted} />, <DropdownActions key="options" size="small" list={options} data-testid="merge-model:action-button" />, ]; return deleted ? ( <TableRow key={`${ID}`} cells={[null, ...cells]} /> ) : ( <OrderableTableRow key={`${ID}`} index={index} cells={cells} ref={ref} /> ); }; export default forwardRef(MergeTableBodyRow);
6,087
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/merge/table/NameTableCell.tsx
import clsx from '@proton/utils/clsx'; import { Checkbox } from '../../../../components'; interface Props { contactID: string; highlightedID: string; checked: boolean; deleted: boolean; greyedOut: boolean; name: string; onToggle: (ID: string) => void; } const NameTableCell = ({ name, contactID, highlightedID, checked, deleted, greyedOut, onToggle }: Props) => { const handleToggle = () => onToggle(contactID); return ( <div className="flex flex-nowrap flex-align-items-center"> <Checkbox checked={checked} onChange={handleToggle} className={`flex flex-align-items-center flex-item-noshrink mr-2 ${deleted ? 'visibility-hidden' : ''}`} data-testid="merge-model:name-checkbox" /> <span className={clsx([ 'max-w-full', 'inline-block', 'text-ellipsis', greyedOut && 'color-weak', contactID === highlightedID && 'text-bold', ])} > {name} </span> </div> ); }; export default NameTableCell;
6,088
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactClearDataConfirmModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button, Input } from '@proton/atoms'; import { Key } from '@proton/shared/lib/interfaces'; import { Alert, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Row } from '../../../components'; import { ContactClearDataExecutionProps } from './ContactClearDataExecutionModal'; export interface ContactClearDataConfirmProps { errorKey: Key; } export interface ContactClearDataConfirmModalProps { onClearData: (props: ContactClearDataExecutionProps) => void; } type Props = ContactClearDataConfirmProps & ContactClearDataConfirmModalProps & ModalProps; const ContactClearDataConfirmModal = ({ errorKey, onClearData, ...rest }: Props) => { const [dangerInput, setDangerInput] = useState(''); const dangerWord = 'DANGER'; const handleSubmit = () => { onClearData({ errorKey }); rest.onClose?.(); }; const boldDanger = <strong key="danger">{dangerWord}</strong>; return ( <ModalTwo {...rest}> <ModalTwoHeader title={c('Title').t`Warning`} /> <ModalTwoContent> <Alert className="mb-4" type="info">{c('Warning') .t`If you don’t remember your password, it is impossible to re-activate your key. We can help you dismiss the alert banner but in the process you will permanently lose access to all the data encrypted with that key.`}</Alert> <Alert className="mb-4" type="error"> {c('Warning') .jt`This action is irreversible. Please enter the word ${boldDanger} in the field to proceed.`} </Alert> <Row> <Input value={dangerInput} placeholder={dangerWord} onChange={(event) => setDangerInput(event.target.value)} /> </Row> </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose}>{c('Action').t`Cancel`}</Button> <Button color="danger" disabled={dangerInput !== dangerWord} onClick={handleSubmit}>{c('Action') .t`Clear data`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactClearDataConfirmModal;
6,089
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactClearDataExecutionModal.tsx
import { useEffect, useRef, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { dropDataEncryptedWithAKey } from '@proton/shared/lib/contacts/globalOperations'; import { Key } from '@proton/shared/lib/interfaces'; import { Alert, DynamicProgress, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, } from '../../../components'; import { useApi, useContacts, useEventManager, useUserKeys } from '../../../hooks'; export interface ContactClearDataExecutionProps { errorKey: Key; } type Props = ContactClearDataExecutionProps & ModalProps; const ContactClearDataExecutionModal = ({ errorKey, ...rest }: Props) => { const [contacts = [], loadingContacts] = useContacts(); const api = useApi(); const { call } = useEventManager(); const [userKeys] = useUserKeys(); const [progress, setProgress] = useState(0); const [updated, setUpdated] = useState(0); const [closing, setClosing] = useState(false); const [execution, setExecution] = useState(true); const exitRef = useRef(false); const max = contacts.length; useEffect(() => { if (loadingContacts) { return; } const execute = async () => { await dropDataEncryptedWithAKey( contacts, errorKey, userKeys, api, (progress, updated) => { setProgress(progress); setUpdated(updated); }, exitRef ); await call(); setExecution(false); }; void execute(); }, [loadingContacts]); // Delayed closing not to leave ongoing process useEffect(() => { if (closing && !execution) { rest.onClose?.(); } }, [closing, execution]); const handleClose = () => { exitRef.current = true; setClosing(true); }; return ( <ModalTwo {...rest}> <ModalTwoHeader title={c('Title').t`Clearing data`} /> <ModalTwoContent> <Alert className="mb-4" type="info">{c('Info') .t`Please wait while we look for contacts that contain data encrypted with the inactive key.`}</Alert> <DynamicProgress id="clear-data-execution-progress" value={progress} display={ execution ? c('Info').t`Checking contact ${progress} of ${max}...` : c('Info').ngettext( msgid`${updated} contact updated successfully.`, `${updated} contacts updated successfully.`, updated ) } max={max} loading={execution} /> </ModalTwoContent> <ModalTwoFooter> {execution ? <Button onClick={handleClose}>{c('Action').t`Cancel`}</Button> : null} <Button color="norm" disabled={execution} onClick={rest.onClose}>{c('Action').t`Done`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactClearDataExecutionModal;
6,090
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactDecryptionErrorModal.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { APPS } from '@proton/shared/lib/constants'; import { getKeyUsedForContact } from '@proton/shared/lib/contacts/keyVerifications'; import { Key } from '@proton/shared/lib/interfaces'; import { Contact } from '@proton/shared/lib/interfaces/contacts'; import { Alert, Copy, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, UnderlineButton, useSettingsLink, } from '../../../components'; import { useNotifications, useUser } from '../../../hooks'; import useContact from '../hooks/useContact'; import { ContactClearDataConfirmProps } from './ContactClearDataConfirmModal'; export interface ContactDecryptionErrorProps { contactID: string; } export interface ContactDecryptionErrorModalProps { onClearDataConfirm: (props: ContactClearDataConfirmProps) => void; } type Props = ContactDecryptionErrorProps & ContactDecryptionErrorModalProps & ModalProps; const ContactDecryptionErrorModal = ({ contactID, onClearDataConfirm, ...rest }: Props) => { const { createNotification } = useNotifications(); const [user] = useUser(); const [contact] = useContact(contactID) as [Contact | undefined, boolean, Error]; const [errorKey, setErrorKey] = useState<Key>(); const goToSettings = useSettingsLink(); useEffect(() => { const findKey = async () => { const key = await getKeyUsedForContact(contact as Contact, user.Keys, true); setErrorKey(key); }; if (user && contact) { void findKey(); } }, [user, contact]); const handleSubmit = () => { goToSettings('/encryption-keys', APPS.PROTONMAIL); }; const handleClear = () => { onClearDataConfirm({ errorKey: errorKey as Key }); rest.onClose?.(); }; return ( <ModalTwo {...rest}> <ModalTwoHeader title={c('Title').t`Recover data`} /> <ModalTwoContent> <Alert className="mb-4" type="info"> {c('Info') .t`To recover your data, you need to re-activate the account key used at the time when the data was created. This will require you to remember the password used when the key was generated.`} </Alert> {errorKey && ( <div className="flex flex-align-items-center mb-4"> <span className="mr-4">{c('Info').t`Key fingerprint`}</span> <span className="flex-item-fluid text-ellipsis mr-4">{errorKey.Fingerprint}</span> <Copy value={errorKey.Fingerprint} onCopy={() => { createNotification({ text: c('Success').t`Fingerprint copied to clipboard` }); }} /> </div> )} <Alert className="mb-4" type="info"> {c('Info') .t`Cannot remember your password? We can help you clear the encrypted data of all contacts encrypted with this key and in the process dismiss the alert.`} <UnderlineButton className="ml-2" onClick={handleClear} disabled={!errorKey}> {c('Action').t`Click here.`} </UnderlineButton> </Alert> </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose}>{c('Action').t`Close`}</Button> <Button color="norm" onClick={handleSubmit}>{c('Action').t`Recover data`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactDecryptionErrorModal;
6,091
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactDeleteModal.tsx
import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { clearContacts, deleteContacts } from '@proton/shared/lib/api/contacts'; import { allSucceded } from '@proton/shared/lib/api/helpers/response'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Contact } from '@proton/shared/lib/interfaces/contacts'; import { Alert, ErrorButton, ModalProps, Prompt } from '../../../components'; import { useApi, useContacts, useEventManager, useNotifications } from '../../../hooks'; export interface ContactDeleteProps { contactIDs: string[]; deleteAll?: boolean; onDelete?: () => void; } type Props = ContactDeleteProps & ModalProps; const ContactDeleteModal = ({ contactIDs = [], deleteAll, onDelete, ...rest }: Props) => { const api = useApi(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [loadingDelete, withLoadingDelete] = useLoading(); const [contacts = []] = useContacts(); const handleDelete = async () => { // Call the callback and close the modal and wait a bit to trigger the event manager // In order eventual contact view can be closed and will not try to request the contact const delayedClosing = async () => { onDelete?.(); rest.onClose?.(); await wait(1000); await call(); }; if (deleteAll) { await api(clearContacts()); void delayedClosing(); return createNotification({ text: c('Success').t`Contacts deleted` }); } const apiSuccess = allSucceded(await api(deleteContacts(contactIDs))); void delayedClosing(); if (!apiSuccess) { return createNotification({ text: c('Error').t`Some contacts could not be deleted`, type: 'warning' }); } createNotification({ text: c('Success').ngettext(msgid`Contact deleted`, `Contacts deleted`, contactIDs.length), }); }; const count = contactIDs.length; const contact = contacts.find((contact: Contact) => contact.ID === contactIDs[0]); const Name = contact?.Name || contact?.ContactEmails?.[0]?.Email || ''; const title = count === 1 ? c('Title').t`Delete ${Name}` : c('Title').ngettext(msgid`Delete ${count} contact`, `Delete ${count} contacts`, count); const text = count === 1 ? c('Warning').t`Are you sure you want to permanently delete this contact?` : c('Warning').ngettext( msgid`Are you sure you want to permanently delete ${count} contact?`, `Are you sure you want to permanently delete ${count} contacts?`, count ); return ( <Prompt title={ <div className="text-ellipsis" title={title}> {title} </div> } buttons={[ <ErrorButton data-testid="delete-button" onClick={() => withLoadingDelete(handleDelete())} loading={loadingDelete} >{c('Action').t`Delete`}</ErrorButton>, <Button onClick={rest.onClose} autoFocus>{c('Action').t`Cancel`}</Button>, ]} {...rest} > <Alert className="mb-4" type="error"> {text} </Alert> </Prompt> ); }; export default ContactDeleteModal;
6,092
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactExportingModal.test.tsx
import { fireEvent } from '@testing-library/react'; import { CryptoProxy } from '@proton/crypto'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import { STATUS } from '@proton/shared/lib/models/cache'; import { api, cache, clearAll, minimalCache, mockedCryptoApi, prepareContact, render } from '../tests/render'; import ContactExportingModal, { ContactExportingProps } from './ContactExportingModal'; jest.mock('@proton/shared/lib/helpers/downloadFile', () => { return jest.fn(); }); describe('ContactExportingModal', () => { const props: ContactExportingProps = { contactGroupID: 'contactGroupID', onSave: jest.fn(), }; const contact1 = { ID: 'ContactID1', LabelIDs: [props.contactGroupID], }; const vcard1 = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN:J. Doe EMAIL:jdoe@example.com TEL:testtel END:VCARD`; const contact2 = { ID: 'ContactID2', LabelIDs: [props.contactGroupID], }; const vcard2 = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b2 FN:Jane Doe EMAIL:janedoe@example.com TEL:testteltt END:VCARD`; beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should export two contacts', async () => { const { Cards: Cards1 } = await prepareContact(vcard1); const { Cards: Cards2 } = await prepareContact(vcard2); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts/export') { return { Contacts: [ { ID: contact1.ID, Cards: Cards1 }, { ID: contact2.ID, Cards: Cards2 }, ], }; } }); minimalCache(); cache.set('Contacts', { status: STATUS.RESOLVED, value: [contact1, contact2] }); const { findByText, getByText } = render(<ContactExportingModal open={true} {...props} />, false); await findByText('2 out of 2', { exact: false }); const saveButton = getByText('Save'); fireEvent.click(saveButton); expect(downloadFile).toHaveBeenCalled(); const args = (downloadFile as jest.Mock).mock.calls[0]; const blob = args[0] as Blob; const content = await new Promise((resolve) => { var reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.readAsText(blob); }); const expected = `BEGIN:VCARD\r\nVERSION:4.0\r\nFN;PREF=1:J. Doe\r\nTEL;PREF=1:testtel\r\nUID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1\r\nITEM1.EMAIL;PREF=1:jdoe@example.com\r\nEND:VCARD\r\nBEGIN:VCARD\r\nVERSION:4.0\r\nFN;PREF=1:Jane Doe\r\nTEL;PREF=1:testteltt\r\nUID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b2\r\nITEM1.EMAIL;PREF=1:janedoe@example.com\r\nEND:VCARD`; expect(content).toBe(expected); }); });
6,093
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactExportingModal.tsx
import { useEffect, useState } from 'react'; import { format } from 'date-fns'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { exportContactsFromLabel } from '@proton/shared/lib/contacts/helpers/export'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import noop from '@proton/utils/noop'; import { Alert, DynamicProgress, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, } from '../../../components'; import { useApi, useContacts, useUserKeys } from '../../../hooks'; const DOWNLOAD_FILENAME = 'protonContacts'; export interface ContactExportingProps { contactGroupID?: string; onSave?: () => void; } type Props = ContactExportingProps & ModalProps; const ContactExportingModal = ({ contactGroupID: LabelID, onSave = noop, ...rest }: Props) => { const api = useApi(); const [contacts = [], loadingContacts] = useContacts(); const [userKeysList, loadingUserKeys] = useUserKeys(); const [contactsExported, addSuccess] = useState<string[]>([]); const [contactsNotExported, addError] = useState<string[]>([]); const countContacts = LabelID ? contacts.filter(({ LabelIDs = [] }) => LabelIDs.includes(LabelID)).length : contacts.length; const handleSave = (vcards: string[]) => { const allVcards = vcards.join('\r\n'); const blob = new Blob([allVcards], { type: 'text/plain;charset=utf-8' }); downloadFile(blob, `${DOWNLOAD_FILENAME}-${format(Date.now(), 'yyyy-MM-dd')}.vcf`); onSave(); rest.onClose?.(); }; useEffect(() => { if (loadingContacts || loadingUserKeys) { return; } const abortController = new AbortController(); exportContactsFromLabel( LabelID, countContacts, userKeysList, abortController.signal, api, (contactExported) => addSuccess((contactsExported) => [...contactsExported, contactExported]), (ID) => addError((contactsNotExported) => [...contactsNotExported, ID]) ).catch((error) => { if (error.name !== 'AbortError') { rest.onClose?.(); // close the modal; otherwise it is left hanging in there throw error; } }); return () => { abortController.abort(); }; }, [loadingContacts, loadingUserKeys]); const success = contactsNotExported.length !== countContacts; const loading = loadingContacts || contactsExported.length + contactsNotExported.length !== countContacts; const display = loading || success ? c('Progress bar description').ngettext( msgid`${contactsExported.length} out of ${countContacts} contact successfully exported.`, `${contactsExported.length} out of ${countContacts} contacts successfully exported.`, countContacts ) : c('Progress bar description').t`No contacts exported.`; return ( <ModalTwo {...rest}> <ModalTwoHeader title={c('Title').t`Exporting contacts`} /> <ModalTwoContent> <Alert className="mb-4"> {c('Description') .t`Decrypting contacts… This may take a few minutes. When the process is completed, you will be able to download the file with all your contacts exported.`} </Alert> <DynamicProgress id="progress-export-contacts" loading={loading} value={contactsExported.length + contactsNotExported.length} max={countContacts} success={success} display={loadingContacts ? '' : display} /> </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" disabled={loading} onClick={() => handleSave(contactsExported)}> {c('Action').t`Save`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactExportingModal;
6,094
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactGroupLimitReachedModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { ModalProps, Prompt } from '@proton/components/components'; import { useContactGroups } from '@proton/components/hooks'; import { ContactGroup } from '@proton/shared/lib/interfaces/contacts'; const getContactGroupsNames = (groupIDs: string[], contactGroups: ContactGroup[]) => { return contactGroups.filter((contactGroup) => groupIDs.includes(contactGroup.ID)); }; export interface ContactGroupLimitReachedProps { groupIDs?: string[]; } type Props = ContactGroupLimitReachedProps & ModalProps; const ContactGroupLimitReachedModal = ({ groupIDs, ...rest }: Props) => { const [groups = []] = useContactGroups(); const onClose = rest.onClose; const text = groupIDs && groupIDs?.length > 0 ? c('Info').t`You've reached the maximum number of addresses in the contact group(s):` : c('Info').t`You've reached the maximum number of addresses in the contact group.`; return ( <Prompt title={c('Title').t`Cannot add more addresses`} onClose={onClose} buttons={<Button onClick={onClose}>{c('Action').t`Close`}</Button>} {...rest} > <p>{text}</p> {groupIDs && groupIDs?.length > 0 && ( <ul> {getContactGroupsNames(groupIDs, groups).map((group) => ( <li key={group.ID}>{group.Name}</li> ))} </ul> )} </Prompt> ); }; export default ContactGroupLimitReachedModal;
6,095
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactImageModal.tsx
import { ChangeEvent, FormEvent, useCallback, useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button, Input } from '@proton/atoms'; import { CONTACT_IMG_SIZE } from '@proton/shared/lib/contacts/constants'; import { resizeImage } from '@proton/shared/lib/helpers/image'; import { isValidHttpUrl } from '@proton/shared/lib/helpers/url'; import debounce from '@proton/utils/debounce'; import { ErrorZone, Field, FileInput, Form, Label, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Row, } from '../../../components'; import { useNotifications } from '../../../hooks'; export interface ContactImageProps { url?: string; onSubmit: (image: string) => void; } enum ImageState { Initial, Error, Ok, } type Props = ContactImageProps & ModalProps; const ContactImageModal = ({ url: initialUrl = '', onSubmit, ...rest }: Props) => { const [imageUrl, setImageUrl] = useState(initialUrl); const [isPristine, setIsPristine] = useState(true); const { createNotification } = useNotifications(); const title = c('Title').t`Edit image`; const isBase64Str = imageUrl.startsWith('data:image'); const [imageState, setImageState] = useState(ImageState.Initial); const [isImageLoading, setIsImageLoading] = useState(false); const handleSuccess = () => { setImageState(ImageState.Ok); setIsImageLoading(false); }; const handleError = () => { setImageState(ImageState.Error); setIsImageLoading(false); }; // Check if the image url is valid const checkImageUrl = (url: string) => { if (!isValidHttpUrl(url)) { setImageState(ImageState.Error); } else { setIsImageLoading(true); const image = new Image(); image.onload = () => handleSuccess(); image.onerror = () => handleError(); image.src = url; } }; const debouncedCheckImage = useCallback( debounce((url) => { checkImageUrl(url); }, 200), [] ); useEffect(() => { if (imageUrl) { debouncedCheckImage(imageUrl); } }, [imageUrl]); const error = !isPristine && imageState !== ImageState.Ok ? c('Info').t`Not a valid URL` : undefined; const handleChange = (e: ChangeEvent<HTMLInputElement>) => { // Remove parameters from URL otherwise the image is broken const urlWithoutParams = e.target.value.split('?')[0]; setImageUrl(urlWithoutParams); }; const handleSubmit = (event: FormEvent) => { event.stopPropagation(); event.preventDefault(); onSubmit(imageUrl); rest.onClose?.(); }; const handleUpload = (e: ChangeEvent<HTMLInputElement>) => { const file = e.target.files ? e.target.files[0] : null; const reader = new FileReader(); if (!file) { return; } reader.onloadend = async () => { try { const base64str = await resizeImage({ original: `${reader.result}`, maxWidth: CONTACT_IMG_SIZE, maxHeight: CONTACT_IMG_SIZE, finalMimeType: 'image/jpeg', encoderOptions: 1, bigResize: true, }); onSubmit(base64str); rest.onClose?.(); } catch (error: any) { createNotification({ text: c('Error').t`Image upload failed`, type: 'error' }); throw error; } }; reader.readAsDataURL(file); }; return ( <ModalTwo as={Form} onSubmit={handleSubmit} className="contacts-modal" {...rest}> <ModalTwoHeader title={title} /> <ModalTwoContent> <Row> <Label htmlFor="contactImageModal-input-url">{c('Label').t`Add image URL`}</Label> <Field> <Input id="contactImageModal-input-url" value={isBase64Str ? '' : imageUrl} onChange={handleChange} onBlur={() => setIsPristine(false)} placeholder={c('Placeholder').t`Image URL`} error={!!error} /> {!!error ? <ErrorZone>{error}</ErrorZone> : null} </Field> </Row> <Row> <Label htmlFor="contactImageModal-input-file">{c('Label').t`Upload picture`}</Label> <Field> <FileInput id="contactImageModal-input-file" accept="image/*" onChange={handleUpload}>{c( 'Action' ).t`Upload picture`}</FileInput> </Field> </Row> </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit" disabled={imageState === ImageState.Error} loading={isImageLoading} >{c('Action').t`Save`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactImageModal;
6,096
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactResignExecutionModal.tsx
import { useEffect, useRef, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { resignAllContacts } from '@proton/shared/lib/contacts/globalOperations'; import { Alert, DynamicProgress, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, } from '../../../components'; import { useApi, useContacts, useEventManager, useUserKeys } from '../../../hooks'; const ContactResignExecutionModal = ({ ...rest }: ModalProps) => { const [contacts = [], loadingContacts] = useContacts(); const [userKeys] = useUserKeys(); const api = useApi(); const { call } = useEventManager(); const [progress, setProgress] = useState(0); const [updated, setUpdated] = useState(0); const [closing, setClosing] = useState(false); const [execution, setExecution] = useState(true); const exitRef = useRef(false); const max = contacts.length; useEffect(() => { if (loadingContacts) { return; } const execute = async () => { await resignAllContacts( contacts, userKeys, api, (progress, update) => { setProgress(progress); setUpdated(update); }, exitRef ); await call(); setExecution(false); }; void execute(); }, [loadingContacts]); // Delayed closing not to leave ongoing process useEffect(() => { if (closing && !execution) { rest.onClose?.(); } }, [closing, execution]); const handleClose = () => { exitRef.current = true; setClosing(true); }; return ( <ModalTwo {...rest}> <ModalTwoHeader title={c('Title').t`Re-signing contacts`} /> <ModalTwoContent> <Alert className="mb-4" type="info">{c('Info') .t`Please wait while we look for contacts that can be re-signed with the primary encryption key.`}</Alert> <DynamicProgress id="clear-data-execution-progress" value={progress} display={ execution ? c('Info').t`Checking contact ${progress} of ${max}...` : c('Info').ngettext( msgid`${updated} contact updated successfully.`, `${updated} contacts updated successfully.`, updated ) } max={max} loading={execution} /> </ModalTwoContent> <ModalTwoFooter> {execution ? <Button onClick={handleClose}>{c('Action').t`Cancel`}</Button> : null} <Button color="norm" disabled={execution} onClick={rest.onClose}>{c('Action').t`Done`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactResignExecutionModal;
6,097
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactSignatureErrorModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components'; export interface ContactSignatureErrorProps { contactID: string; } export interface ContactSignatureErrorModalProps { onResign: () => void; } type Props = ContactSignatureErrorProps & ContactSignatureErrorModalProps & ModalProps; const ContactSignatureErrorModal = ({ contactID, onResign, ...rest }: Props) => { const handleSubmit = () => { onResign(); rest.onClose?.(); }; return ( <ModalTwo size="small" {...rest}> <ModalTwoHeader title={c('Title').t`Re-sign all contacts`} /> <ModalTwoContent> <Alert className="mb-4" type="info">{c('Info') .t`To re-sign your contacts, we need to check every contact against the list of encryption keys available in your account. If no match is found, your contact will be re-signed with the primary encryption key.`}</Alert> <Alert className="mb-4" type="info">{c('Info') .t`Please note that this process may take some time depending on the size of your address book.`}</Alert> </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose}>{c('Action').t`Close`}</Button> <Button color="norm" onClick={handleSubmit}>{c('Action').t`Re-sign`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactSignatureErrorModal;
6,098
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/ContactUpgradeModal.tsx
import { c } from 'ttag'; import { useConfig } from '@proton/components/hooks'; import { SHARED_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell'; import { ModalStateProps, UpsellModal } from '../../../components'; const ContactUpgradeModal = (modalProps: ModalStateProps) => { const { APP_NAME } = useConfig(); const upsellRef = getUpsellRefFromApp({ app: APP_NAME, feature: SHARED_UPSELL_PATHS.CONTACT_GROUP, component: UPSELL_COMPONENT.MODAL, }) || ''; return ( <UpsellModal modalProps={modalProps} features={['more-storage', 'more-email-addresses', 'unlimited-folders-and-labels', 'custom-email-domains']} description={c('Description') .t`Save time by sending emails or invitations to everyone at once, a premium feature amongst many others. Upgrade today.`} title={c('Title').t`Unlock contacts groups`} upsellRef={upsellRef} /> ); }; export default ContactUpgradeModal;
6,099