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/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useSendVerifications.tsx
import { useCallback } from 'react'; import { c, msgid } from 'ttag'; import { useGetEncryptionPreferences, useModals, useNotifications } from '@proton/components'; import { serverTime } from '@proton/crypto'; import { HOUR } from '@proton/shared/lib/constants'; import { validateEmailAddress } from '@proton/shared/lib/helpers/email'; import { normalize } from '@proton/shared/lib/helpers/string'; import { languageCode, localeCode } from '@proton/shared/lib/i18n'; import { SendPreferences } from '@proton/shared/lib/interfaces/mail/crypto'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { EncryptionPreferencesError } from '@proton/shared/lib/mail/encryptionPreferences'; import { getRecipients, getRecipientsAddresses, isPlainText } from '@proton/shared/lib/mail/messages'; import getSendPreferences from '@proton/shared/lib/mail/send/getSendPreferences'; import unique from '@proton/utils/unique'; import SendWithChangedPreferencesModal, { PREFERENCE_CHANGE_TYPE, } from '../../components/composer/addresses/SendWithChangedPreferencesModal'; import SendWithErrorsModal from '../../components/composer/addresses/SendWithErrorsModal'; import SendWithExpirationModal from '../../components/composer/addresses/SendWithExpirationModal'; import SendWithWarningsModal from '../../components/composer/addresses/SendWithWarningsModal'; import { MESSAGE_ALREADY_SENT_INTERNAL_ERROR } from '../../constants'; import { removeMessageRecipients, uniqueMessageRecipients } from '../../helpers/message/cleanMessage'; import { locateBlockquote } from '../../helpers/message/messageBlockquote'; import { MessageStateWithData } from '../../logic/messages/messagesTypes'; import { MapSendInfo } from '../../models/crypto'; import { useContactsMap } from '../contact/useContacts'; import { useGetMessage } from '../message/useMessage'; const FR_REGEX = /voir pi\u00e8ce jointe|voir pi\u00e8ces jointes|voir fichier joint|voir fichiers joints|voir fichier associ\u00e9|voir fichiers associ\u00e9s|joint|joints|jointe|jointes|joint \u00e0 cet e-mail|jointe \u00e0 cet e-mail|joints \u00e0 cet e-mail|jointes \u00e0 cet e-mail|joint \u00e0 ce message|jointe \u00e0 ce message|joints \u00e0 ce message|jointes \u00e0 ce message|je joins|j'ai joint|ci-joint|pi\u00e8ce jointe|pi\u00e8ces jointes|fichier joint|fichiers joints|voir le fichier joint|voir les fichiers joints|voir la pi\u00e8ce jointe|voir les pi\u00e8ces jointes/gi; const EN_REGEX = /see attached|see attachment|see included|is attached|attached is|are attached|attached are|attached to this email|attached to this message|I'm attaching|I am attaching|I've attached|I have attached|I attach|I attached|find attached|find the attached|find included|find the included|attached file|see the attached|see attachments|attached files|see the attachment|here is the attachment|attached you will find/gi; const DE_REGEX = /siehe Anhang|angeh\u00e4ngt|anbei|hinzugef\u00fcgt|ist angeh\u00e4ngt|angeh\u00e4ngt ist|sind angeh\u00e4ngt|angeh\u00e4ngt sind|an diese E-Mail angeh\u00e4ngt|an diese Nachricht angeh\u00e4ngt|Anhang hinzuf\u00fcgen|Anhang anbei|Anhang hinzugef\u00fcgt|anbei finden|anbei|im Anhang|mit dieser E-Mail sende ich|angeh\u00e4ngte Datei|siehe angeh\u00e4ngte Datei|siehe Anh\u00e4nge|angeh\u00e4ngte Dateien|siehe Anlage|siehe Anlagen/gi; const ES_REGEX = /ver adjunto|ver archivo adjunto|ver archivo incluido|se ha adjuntado|adjuntado|se han adjuntado|adjuntados|se ha adjuntado a este correo|se ha adjuntado a este mensaje|Adjunto te env\u00edo|He adjuntado|He adjuntado un archivo|adjunto|adjunto el archivo|incluyo el archivo|archivo adjunto|mira el archivo adjunto|ver archivos adjuntos|archivos adjuntos|ver el archivo adjunto/gi; const RU_REGEX = /прикрепленный файл|прикреплённый файл|прикреплен|прикреплён|прикрепил|прикрепила/gi; const IT_REGEX = /vedi in allegato|vedi allegato|vedi accluso|\u00e8 allegato|in allegato|sono allegati|in allegato vi sono|in allegato a questa email|in allegato a questo messaggio|invio in allegato|allego|ho allegato|in allegato trovi|trova in allegato|trova accluso|incluso troverai|file allegato|vedi allegato|vedi allegati|file allegati|vedi l'allegato|ti allego/gi; const PT_PT_REGEX = /ver em anexo|ver anexo|ver inclu\u00eddo|est\u00e1 anexado|est\u00e1 em anexo|est\u00e3o anexados|est\u00e3o em anexo|anexado a este email|anexado a esta mensagem|estou a anexar|anexo|anexei|anexei|anexo|anexei|queira encontrar em anexo|segue em anexo|encontra-se inclu\u00eddo|segue inclu\u00eddo|ficheiro anexado|ver o anexo|ver anexos|ficheiros anexados|ver o anexo/gi; const PT_BR_REGEX = /ver anexado|ver anexo|ver inclu\u00eddo|est\u00e1 anexado|anexado|est\u00e3o anexados|anexados|anexado a este e-mail|anexado a esta mensagem|estou anexando|eu estou anexando|anexei|eu anexei|estou incluindo|eu estou incluindo|inclu\u00ed|eu inclu\u00ed|enviar anexo|enviar o anexo|enviar inclu\u00eddo|ver anexos|arquivo anexado|arquivos anexados|em anexo|anexo|veja em anexo|veja o anexo|veja os anexos/gi; const NL_REGEX = /zie bijgevoegd|zie bijlage|zie toegevoegd|is bijgevoegd|bijgevoegd is|zijn bijgevoegd|bijgevoegd zijn|toegevoegd aan dit e-mailbericht|toegevoegd aan dit bericht|Ik voeg bij|Ik heb bijgevoegd|Ik voeg een bijlage bij|Ik heb een bijlage bijgevoegd|bijlage bijvoegen|bijlagen bijvoegen|bijlage opgenomen|opgenomen bijlage|bijgevoegd bestand|zie de bijlage|zie bijlagen|bijgevoegde bestanden|de bijlage bekijken/gi; const PL_REGEX = /patrz w za\u0142\u0105czeniu|patrz za\u0142\u0105cznik|patrz do\u0142\u0105czony|jest do\u0142\u0105czony|w za\u0142\u0105czeniu|s\u0105 za\u0142\u0105czone|za\u0142\u0105czone s\u0105|za\u0142\u0105czone do tego e-maila|do\u0142\u0105czone do tej wiadomo\u015bci|do\u0142\u0105czam|za\u0142\u0105czam|za\u0142\u0105czy\u0142em|za\u0142\u0105czy\u0142am|dodaj\u0119|wysy\u0142am|do\u0142\u0105czy\u0142em|do\u0142\u0105czy\u0142am|patrz za\u0142\u0105czniki|w za\u0142\u0105czniku|patrz za\u0142\u0105czony|patrz za\u0142\u0105czone|masz w za\u0142\u0105czeniu|za\u0142\u0105czony plik|zobacz za\u0142\u0105cznik|zobacz za\u0142\u0105czniki|za\u0142\u0105czone pliki/gi; export const useSendVerifications = ( handleNoRecipients?: () => void, handleNoSubjects?: () => void, handleNoAttachments?: (keyword: string) => void ) => { const { createModal } = useModals(); const { createNotification } = useNotifications(); const getEncryptionPreferences = useGetEncryptionPreferences(); const getMessage = useGetMessage(); const contactsMap = useContactsMap(); const preliminaryVerifications = useCallback(async (message: MessageStateWithData): Promise<void> => { const { draftFlags } = getMessage(message.localID) as MessageStateWithData; const { isSentDraft } = draftFlags || {}; // Message already sent if (isSentDraft) { throw new Error(MESSAGE_ALREADY_SENT_INTERNAL_ERROR); } // No recipients if (!getRecipients(message.data).length) { if (handleNoRecipients) { await handleNoRecipients(); } } // Empty subject if (!message.data.Subject) { if (handleNoSubjects) { await handleNoSubjects(); } } if (!isPlainText(message.data)) { const [contentBeforeBlockquote] = locateBlockquote(message.messageDocument?.document); const normalized = normalize(`${message.data.Subject} ${contentBeforeBlockquote || ''}`); const [keyword] = (languageCode === 'en' && normalized.match(EN_REGEX)) || (languageCode === 'fr' && normalized.match(FR_REGEX)) || (languageCode === 'de' && normalized.match(DE_REGEX)) || (languageCode === 'es' && normalized.match(ES_REGEX)) || (languageCode === 'ru' && normalized.match(RU_REGEX)) || (languageCode === 'it' && normalized.match(IT_REGEX)) || (languageCode === 'pt' && normalized.match(PT_PT_REGEX)) || (languageCode === 'pt' && localeCode === 'pt_BR' && normalized.match(PT_BR_REGEX)) || (languageCode === 'nl' && normalized.match(NL_REGEX)) || (languageCode === 'pl' && normalized.match(PL_REGEX)) || []; // Attachment word without attachments if (keyword && !message.data.Attachments.length) { if (handleNoAttachments) { await handleNoAttachments(keyword); } } } }, []); const extendedVerifications = useCallback( async ( message: MessageStateWithData, trustedMapSendInfo: MapSendInfo ): Promise<{ cleanMessage: MessageStateWithData; mapSendPrefs: SimpleMap<SendPreferences>; hasChanged: boolean; }> => { const uniqueMessage = { ...message, data: uniqueMessageRecipients(message.data), }; const emails = unique(getRecipientsAddresses(uniqueMessage.data)); // Invalid addresses const invalids = emails.filter((email) => !validateEmailAddress(email)); if (invalids.length > 0) { const invalidAddresses = invalids.join(', '); createNotification({ text: c('Send email with warnings').ngettext( msgid`The following address is not valid: ${invalidAddresses}`, `The following addresses are not valid: ${invalidAddresses}`, invalids.length ), type: 'error', }); throw new Error(); } const emailWarnings: { [email: string]: string[] } = {}; const mapSendPrefs: SimpleMap<SendPreferences> = {}; const sendErrors: { [email: string]: EncryptionPreferencesError } = {}; const emailsWithMissingPreferences: string[] = []; const emailsWithE2EEDisabled: string[] = []; const expiresNotEncrypted: string[] = []; await Promise.all( emails.map(async (email) => { let sendPreferences; // We need to retrieve the most recent encryption preferences (thus bypassing & updating the cache), to avoid missing any of the latest legitimate changes // that occured after the last contact update we received. This also re-downloads public encryption keys (both pinned and not). // However, at this point the server could provide malicious encryption information, and the user cannot visually check // whether something is off through the send status icons. // Hence, we must compare the newly fetched data with the cached one, which the user could verify before hitting Send. const lastMinuteEncryptionPrefs = await getEncryptionPreferences({ email, lifetime: 0, contactEmailsMap: contactsMap, }); if (lastMinuteEncryptionPrefs.emailAddressWarnings?.length) { emailWarnings[email] = lastMinuteEncryptionPrefs.emailAddressWarnings as string[]; } const cachedSendInfo = trustedMapSendInfo[email]; if (!cachedSendInfo || !cachedSendInfo.contactSignatureInfo?.isVerified) { // Cached data might not be available if the user clicks 'Send' before the icons are loaded, // or in the UnsubscribeBanner context. In both cases, it's fine to use the last-minute preferences. sendPreferences = getSendPreferences(lastMinuteEncryptionPrefs, message.data); } else if (!lastMinuteEncryptionPrefs.isContactSignatureVerified) { // The signed contact was deleted, or the contact signature was removed. // Note: unpinning a key still results in a new signed contact body, so this block does not deal with that case. if ( cachedSendInfo.sendPreferences?.encrypt && cachedSendInfo.sendPreferences?.isPublicKeyPinned ) { // We warn the user if the contact previously had encryption enabled and included a valid trusted key. // This is needed because we cannot tell whether the user deleted the contact, or whether the action was faked by the server to try // to downgrade encryption preferences maliciously. emailsWithMissingPreferences.push(email); } sendPreferences = getSendPreferences(lastMinuteEncryptionPrefs, message.data); } else { // We have both verified cached preferences and verified last-minute preferences. // We must check that the last-minute preferences' signature is newer than the cached one, and that it was created recently, // otherwise the server might be trying to downgrade the encryption preferences maliciously. const cachedSignatureTime = cachedSendInfo.contactSignatureInfo.creationTime!; const lastMinuteSignatureTime = lastMinuteEncryptionPrefs.contactSignatureTimestamp!; const lastMinuteSignatureAge = Math.abs(+lastMinuteSignatureTime - +serverTime()); if ( +lastMinuteSignatureTime < +cachedSignatureTime || (+lastMinuteSignatureTime !== +cachedSignatureTime && lastMinuteSignatureAge > 24 * HOUR) ) { // The server sent us an old last-minute contact signature. This should never happen, since the server time is used when signing. // This might be an attempt to downgrade the encryption preferences, so we silently discard last-minute prefs and send with cached ones. sendPreferences = cachedSendInfo.sendPreferences!; } else { // The last-minute signature is newer than the cached one, and was created recently enough, so // even if the pinned keys are removed at the last minute, we can be positive that the user made those changes. // Thus, we can now trust & use the last-minute preferences. sendPreferences = getSendPreferences(lastMinuteEncryptionPrefs, message.data); // In the case of internal addresses with E2EE disabled for mail, pinned keys are automatically ignored. // So even if the last-minute contact signature is verified, we must warn the user if the recipient has just disabled E2EE on their address if ( sendPreferences.encryptionDisabled && !cachedSendInfo.sendPreferences?.encryptionDisabled ) { emailsWithE2EEDisabled.push(email); } } } mapSendPrefs[email] = sendPreferences; if (sendPreferences.error) { sendErrors[email] = sendPreferences.error; } if (message.draftFlags?.expiresIn && !sendPreferences.encrypt) { expiresNotEncrypted.push(email); } }) ); // Addresses with warnings const emailsWithWarnings = Object.keys(emailWarnings); if (emailsWithWarnings.length > 0) { await new Promise((resolve, reject) => { createModal( <SendWithWarningsModal mapWarnings={emailWarnings} onSubmit={() => resolve(undefined)} onClose={reject} /> ); }); } // Addresses with sending errors const emailsWithErrors = Object.keys(sendErrors); if (emailsWithErrors.length > 0) { await new Promise((resolve, reject) => { const handleSendAnyway = () => { for (const email of emailsWithErrors) { const indexOfEmail = emails.findIndex((emailAddress) => emailAddress === email); emails.splice(indexOfEmail, 1); delete mapSendPrefs[email]; } resolve(undefined); }; createModal( <SendWithErrorsModal mapErrors={sendErrors} cannotSend={emailsWithErrors.length === emails.length} onSubmit={handleSendAnyway} onClose={reject} /> ); }); } // Addresses where E2EE was disabled at the last minute if (emailsWithE2EEDisabled.length > 0) { await new Promise((resolve, reject) => { createModal( <SendWithChangedPreferencesModal emails={emailsWithE2EEDisabled} changeType={PREFERENCE_CHANGE_TYPE.E2EE_DISABLED} onSubmit={() => resolve(undefined)} onClose={reject} /> ); }); } // Addresses with missing preferences if (emailsWithMissingPreferences.length > 0) { await new Promise((resolve, reject) => { createModal( <SendWithChangedPreferencesModal emails={emailsWithMissingPreferences} changeType={PREFERENCE_CHANGE_TYPE.CONTACT_DELETED} onSubmit={() => resolve(undefined)} onClose={reject} /> ); }); } // Expiration and addresses with no encryptions if (expiresNotEncrypted.length > 0) { await new Promise((resolve, reject) => { createModal( <SendWithExpirationModal emails={expiresNotEncrypted} onSubmit={() => resolve(undefined)} onClose={reject} /> ); }); } // Prepare and save draft const cleanMessage = { ...message, data: removeMessageRecipients(uniqueMessage.data, emailsWithErrors), } as MessageStateWithData; return { cleanMessage, mapSendPrefs, hasChanged: emailsWithErrors.length > 0 }; }, [contactsMap] ); return { preliminaryVerifications, extendedVerifications }; };
4,000
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/contact/useContacts.ts
import { useSelector } from 'react-redux'; import { contactGroupsMap, contactsMap, groupsLabelCache, groupsWithContactsMap, recipientsLabelCache, } from '../../logic/contacts/contactsSelectors'; export const useContactsMap = () => { return useSelector(contactsMap); }; export const useContactGroupsMap = () => { return useSelector(contactGroupsMap); }; export const useGroupsWithContactsMap = () => { return useSelector(groupsWithContactsMap); }; export const useRecipientsLabelCache = () => { return useSelector(recipientsLabelCache); }; export const useGroupsLabelCache = () => { return useSelector(groupsLabelCache); };
4,001
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/contact/useContactsListener.ts
import { useEffect } from 'react'; import { useCache, useContactEmails, useContactGroups, useEventManager, useUserKeys } from '@proton/components'; import { CACHE_KEY } from '@proton/components/hooks/useGetEncryptionPreferences'; import { PublicKeyReference } from '@proton/crypto'; import { CONTACT_CARD_TYPE } from '@proton/shared/lib/constants'; import { readSigned } from '@proton/shared/lib/contacts/decrypt'; import { parseToVCard } from '@proton/shared/lib/contacts/vcard'; import { Cache } from '@proton/shared/lib/helpers/cache'; import { canonicalizeEmail } from '@proton/shared/lib/helpers/email'; import { Contact } from '@proton/shared/lib/interfaces/contacts'; import { splitKeys } from '@proton/shared/lib/keys/keys'; import { refresh } from '../../logic/contacts/contactsActions'; import { resetVerification } from '../../logic/messages/read/messagesReadActions'; import { useAppDispatch } from '../../logic/store'; import { Event } from '../../models/event'; /** * Deal with contact update from the event manager * Will read the updated contact to invalidate some cached related data * * @param contact Contact data update from the event manager * @param publicKeys Public keys of the current user * @param globalCache Proton main cache * @param onResetMessageForEmails */ const processContactUpdate = async ( contact: Contact | undefined, publicKeys: PublicKeyReference[], globalCache: Cache<string, any>, onResetMessageForEmails: (emails: string[]) => void ) => { const signedCard = contact?.Cards.find(({ Type }) => Type === CONTACT_CARD_TYPE.SIGNED); if (!signedCard) { return; } const { data: signedVcard } = await readSigned(signedCard, { publicKeys }); const vCardContact = parseToVCard(signedVcard); const emails = (vCardContact.email || []).map((property) => canonicalizeEmail(property.value)); // Looking in the EncryptionPreference cache const encryptionPreferenceCache = globalCache.get(CACHE_KEY) as Map<string, any>; emails.forEach((email) => { if (encryptionPreferenceCache) { encryptionPreferenceCache.delete(email); } }); // Looking in the Message cache to check if there is message signed from one of the contact addresses onResetMessageForEmails(emails); }; export const useContactsListener = () => { const globalCache = useCache(); const dispatch = useAppDispatch(); const { subscribe } = useEventManager(); const [userKeys = []] = useUserKeys(); const [contacts = []] = useContactEmails(); const [contactGroups = []] = useContactGroups(); const { publicKeys } = splitKeys(userKeys); const handleResetMessageForEmails = (emails: string[]) => { dispatch(resetVerification(emails)); }; useEffect( () => subscribe(({ Contacts = [] }: Event) => { for (const { Contact } of Contacts) { void processContactUpdate(Contact, publicKeys, globalCache, handleResetMessageForEmails); } }), [publicKeys] ); useEffect(() => { dispatch(refresh({ contacts, contactGroups })); }, [contacts, contactGroups]); };
4,002
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/contact/useRecipientLabel.ts
import { Recipient } from '@proton/shared/lib/interfaces'; import { getRecipientGroupLabel as computeRecipientGroupLabel, getRecipientLabel as computeRecipientLabel, getRecipientLabelDetailed as computeRecipientLabelDetailed, recipientsToRecipientOrGroup, } from '../../helpers/message/messageRecipients'; import { RecipientGroup, RecipientOrGroup } from '../../models/address'; import { useContactGroupsMap, useContactsMap, useGroupsLabelCache, useGroupsWithContactsMap, useRecipientsLabelCache, } from './useContacts'; const getRecipientKey = (recipient: Recipient, detailed = false) => `${recipient.Address}-${recipient.Name}-${detailed}`; const getGroupKey = (recipientGroup: RecipientGroup) => `${recipientGroup.group?.Path}-${recipientGroup.recipients .map((recipient) => getRecipientKey(recipient)) .join('-')}`; export const useRecipientLabel = () => { const contactsMap = useContactsMap(); const contactGroupsMap = useContactGroupsMap(); const groupsWithContactsMap = useGroupsWithContactsMap(); const recipientsLabelCache = useRecipientsLabelCache(); const groupsLabelCache = useGroupsLabelCache(); const getRecipientLabel = (recipient: Recipient | undefined, detailed = false): string => { if (!recipient) { return ''; } const recipientKey = getRecipientKey(recipient, detailed); return recipientsLabelCache[recipientKey] ? (recipientsLabelCache[recipientKey] as string) : (detailed ? computeRecipientLabelDetailed : computeRecipientLabel)(recipient, contactsMap); }; const getGroupLabel = (recipientGroup: RecipientGroup | undefined, isShortName = false): string => { if (!recipientGroup) { return ''; } const recipientGroupKey = getGroupKey(recipientGroup); return groupsLabelCache[recipientGroupKey] ? (groupsLabelCache[recipientGroupKey] as string) : computeRecipientGroupLabel( recipientGroup, groupsWithContactsMap[recipientGroup.group?.ID || '']?.contacts.length, isShortName ); }; const getRecipientOrGroupLabel = ({ recipient, group }: RecipientOrGroup, detailed = false): string => recipient ? getRecipientLabel(recipient, detailed) : getGroupLabel(group as RecipientGroup); const getRecipientsOrGroupsLabels = (recipientsOrGroups: RecipientOrGroup[], detailed = false): string[] => recipientsOrGroups.map((recipientsOrGroups) => getRecipientOrGroupLabel(recipientsOrGroups, detailed)); const getRecipientsOrGroups = (recipients: Recipient[], alwaysShowRecipient = false): RecipientOrGroup[] => recipientsToRecipientOrGroup(recipients, contactGroupsMap, alwaysShowRecipient); return { getRecipientLabel, getGroupLabel, getRecipientOrGroupLabel, getRecipientsOrGroupsLabels, getRecipientsOrGroups, }; };
4,003
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/conversation/useClickOutsideFocusedMessage.ts
import { useEffect } from 'react'; const useClickOutsideFocusedMessage = ( focusedMessageId: string | undefined, onClickOutside: (event: MouseEvent) => void ) => { useEffect(() => { if (focusedMessageId === undefined) { return; } const clickCallback = (event: MouseEvent) => { try { if (!event.composed) { return false; } const clickedInside = event .composedPath() .some( (element) => element instanceof HTMLElement && 'message-container' === element.dataset.shortcutTarget && focusedMessageId === element.dataset.messageId ); if (!clickedInside) { onClickOutside(event); } } catch (e) {} }; document.addEventListener('click', clickCallback); return () => { document.removeEventListener('click', clickCallback); }; }, [focusedMessageId]); }; export default useClickOutsideFocusedMessage;
4,004
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/conversation/useConversation.ts
import { useCallback, useEffect, useState } from 'react'; import { useSelector, useStore } from 'react-redux'; import { useEventManager } from '@proton/components'; import useIsMounted from '@proton/hooks/useIsMounted'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { LOAD_RETRY_COUNT, LOAD_RETRY_DELAY } from '../../constants'; import { hasError, hasErrorType } from '../../helpers/errors'; import { initialize, load as loadAction, retryLoading } from '../../logic/conversations/conversationsActions'; import { allConversations, conversationByID } from '../../logic/conversations/conversationsSelectors'; import { ConversationErrors, ConversationState } from '../../logic/conversations/conversationsTypes'; import { RootState, useAppDispatch } from '../../logic/store'; import { Conversation } from '../../models/conversation'; import { useGetElementsFromIDs } from '../mailbox/useElements'; export interface ConversationStateOptional { Conversation?: Conversation; Messages?: Message[]; loadRetry: number; errors: ConversationErrors; } export const useGetConversation = () => { const store = useStore<RootState>(); return useCallback((ID: string) => conversationByID(store.getState(), { ID }), []); }; export const useGetAllConversations = () => { const store = useStore<RootState>(); return useCallback(() => allConversations(store.getState()), []); }; interface ReturnValue { conversationID: string; conversation: ConversationStateOptional | undefined; pendingRequest: boolean; loadingConversation: boolean; loadingMessages: boolean; numMessages: number | undefined; handleRetry: () => void; } interface UseConversation { (conversationID: string, messageID?: string): ReturnValue; } export const useConversation: UseConversation = (inputConversationID, messageID) => { const dispatch = useAppDispatch(); const getElementsFromIDs = useGetElementsFromIDs(); const getConversation = useGetConversation(); const isMounted = useIsMounted(); const { call } = useEventManager(); const conversationState = useSelector((state: RootState) => conversationByID(state, { ID: inputConversationID })); const init = (conversationID: string): ConversationStateOptional | undefined => { if (conversationState) { // Conversation updated from elements can be desynchronized with messages in store if (conversationState.Conversation.NumMessages !== conversationState.Messages?.length) { void call(); } return conversationState; } const [conversationFromElementsState] = getElementsFromIDs([conversationID]); const newConversationState: ConversationState = { Conversation: { ID: conversationID }, Messages: undefined, loadRetry: 0, errors: {}, }; if (conversationFromElementsState) { newConversationState.Conversation = conversationFromElementsState; } dispatch(initialize(newConversationState)); return { Conversation: undefined, Messages: undefined, loadRetry: 0, errors: {} }; }; const [conversationID, setConversationID] = useState(inputConversationID); const [pendingRequest, setPendingRequest] = useState(false); const [conversation, setConversation] = useState<ConversationStateOptional | undefined>(() => init(conversationID)); const load = async (conversationID: string, messageID: string | undefined) => { const existingConversation = getConversation(conversationID); if ((existingConversation?.loadRetry || 0) > LOAD_RETRY_COUNT) { // Max retries reach, aborting return; } if (hasErrorType(existingConversation?.errors, 'notExist')) { // Conversation not exist or invalid id, retrying will not help, aborting return; } if (isMounted()) { setPendingRequest(true); } (await dispatch(loadAction({ conversationID, messageID }))) as any as Promise<any>; const updatedConversation = getConversation(conversationID); if ( updatedConversation && hasError(updatedConversation.errors) && !hasErrorType(updatedConversation.errors, 'notExist') ) { await wait(LOAD_RETRY_DELAY); } if (isMounted()) { setPendingRequest(false); } }; useEffect(() => { if (pendingRequest) { return; } const conversationInState = init(inputConversationID); setConversationID(inputConversationID); setConversation(conversationInState); if (!conversationInState || !conversationInState.Messages || !conversationInState.Messages.length) { void load(inputConversationID, messageID); } }, [inputConversationID, messageID, pendingRequest, conversation?.loadRetry]); useEffect(() => { if (conversationState) { setConversation(conversationState); } }, [conversationState]); const handleRetry = useCallback(() => { dispatch(retryLoading({ ID: conversationID })); }, [conversationID]); const loadingError = hasError(conversation?.errors) && (conversation?.loadRetry || 0) > LOAD_RETRY_COUNT; const loadingConversation = !loadingError && conversation?.Conversation?.Subject === undefined; const loadingMessages = !loadingError && !conversation?.Messages?.length; const numMessages = conversation?.Messages?.length || conversation?.Conversation?.NumMessages; return { conversationID, conversation, pendingRequest, loadingConversation, loadingMessages, numMessages, handleRetry, }; };
4,005
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/conversation/useConversationFocus.tsx
import { FocusEvent, RefObject, useCallback, useEffect, useRef, useState } from 'react'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import useClickOutsideFocusedMessage from './useClickOutsideFocusedMessage'; export type HandleConversationFocus = ( index: number | undefined, options?: { scrollTo?: boolean; withKeyboard?: boolean } ) => void; export const useConversationFocus = (messages: Message[]) => { const [focusIndex, setFocusIndex] = useState<number>(); const [nextScrollTo, setNextScrollTo] = useState(false); // We might want to expand or scroll to a message without focusing it const preventFocusRef = useRef(false); // Controls the scrollIntoView alignment (center, start, end, nearest) const alignmentRef = useRef<ScrollLogicalPosition>('center'); // If last focus actions has been done with keyboard shortcut const withKeyboardRef = useRef(false); useClickOutsideFocusedMessage(focusIndex ? messages[focusIndex]?.ID : undefined, () => { setFocusIndex(undefined); }); const getFocusedId = useCallback( () => (focusIndex !== undefined ? messages[focusIndex] : undefined)?.ID, [focusIndex, messages] ); const handleFocus = useCallback<HandleConversationFocus>( (index, options) => { const { scrollTo = false, withKeyboard = false } = options || {}; if (withKeyboard) { withKeyboardRef.current = true; } setFocusIndex(index); if (index === focusIndex) { setNextScrollTo(scrollTo); } }, [focusIndex] ); const handleScrollToMessage = useCallback((index?: number, alignment?: ScrollLogicalPosition) => { preventFocusRef.current = true; if (alignment) { alignmentRef.current = alignment; } setFocusIndex(index); setNextScrollTo(true); }, []); const handleBlur = useCallback( (event: FocusEvent<HTMLElement>, messageRef: RefObject<HTMLElement>) => { // Check if relatedTarget is inside message ref. If not remove focus // WARNING : relatedTarget returns null when clicking on iframe if (event.relatedTarget && !messageRef.current?.contains(event.relatedTarget)) { setFocusIndex(undefined); } }, [focusIndex] ); useEffect(() => { if (focusIndex === undefined) { return; } const focus = (element: HTMLElement | null) => element?.focus({ preventScroll: true }); let element = document.querySelector( `[data-shortcut-target="message-container"][data-message-id="${messages[focusIndex]?.ID}"]` ) as HTMLElement | null; if (element && !preventFocusRef.current) { const iframe = element.querySelector('iframe'); // If has been focused by keyboard shortcut // Also, if opening the message for the first time, the iframe will not be defined yet // In that case, we want to focus the message, otherwise, nothing gets the focus if (withKeyboardRef.current === true || !iframe) { focus(element); } else { focus(iframe); } } withKeyboardRef.current = false; preventFocusRef.current = false; }, [focusIndex]); useEffect(() => { if (focusIndex !== undefined && nextScrollTo) { let element = document.querySelector( `[data-shortcut-target="message-container"][data-message-id="${messages[focusIndex]?.ID}"]` ) as HTMLElement | null; element?.scrollIntoView({ block: alignmentRef.current, behavior: 'smooth' }); alignmentRef.current = 'center'; setNextScrollTo(false); } }, [nextScrollTo]); return { focusIndex, handleFocus, handleScrollToMessage, handleBlur, getFocusedId }; };
4,006
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/conversation/useConversationHotkeys.tsx
import { useRef } from 'react'; import { HotkeyTuple, useHotkeys } from '@proton/components'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { HandleConversationFocus } from './useConversationFocus'; export interface ConversationHotkeysContext { messages: Message[]; focusIndex: number | undefined; } export interface ConversationHotkeysHandlers { handleFocus: HandleConversationFocus; expandMessage: (ID: string) => void; getFocusedId: () => string | undefined; } export const useConversationHotkeys = ( { messages, focusIndex }: ConversationHotkeysContext, { handleFocus, expandMessage, getFocusedId }: ConversationHotkeysHandlers ) => { const elementRef = useRef<HTMLDivElement>(null); const shortcutHandlers: HotkeyTuple[] = [ [ 'ArrowLeft', (e) => { e.preventDefault(); e.stopPropagation(); const element = (document.querySelector( '[data-shortcut-target="item-container"][data-shortcut-target-selected="true"]' ) as HTMLElement) || (document.querySelector('[data-shortcut-target="item-container"]') as HTMLElement); element?.focus(); handleFocus(undefined); }, ], [ ['Meta', 'ArrowUp'], (e) => { e.stopPropagation(); handleFocus(0, { withKeyboard: true }); }, ], [ 'ArrowUp', (e) => { e.stopPropagation(); const trashWarning = document.querySelector('[data-shortcut-target="trash-warning"]') as HTMLElement; if (trashWarning && focusIndex === 0) { trashWarning.focus(); return; } const previousIndex = focusIndex !== undefined ? Math.max(0, focusIndex - 1) : messages.length - 1; // leave the browser arrow scroll for last email if (previousIndex !== 0) { e.preventDefault(); } handleFocus(previousIndex, { withKeyboard: true }); }, ], [ ['Meta', 'ArrowDown'], (e) => { e.stopPropagation(); handleFocus(messages.length - 1, { withKeyboard: true }); }, ], [ 'ArrowDown', (e) => { e.stopPropagation(); const lastIndex = messages.length - 1; const nextIndex = focusIndex !== undefined ? Math.min(lastIndex, focusIndex + 1) : 0; // leave the browser arrow scroll for last email if (nextIndex !== lastIndex) { e.preventDefault(); } handleFocus(nextIndex, { withKeyboard: true }); }, ], [ 'Enter', (e) => { e.stopPropagation(); const id = getFocusedId(); if (id) { expandMessage(id); } }, ], ]; useHotkeys(elementRef, shortcutHandlers); return { elementRef }; };
4,007
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/drawer/useMailDrawer.tsx
import { CalendarDrawerAppButton, ContactDrawerAppButton } from '@proton/components/components'; import { useDrawer } from '@proton/components/hooks'; import { APPS } from '@proton/shared/lib/constants'; import { isAppInView } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_NATIVE_APPS } from '@proton/shared/lib/drawer/interfaces'; const useMailDrawer = () => { const { appInView, showDrawerSidebar } = useDrawer(); const drawerSidebarButtons = [ <ContactDrawerAppButton aria-expanded={isAppInView(DRAWER_NATIVE_APPS.CONTACTS, appInView)} />, <CalendarDrawerAppButton aria-expanded={isAppInView(APPS.PROTONCALENDAR, appInView)} />, ]; return { drawerSidebarButtons, showDrawerSidebar }; }; export default useMailDrawer;
4,008
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/eo/useEOAttachments.ts
import { RefObject, useState } from 'react'; import { useHandler, useNotifications } from '@proton/components'; import { PublicKeyReference } from '@proton/crypto'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants'; import { EO_REPLY_NUM_ATTACHMENTS_LIMIT } from '@proton/shared/lib/mail/eo/constants'; import { getAttachments, isPlainText } from '@proton/shared/lib/mail/messages'; import { MessageChange } from '../../components/composer/Composer'; import { ExternalEditorActions } from '../../components/composer/editor/EditorWrapper'; import { checkSizeAndLength, uploadEO } from '../../helpers/attachment/attachmentUploader'; import { createEmbeddedImageFromUpload, isEmbeddable, matchSameCidOrLoc, readContentIDandLocation, } from '../../helpers/message/messageEmbeddeds'; import { getEmbeddedImages, updateImages } from '../../helpers/message/messageImages'; import { MessageState, MessageStateWithData } from '../../logic/messages/messagesTypes'; interface Props { message: MessageState; onChange: MessageChange; editorActionsRef: RefObject<ExternalEditorActions | undefined>; publicKey?: PublicKeyReference[]; } export const useEOAttachments = ({ message, onChange, editorActionsRef, publicKey }: Props) => { const { createNotification } = useNotifications(); const [imagesToInsert, setImagesToInsert] = useState<File[]>([]); /** * Start uploading a file, the choice between attachment or inline is done. */ const handleAddAttachmentsUpload = useHandler(async (action: ATTACHMENT_DISPOSITION, files: File[] = []) => { if (publicKey) { files.forEach((file: File) => { void uploadEO(file, message as MessageStateWithData, publicKey, action).then( ({ attachment, packets }) => { // Warning, that change function can be called multiple times, don't do any side effect in it onChange((message: MessageState) => { // New attachment list const Attachments = [...getAttachments(message.data), attachment]; const embeddedImages = getEmbeddedImages(message); if (action === ATTACHMENT_DISPOSITION.INLINE) { embeddedImages.push(createEmbeddedImageFromUpload(attachment)); } const messageImages = updateImages( message.messageImages, undefined, undefined, embeddedImages ); return { data: { Attachments }, messageImages }; }); if (action === ATTACHMENT_DISPOSITION.INLINE) { editorActionsRef.current?.insertEmbedded(attachment, packets.Preview); } } ); }); } }); /** * Entry point for upload, will check and ask for attachment action if possible */ const handleAddAttachments = useHandler(async (files: File[]) => { const embeddable = files.every((file) => isEmbeddable(file.type)); const plainText = isPlainText(message.data); const hasReachedLimits = checkSizeAndLength({ createNotification, message, files, attachmentsCountLimit: EO_REPLY_NUM_ATTACHMENTS_LIMIT, }); if (hasReachedLimits) { return; } if (!plainText && embeddable) { setImagesToInsert(files); } else { void handleAddAttachmentsUpload(ATTACHMENT_DISPOSITION.ATTACHMENT, files); } }); /** * Remove an existing attachment, deal with potential embedded image */ const handleRemoveAttachment = useHandler(async (attachment: Attachment) => { onChange((message: MessageState) => { const Attachments = message.data?.Attachments?.filter((a: Attachment) => a.ID !== attachment.ID) || []; const { cid, cloc } = readContentIDandLocation(attachment); const embeddedImages = getEmbeddedImages(message); const embeddedImage = embeddedImages.find((image) => matchSameCidOrLoc(image, cid, cloc)); const newEmbeddedImages = embeddedImages.filter((image) => !matchSameCidOrLoc(image, cid, cloc)); if (embeddedImage) { setTimeout(() => { editorActionsRef.current?.removeEmbedded(embeddedImage.attachment); }); } const messageImages = updateImages(message.messageImages, undefined, undefined, newEmbeddedImages); return { data: { Attachments }, messageImages }; }); }); const handleUploadImage = (action: ATTACHMENT_DISPOSITION) => { void handleAddAttachmentsUpload(action, imagesToInsert); setImagesToInsert([]); }; return { imagesToInsert, setImagesToInsert, handleAddAttachments, handleAddAttachmentsUpload, handleRemoveAttachment, handleUploadImage, }; };
4,009
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/eo/useInitializeEOMessage.ts
import { useCallback } from 'react'; import { PayloadAction } from '@reduxjs/toolkit'; import { useApi } from '@proton/components'; import { PrivateKeyReference } from '@proton/crypto'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { EO_DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/eo/constants'; import { isPlainText } from '@proton/shared/lib/mail/messages'; import noop from '@proton/utils/noop'; import { LOAD_RETRY_COUNT, LOAD_RETRY_DELAY } from '../../constants'; import { isNetworkError } from '../../helpers/errors'; import { decryptMessage } from '../../helpers/message/messageDecrypt'; import { Preparation, prepareHtml, preparePlainText } from '../../helpers/transforms/transforms'; import { EODocumentInitializeFulfilled, EODocumentInitializePending, EOLoadEmbedded, EOLoadRemote, } from '../../logic/eo/eoActions'; import { EOLoadEmbeddedParams, EOLoadRemoteResults } from '../../logic/eo/eoType'; import { LoadEmbeddedResults, MessageErrors, MessageImages, MessageRemoteImage, MessageState, MessageStateWithDataFull, } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; import { useBase64Cache } from '../useBase64Cache'; import { useGetEODecryptedToken, useGetEOMessageState, useGetEOPassword } from './useLoadEOMessage'; export const useInitializeEOMessage = () => { const api = useApi(); const dispatch = useAppDispatch(); const getMessage = useGetEOMessageState(); const getPassword = useGetEOPassword(); const getEODecryptedToken = useGetEODecryptedToken(); const base64Cache = useBase64Cache(); return useCallback(async () => { const getData = () => (getMessage() as MessageStateWithDataFull).data; const password = getPassword(); const decryptedToken = getEODecryptedToken(); const messageFromState = { ...getMessage() } as MessageState; dispatch(EODocumentInitializePending()); const errors: MessageErrors = {}; const { loadRetry = 0 } = messageFromState; let initialized: boolean | undefined = true; let decryption; let preparation: Preparation | undefined; let dataChanges = {} as Partial<Message>; let messageImages: MessageImages | undefined; try { // Decryption decryption = await decryptMessage(getData(), [] as PrivateKeyReference[], undefined, undefined, password); if (decryption.mimetype) { dataChanges = { ...dataChanges, MIMEType: decryption.mimetype }; } // PGP encrypted attachment decryption with all attachments const mimeAttachments = decryption.attachments || []; const allAttachments = [...getData().Attachments, ...mimeAttachments]; dataChanges = { ...dataChanges, Attachments: allAttachments, NumAttachments: getData().NumAttachments + mimeAttachments.length, }; if (decryption.errors) { Object.assign(errors, decryption.errors); } const MIMEType = dataChanges.MIMEType || getData().MIMEType; const handleEOLoadEmbeddedImages = async (attachments: Attachment[]) => { const dispatchResult = dispatch( EOLoadEmbedded({ attachments, api, messageVerification: messageFromState.verification, password, id: 'TODO: CHANGE ID', decryptedToken, }) ) as any as Promise<PayloadAction<LoadEmbeddedResults, string, { arg: EOLoadEmbeddedParams }>>; const { payload } = await dispatchResult; return payload; }; const handleEOLoadRemoteImages = (imagesToLoad: MessageRemoteImage[]) => { const dispatchResult = dispatch( EOLoadRemote({ imagesToLoad, }) ); return dispatchResult as any as Promise<EOLoadRemoteResults[]>; }; preparation = isPlainText({ MIMEType }) ? await preparePlainText(decryption.decryptedBody, false, EO_DEFAULT_MAILSETTINGS) : await prepareHtml( { ...messageFromState, decryption, data: { ...messageFromState.data, Attachments: allAttachments } as Message, }, base64Cache, EO_DEFAULT_MAILSETTINGS, handleEOLoadEmbeddedImages, noop, noop, handleEOLoadRemoteImages, noop, false ); if (!isPlainText({ MIMEType })) { messageImages = { hasRemoteImages: preparation.hasRemoteImages as boolean, showRemoteImages: preparation.showRemoteImages as boolean, hasEmbeddedImages: preparation.hasEmbeddedImages as boolean, showEmbeddedImages: preparation.showEmbeddedImages as boolean, trackersStatus: 'not-loaded', images: [...(preparation.remoteImages || []), ...(preparation.embeddedImages || [])], }; } } catch (error: any) { if (isNetworkError(error)) { errors.network = [error]; if (loadRetry < LOAD_RETRY_COUNT) { initialized = undefined; await wait(LOAD_RETRY_DELAY); } } else { errors.processing = [error]; } console.log('EO message initialization error', error); } finally { dispatch( EODocumentInitializeFulfilled({ dataChanges, initialized, preparation, decryption, errors, messageImages, }) ); } }, []); };
4,010
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/eo/useLoadEOImages.ts
import { useCallback } from 'react'; import { useApi } from '@proton/components'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { EO_DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/eo/constants'; import { updateImages } from '../../helpers/message/messageImages'; import { transformEmbedded } from '../../helpers/transforms/transformEmbedded'; import { transformRemote } from '../../helpers/transforms/transformRemote'; import { EOLoadEmbedded, EOLoadRemote } from '../../logic/eo/eoActions'; import { EOLoadEmbeddedResults, EOLoadRemoteResults } from '../../logic/eo/eoType'; import { MessageRemoteImage, MessageState } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; import { useGetEODecryptedToken, useGetEOMessageState, useGetEOPassword } from './useLoadEOMessage'; export const useLoadEORemoteImages = (mailSettings: MailSettings) => { const dispatch = useAppDispatch(); const getMessage = useGetEOMessageState(); return useCallback(async () => { const message = getMessage() as MessageState; const handleLoadEORemoteImages = (imagesToLoad: MessageRemoteImage[]) => { const dispatchResult = dispatch(EOLoadRemote({ imagesToLoad })); return dispatchResult as any as Promise<EOLoadRemoteResults[]>; }; transformRemote( { ...message, messageImages: updateImages(message.messageImages, { showRemoteImages: true }, undefined, undefined), }, mailSettings, handleLoadEORemoteImages ); }, []); }; export const useLoadEOEmbeddedImages = (id: string) => { const dispatch = useAppDispatch(); const api = useApi(); const getMessage = useGetEOMessageState(); const getDecryptedToken = useGetEODecryptedToken(); const getPassword = useGetEOPassword(); return useCallback(async () => { const message = getMessage() as MessageState; const decryptedToken = getDecryptedToken(); const password = getPassword(); const handleLoadEOEmbeddedImages = (attachments: Attachment[]) => { const dispatchResult = dispatch( EOLoadEmbedded({ attachments, api, messageVerification: message.verification, password, id, decryptedToken, }) ); return dispatchResult as any as Promise<EOLoadEmbeddedResults>; }; await transformEmbedded( { ...message, messageImages: updateImages(message.messageImages, { showEmbeddedImages: true }, undefined, undefined), }, EO_DEFAULT_MAILSETTINGS, handleLoadEOEmbeddedImages ); }, []); };
4,011
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/eo/useLoadEOMessage.ts
import { useCallback, useEffect, useMemo } from 'react'; import { useSelector, useStore } from 'react-redux'; import { useApi } from '@proton/components'; import { loadEOToken } from '../../logic/eo/eoActions'; import { eoDecryptedTokenSelector, eoMessageSelector, eoMessageStateSelector, eoTokenSelector, isStoreInitializedSelector, passwordSelector, } from '../../logic/eo/eoSelectors'; import { RootState } from '../../logic/eo/eoStore'; import { OutsideKey } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; export const useGetEOMessage = () => { const store = useStore<RootState>(); return useCallback(() => eoMessageSelector(store.getState()), []); }; export const useGetEOToken = () => { const store = useStore<RootState>(); return useCallback(() => eoTokenSelector(store.getState()), []); }; export const useGetEODecryptedToken = () => { const store = useStore<RootState>(); return useCallback(() => eoDecryptedTokenSelector(store.getState()), []); }; export const useGetEOMessageState = () => { const store = useStore<RootState>(); return useCallback(() => eoMessageStateSelector(store.getState()), []); }; export const useGetEOPassword = () => { const store = useStore<RootState>(); return useCallback(() => passwordSelector(store.getState()), []); }; interface Props { id: string | undefined; setSessionStorage: (key: string, data: any) => void; } export const useLoadEOMessage = ({ id, setSessionStorage }: Props) => { const dispatch = useAppDispatch(); const api = useApi(); const encryptedToken = useSelector((state: RootState) => eoTokenSelector(state)); const decryptedToken = useSelector((state: RootState) => eoDecryptedTokenSelector(state)); const eoMessageState = useSelector((state: RootState) => eoMessageSelector(state)); const isStoreInitialized = useSelector((state: RootState) => isStoreInitializedSelector(state)); const password = useSelector((state: RootState) => passwordSelector(state)); const messageState = useSelector((state: RootState) => eoMessageStateSelector(state)); const outsideKey = useMemo(() => { return { type: 'outside', password, id, decryptedToken, } as OutsideKey; }, [password, decryptedToken, id]); // When opening the app, we try to get the session from the secureSessionStorage. // If session has not been found, we try to load the EO token from the ID in the URL useEffect(() => { const fetchToken = async (id: string) => { try { await dispatch(loadEOToken({ api, id, set: setSessionStorage })); } catch (error: any | undefined) { console.error(error); } }; if (isStoreInitialized && id && (!encryptedToken || encryptedToken === '')) { void fetchToken(id); } }, [encryptedToken, isStoreInitialized]); return { encryptedToken, isStoreInitialized, message: eoMessageState, decryptedToken, password, messageState, outsideKey, }; };
4,012
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/eo/useLoadEOToken.ts
import { useHistory } from 'react-router'; import { c } from 'ttag'; import { useApi, useNotifications } from '@proton/components'; import { EO_MESSAGE_REDIRECT_PATH } from '../../constants'; import { eoDecrypt } from '../../helpers/eo/message'; import { loadEOMessage } from '../../logic/eo/eoActions'; import { useAppDispatch } from '../../logic/store'; interface Props { id?: string; encryptedToken: string; setSessionStorage: (key: string, data: any) => void; } export const useLoadEOToken = ({ id, encryptedToken, setSessionStorage }: Props) => { const api = useApi(); const dispatch = useAppDispatch(); const { createNotification } = useNotifications(); const history = useHistory(); const handleTryUnlock = async (password: string) => { if (password.length > 0 && id) { try { const token = await eoDecrypt(encryptedToken, password); await dispatch(loadEOMessage({ api, token, id, password, set: setSessionStorage })); history.push(`${EO_MESSAGE_REDIRECT_PATH}/${id}`); } catch (e: any) { console.error(e); createNotification({ text: c('Error').t`Wrong mailbox password`, type: 'error' }); } } else { createNotification({ text: c('Error').t`Enter a password`, type: 'error' }); } }; return { handleTryUnlock }; };
4,013
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/eo/useSendEO.tsx
import { useHistory } from 'react-router'; import { c } from 'ttag'; import { useApi, useNotifications } from '@proton/components'; import { CryptoProxy, PublicKeyReference } from '@proton/crypto'; import { EOReply } from '@proton/shared/lib/api/eo'; import { blobURLtoBlob } from '@proton/shared/lib/helpers/file'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import SendingMessageNotification, { createSendingMessageNotificationManager, } from '../../components/notifications/SendingMessageNotification'; import { EO_MESSAGE_REDIRECT_PATH, MIN_DELAY_SENT_NOTIFICATION } from '../../constants'; import { getDecryptedAttachment } from '../../helpers/attachment/attachmentLoader'; import { encryptFile } from '../../helpers/attachment/attachmentUploader'; import { createBlob, readContentIDandLocation } from '../../helpers/message/messageEmbeddeds'; import { prepareExport } from '../../helpers/message/messageExport'; import { EOAddReply } from '../../logic/eo/eoActions'; import { EOMessageReply } from '../../logic/eo/eoType'; import { MessageKeys, MessageState } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; interface EOAttachment { Filename: string[]; DataPacket: Blob[]; KeyPackets: Blob[]; ContentID: string[]; MIMEType: string[]; } interface Props { message: MessageState; publicKeys?: PublicKeyReference[]; outsideKey?: MessageKeys; } export const useSendEO = ({ message, publicKeys, outsideKey }: Props) => { const api = useApi(); const dispatch = useAppDispatch(); const history = useHistory(); const notifManager = createSendingMessageNotificationManager(); const { createNotification, hideNotification } = useNotifications(); let password = ''; let decryptedToken = ''; let id = ''; if (outsideKey?.type === 'outside') { password = outsideKey.password; decryptedToken = outsideKey.decryptedToken; id = outsideKey.id; } /** To get Data and Key packets, we need to : * - Get attachments data from BE to build the blob URL * - Create the actual blob from the blob URL * - Encrypt the blob to get the packets which contains Data and Key packets */ const handleOriginalMessageEmbedded = async (packages: EOAttachment, attachment: Attachment) => { if (outsideKey && publicKeys) { const decryptedAttachment = await getDecryptedAttachment(attachment, undefined, outsideKey, api); const blobURL = createBlob(attachment, decryptedAttachment.data as Uint8Array); const blob = await blobURLtoBlob(blobURL); const packet = await encryptFile(blob as File, true, publicKeys); packages.DataPacket.push(new Blob([packet.data])); packages.KeyPackets.push(new Blob([packet.keys])); } }; const send = async () => { notifManager.ID = createNotification({ text: <SendingMessageNotification manager={notifManager} />, expiration: -1, showCloseButton: false, }); try { const replyContent = prepareExport(message); const Body = ( await CryptoProxy.encryptMessage({ textData: replyContent, stripTrailingSpaces: true, encryptionKeys: publicKeys, }) ).message; const ReplyBody = ( await CryptoProxy.encryptMessage({ textData: replyContent, stripTrailingSpaces: true, passwords: [password], }) ).message; const Packages = { Filename: [], DataPacket: [], KeyPackets: [], ContentID: [], MIMEType: [], } as EOAttachment; for (const attachment of message.data?.Attachments || []) { const { cid } = readContentIDandLocation(attachment); Packages.ContentID.push(cid); Packages.Filename.push(attachment.Name || ''); Packages.MIMEType.push(attachment.MIMEType || ''); /** Uploaded attachments during reply composition already contains Data and KeyPackets. * However, we do not have these data for embedded images in the original message, which are in the reply blockquotes * We need to get original message embedded images data in order to build KeyPackets and DataPacket before sending */ if (!attachment.DataPacket) { await handleOriginalMessageEmbedded(Packages, attachment); } else { // Attachments from EO message to send Packages.DataPacket.push(attachment.DataPacket); Packages.KeyPackets.push(attachment.KeyPackets); } } const data = { Body, ReplyBody, 'Filename[]': Packages ? Packages.Filename : [], 'MIMEType[]': Packages ? Packages.MIMEType : [], 'ContentID[]': Packages ? Packages.ContentID : [], 'KeyPackets[]': Packages ? Packages.KeyPackets : [], 'DataPacket[]': Packages ? Packages.DataPacket : [], }; const promise = api(EOReply(decryptedToken || '', id, data)); notifManager.setProperties(promise); const result = (await promise) as unknown as { Reply: EOMessageReply }; if (result?.Reply) { await dispatch(EOAddReply(result.Reply)); } history.push(`${EO_MESSAGE_REDIRECT_PATH}/${id}`); await wait(MIN_DELAY_SENT_NOTIFICATION); hideNotification(notifManager.ID); } catch (error: any) { hideNotification(notifManager.ID); createNotification({ type: 'error', text: c('Error').t`Error while sending the message. Message is not sent.`, }); console.error('Error while sending the message.', error); throw error; } }; return { send }; };
4,014
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/events/useConversationsEvents.tsx
import { useSubscribeEventManager } from '@proton/components'; import { EVENT_ACTIONS } from '@proton/shared/lib/constants'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { parseLabelIDsInEvent } from '../../helpers/elements'; import { eventConversationUpdate, eventDelete, eventMessageUpdate, load as loadAction, } from '../../logic/conversations/conversationsActions'; import { useAppDispatch } from '../../logic/store'; import { Conversation } from '../../models/conversation'; import { Event, LabelIDsChanges } from '../../models/event'; import { useGetConversation } from '../conversation/useConversation'; export const useConversationsEvent = () => { const dispatch = useAppDispatch(); const getConversation = useGetConversation(); useSubscribeEventManager(async ({ Conversations = [], Messages = [] }: Event) => { // Conversation messages event const { toCreate, toUpdate, toDelete } = Messages.reduce<{ toCreate: Message[]; toUpdate: Message[]; toDelete: { [ID: string]: boolean }; }>( ({ toCreate, toUpdate, toDelete }, { ID, Action, Message }) => { const data = Message && getConversation(Message.ConversationID); if (Action === EVENT_ACTIONS.CREATE && data) { toCreate.push(Message as Message); } else if ((Action === EVENT_ACTIONS.UPDATE_DRAFT || Action === EVENT_ACTIONS.UPDATE_FLAGS) && data) { toUpdate.push({ ID, ...(Message as Omit<Message, 'ID'>) }); } else if (Action === EVENT_ACTIONS.DELETE) { toDelete[ID] = true; } return { toCreate, toUpdate, toDelete }; }, { toCreate: [], toUpdate: [], toDelete: {} } ); void dispatch(eventMessageUpdate({ toCreate, toUpdate, toDelete })); // Conversation events for (const { ID, Action, Conversation } of Conversations) { const currentConversation = getConversation(ID); if (!currentConversation) { return; } if (Action === EVENT_ACTIONS.DELETE) { void dispatch(eventDelete(ID)); } if ( Action === EVENT_ACTIONS.UPDATE_DRAFT || Action === EVENT_ACTIONS.UPDATE_FLAGS || Action === EVENT_ACTIONS.CREATE ) { // Try to update the conversation from event data without reloading it try { const updatedConversation: Conversation = parseLabelIDsInEvent( currentConversation?.Conversation || ({} as Conversation), Conversation as Conversation & LabelIDsChanges ); dispatch(eventConversationUpdate({ ID, updatedConversation })); } catch (error: any) { console.warn('Something went wrong on updating a conversation from an event.', error); void dispatch(loadAction({ conversationID: ID, messageID: undefined })); } } } }); };
4,015
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/events/useElementsEvents.ts
import { useSelector, useStore } from 'react-redux'; import { useSubscribeEventManager } from '@proton/components'; import { EVENT_ACTIONS } from '@proton/shared/lib/constants'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { eventUpdates, invalidate } from '../../logic/elements/elementsActions'; import { isES as isESSelector, isLive as isLiveSelector, taskRunning as taskRunningSelector, } from '../../logic/elements/elementsSelectors'; import { EventUpdates } from '../../logic/elements/elementsTypes'; import { RootState, useAppDispatch } from '../../logic/store'; import { Element } from '../../models/element'; import { ConversationEvent, ElementEvent, Event, MessageEvent } from '../../models/event'; import { SearchParameters } from '../../models/tools'; export const useElementsEvents = (conversationMode: boolean, search: SearchParameters) => { const { esStatus } = useEncryptedSearchContext(); const store = useStore<RootState>(); const dispatch = useAppDispatch(); const isLive = useSelector(isLiveSelector); const isES = useSelector((state: RootState) => isESSelector(state, { search, esStatus })); const taskRunning = useSelector(taskRunningSelector); // Listen to event manager and update the cache useSubscribeEventManager(async ({ Conversations = [], Messages = [] }: Event) => { const Elements: ElementEvent[] = conversationMode ? Conversations : Messages; // If it's an encrypted search, its event manager will deal with the change if (isES) { return; } if (!Elements.length) { return; } if (!isLive) { if (Elements.length) { dispatch(invalidate()); } return; } const { toCreate, toUpdate: toUpdateOrLoad, toDelete, } = Elements.reduce<Pick<EventUpdates, 'toCreate' | 'toUpdate' | 'toDelete'>>( ({ toCreate, toUpdate, toDelete }, event) => { const { ID, Action } = event; const Element = conversationMode ? (event as ConversationEvent).Conversation : (event as MessageEvent).Message; if (Action === EVENT_ACTIONS.CREATE) { toCreate.push(Element as Element); } else if (Action === EVENT_ACTIONS.UPDATE_DRAFT || Action === EVENT_ACTIONS.UPDATE_FLAGS) { toUpdate.push(Element as Element); } else if (Action === EVENT_ACTIONS.DELETE) { toDelete.push(ID); } return { toCreate, toUpdate, toDelete }; }, { toCreate: [], toUpdate: [], toDelete: [] } ); // Not the elements ids "in view" but all in the cache const elementIDs = Object.keys(store.getState().elements.elements); const { toUpdate, toLoad } = toUpdateOrLoad.reduce<Pick<EventUpdates, 'toUpdate' | 'toLoad'>>( ({ toUpdate, toLoad }, element) => { const existingElement = elementIDs.includes(element.ID || ''); if (existingElement) { toUpdate.push(element); } else if (taskRunning.labelIDs.length === 0) { // Long tasks trigger too much element update to be able to load them all toLoad.push(element); } else { // We can't loose the element, so we create it toCreate.push(element); } return { toUpdate, toLoad }; }, { toUpdate: [], toLoad: [] } ); void dispatch(eventUpdates({ conversationMode, toCreate, toUpdate, toLoad, toDelete })); }); };
4,016
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/events/useMessagesEvents.ts
import { useSubscribeEventManager } from '@proton/components'; import { event } from '../../logic/messages/read/messagesReadActions'; import { useAppDispatch } from '../../logic/store'; import { Event } from '../../models/event'; import { useGetMessage } from '../message/useMessage'; export const useMessagesEvents = () => { const dispatch = useAppDispatch(); const getMessage = useGetMessage(); useSubscribeEventManager(async ({ Messages }: Event) => { if (!Array.isArray(Messages)) { return; } for (const MessageEvent of Messages) { const currentValue = getMessage(MessageEvent.ID); // Ignore updates for non-fetched messages. if (!currentValue) { continue; } dispatch(event(MessageEvent)); } }); };
4,017
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/incomingDefaults/useIncomingDefaults.ts
import { useSelector } from 'react-redux'; import { IncomingDefault, IncomingDefaultStatus } from '@proton/shared/lib/interfaces'; import { getIncomingDefaultStatus, getIncomingDefaultsAddresses, } from '../../logic/incomingDefaults/incomingDefaultsSelectors'; import { RootState } from '../../logic/store'; export const useIncomingDefaultsAddresses = (): IncomingDefault[] => useSelector((state: RootState) => getIncomingDefaultsAddresses(state)); export const useIncomingDefaultsStatus = (): IncomingDefaultStatus => useSelector((state: RootState) => getIncomingDefaultStatus(state));
4,018
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/incomingDefaults/useIncomingDefaultsEvents.ts
import { useSubscribeEventManager } from '@proton/components'; import { event } from '../../logic/incomingDefaults/incomingDefaultsActions'; import { useAppDispatch } from '../../logic/store'; import { Event } from '../../models/event'; export default () => { const dispatch = useAppDispatch(); useSubscribeEventManager(async ({ IncomingDefaults }: Event) => { if (!Array.isArray(IncomingDefaults)) { return; } for (const IncomingDefaultEvent of IncomingDefaults) { dispatch(event(IncomingDefaultEvent)); } }); };
4,019
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/incomingDefaults/useIncomingDefaultsLoad.ts
import { useEffect } from 'react'; import { load as loadIncomingDefaults } from '../../logic/incomingDefaults/incomingDefaultsActions'; import { useAppDispatch } from '../../logic/store'; import { useIncomingDefaultsStatus } from './useIncomingDefaults'; export default () => { const dispatch = useAppDispatch(); const incomingDefaultsStatus = useIncomingDefaultsStatus(); useEffect(() => { if (incomingDefaultsStatus === 'not-loaded') { void dispatch(loadIncomingDefaults()); } }, []); };
4,020
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useApplyEncryptedSearch.ts
import { useEffect } from 'react'; import { useSelector } from 'react-redux'; import { useHistory } from 'react-router-dom'; import { c } from 'ttag'; import { useNotifications } from '@proton/components'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { isSearch } from '../../helpers/elements'; import { parseSearchParams } from '../../helpers/encryptedSearch'; import { addESResults, load as loadAction, manualFulfilled, manualPending, updatePage, } from '../../logic/elements/elementsActions'; import { isES as isESSelector, messagesToLoadMoreES as messagesToLoadMoreESSelector, shouldSendRequest as shouldSendRequestSelector, } from '../../logic/elements/elementsSelectors'; import { RootState, useAppDispatch } from '../../logic/store'; import { Element } from '../../models/element'; import { Filter, SearchParameters, Sort } from '../../models/tools'; interface EncryptedSearchParams { conversationMode: boolean; labelID: string; page: number; sort: Sort; filter: Filter; search: SearchParameters; onPage: (page: number) => void; } export const useApplyEncryptedSearch = ({ conversationMode, labelID, search, page, sort, filter, onPage, }: EncryptedSearchParams) => { const history = useHistory(); const { createNotification } = useNotifications(); const dispatch = useAppDispatch(); const { esStatus, encryptedSearch } = useEncryptedSearchContext(); const { esEnabled } = esStatus; const params = { labelID, conversationMode, sort, filter, search, esEnabled }; const isES = useSelector((state: RootState) => isESSelector(state, { search, esStatus })); const shouldSendRequest = useSelector((state: RootState) => shouldSendRequestSelector(state, { page, params })); const messagesToLoadMoreES = useSelector((state: RootState) => messagesToLoadMoreESSelector(state, { page, search, esStatus }) ); const setEncryptedSearchResults = (elements: Element[]) => { dispatch(addESResults({ elements, page: parseSearchParams(history.location).page })); }; const executeSearch = async () => { dispatch(manualPending()); try { let success = false; if (isES) { success = await encryptedSearch(setEncryptedSearchResults); } if (!success) { if (page >= 200) { // This block will most likely be called two times // Fortunately notification system use a de-duplication system createNotification({ text: c('Error') .t`Your search matched too many results. Please limit your search and try again.`, type: 'error', }); dispatch(manualFulfilled()); onPage(0); } else { void dispatch(loadAction({ conversationMode, page, params, abortController: undefined })); } } } catch (error: any) { createNotification({ text: c('Error').t`There has been an issue with content search. Default search has been used instead.`, type: 'error', }); void dispatch(loadAction({ conversationMode, page, params, abortController: undefined })); } }; useEffect(() => { if (shouldSendRequest && isSearch(search)) { void executeSearch(); } if (isES && messagesToLoadMoreES !== 0) { // We navigate directly to the requested page first, because it is always guaranteed // to contain some messages, either because it's an already full intermediate page or // because it's the partial last page available dispatch(updatePage(parseSearchParams(history.location).page)); void encryptedSearch(setEncryptedSearchResults, messagesToLoadMoreES); } }, [shouldSendRequest, messagesToLoadMoreES, search]); };
4,021
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useElements.ts
import { useCallback, useEffect, useRef } from 'react'; import { useSelector, useStore } from 'react-redux'; import { useCache, useConversationCounts, useMessageCounts } from '@proton/components'; import { omit } from '@proton/shared/lib/helpers/object'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import { ConversationCountsModel, MessageCountsModel } from '@proton/shared/lib/models'; import isTruthy from '@proton/utils/isTruthy'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { hasAttachmentsFilter, isSearch } from '../../helpers/elements'; import { pageCount } from '../../helpers/paging'; import { conversationByID } from '../../logic/conversations/conversationsSelectors'; import { load as loadAction, removeExpired, reset, updatePage } from '../../logic/elements/elementsActions'; import { dynamicTotal as dynamicTotalSelector, elementIDs as elementIDsSelector, elementsMap as elementsMapSelector, elements as elementsSelector, expectingEmpty as expectingEmptySelector, loadedEmpty as loadedEmptySelector, loading as loadingSelector, messagesToLoadMoreES as messagesToLoadMoreESSelector, params as paramsSelector, partialESSearch as partialESSearchSelector, pendingActions as pendingActionsSelector, placeholderCount as placeholderCountSelector, shouldResetCache as shouldResetCacheSelector, shouldSendRequest as shouldSendRequestSelector, shouldUpdatePage as shouldUpdatePageSelector, stateInconsistency as stateInconsistencySelector, totalReturned as totalReturnedSelector, } from '../../logic/elements/elementsSelectors'; import { messageByID } from '../../logic/messages/messagesSelectors'; import { RootState, useAppDispatch } from '../../logic/store'; import { Element } from '../../models/element'; import { Filter, SearchParameters, Sort } from '../../models/tools'; import { useElementsEvents } from '../events/useElementsEvents'; import { useExpirationCheck } from '../useExpirationCheck'; interface Options { conversationMode: boolean; labelID: string; page: number; sort: Sort; filter: Filter; search: SearchParameters; onPage: (page: number) => void; } interface ReturnValue { labelID: string; elements: Element[]; elementIDs: string[]; placeholderCount: number; loading: boolean; total: number | undefined; } interface UseElements { (options: Options): ReturnValue; } export const useElements: UseElements = ({ conversationMode, labelID, search, page, sort, filter, onPage }) => { const store = useStore<RootState>(); const dispatch = useAppDispatch(); const abortControllerRef = useRef<AbortController>(); const [conversationCounts = [], loadingConversationCounts] = useConversationCounts() as [ LabelCount[], boolean, Error, ]; const [messageCounts = [], loadingMessageCounts] = useMessageCounts() as [LabelCount[], boolean, Error]; const countValues = conversationMode ? conversationCounts : messageCounts; const countsLoading = conversationMode ? loadingConversationCounts : loadingMessageCounts; const { esStatus } = useEncryptedSearchContext(); const { esEnabled } = esStatus; const globalCache = useCache(); const params = { labelID, conversationMode, sort, filter, search, esEnabled }; const counts = { counts: countValues, loading: countsLoading }; const stateParams = useSelector(paramsSelector); const elementsMap = useSelector(elementsMapSelector); const pendingActions = useSelector(pendingActionsSelector); const elements = useSelector(elementsSelector); const elementIDs = useSelector(elementIDsSelector); const messagesToLoadMoreES = useSelector((state: RootState) => messagesToLoadMoreESSelector(state, { page, search, esStatus }) ); const shouldResetCache = useSelector((state: RootState) => shouldResetCacheSelector(state, { page, params })); const shouldSendRequest = useSelector((state: RootState) => shouldSendRequestSelector(state, { page, params })); const shouldUpdatePage = useSelector((state: RootState) => shouldUpdatePageSelector(state, { page })); const dynamicTotal = useSelector((state: RootState) => dynamicTotalSelector(state, { counts })); const placeholderCount = useSelector((state: RootState) => placeholderCountSelector(state, { counts })); const loading = useSelector((state: RootState) => loadingSelector(state, { page, params })); const totalReturned = useSelector((state: RootState) => totalReturnedSelector(state, { counts })); const expectingEmpty = useSelector((state: RootState) => expectingEmptySelector(state, { counts })); const loadedEmpty = useSelector(loadedEmptySelector); const partialESSearch = useSelector((state: RootState) => partialESSearchSelector(state, { search, esStatus })); const stateInconsistency = useSelector((state: RootState) => stateInconsistencySelector(state, { search, esStatus }) ); // Remove from cache expired elements useExpirationCheck(Object.values(elementsMap), (element) => { dispatch(removeExpired(element)); globalCache.delete(ConversationCountsModel.key); globalCache.delete(MessageCountsModel.key); }); // Main effect watching all inputs and responsible to trigger actions on the cache useEffect(() => { if (shouldResetCache) { dispatch(reset({ page, params: { labelID, conversationMode, sort, filter, esEnabled, search } })); } if (shouldSendRequest && pendingActions === 0 && !isSearch(search)) { void dispatch(loadAction({ abortController: abortControllerRef.current, conversationMode, page, params })); } if (shouldUpdatePage && messagesToLoadMoreES === 0) { dispatch(updatePage(page)); } }, [shouldResetCache, shouldSendRequest, shouldUpdatePage, messagesToLoadMoreES, pendingActions, search]); // Move to the last page if the current one becomes empty useEffect(() => { if (page === 0) { return; } if (!partialESSearch && (expectingEmpty || loadedEmpty)) { const count = dynamicTotal ? pageCount(dynamicTotal) : 0; if (count === 0) { onPage(0); } else if (page !== count - 1) { onPage(count - 1); } } }, [page, partialESSearch, expectingEmpty, loadedEmpty, dynamicTotal]); useEffect(() => { if (stateInconsistency) { if (!esEnabled) { const message = 'Elements list inconsistency error'; const state = store.getState(); const context = { conversationMode, labelID, search, // @ts-expect-error to fix later page, sort, filter, dynamicTotal, state: omit(state, ['elements']), ...state.elements, // Sentry limit depth in extra data, this optimize our feedback }; console.error(message, context); captureMessage(message, { extra: { context } }); } dispatch( reset({ page, params: { labelID, sort, filter, esEnabled, search, conversationMode }, beforeFirstLoad: !esEnabled && (isSearch(search) || hasAttachmentsFilter(filter)), }) ); } }, [stateInconsistency]); useElementsEvents(conversationMode, search); return { labelID: stateParams.labelID, elements, elementIDs, placeholderCount, loading, total: totalReturned, }; }; /** * Returns the element in the elements state for the given elementID */ export const useGetElementByID = () => { const store = useStore<RootState>(); return useCallback((elementID: string): Element | undefined => { return store.getState().elements.elements[elementID]; }, []); }; /** * This helper will get as much data as we can on the ids whatever the location of the data * Don't use this for optimistic for example */ export const useGetElementsFromIDs = () => { const store = useStore<RootState>(); return useCallback((elementIDs: string[]): Element[] => { const state = store.getState(); return elementIDs .map((ID: string) => { if (state.elements.elements[ID]) { return state.elements.elements[ID]; } const messageFromMessageState = messageByID(state, { ID }); const conversationFromConversationState = conversationByID(state, { ID }); return messageFromMessageState?.data || conversationFromConversationState?.Conversation; }) .filter(isTruthy); }, []); };
4,022
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useFolderNavigationHotkeys.test.tsx
import { KeyboardKey } from '@proton/shared/lib/interfaces'; import { ALMOST_ALL_MAIL, SHORTCUTS, SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings'; import { mockUseHistory, mockUseMailSettings } from '@proton/testing/index'; import { useFolderNavigationHotkeys } from './useFolderNavigationHotkeys'; jest.mock('@proton/shared/lib/shortcuts/helpers', () => ({ __esModule: true, isBusy: jest.fn(() => false) })); const event = { stopPropagation: jest.fn(), preventDefault: jest.fn(), } as unknown as KeyboardEvent; describe('useFolderNavigationHotkeys', () => { const mockedPush = jest.fn(); beforeEach(() => { mockUseHistory({ push: mockedPush }); mockUseMailSettings([{ Shortcuts: 1 }]); }); afterEach(() => { mockedPush.mockClear(); }); it('should return correct helper', () => { const shortcuts = useFolderNavigationHotkeys(); expect(shortcuts).toHaveLength(8); const firstShortCut = shortcuts[0]; expect(firstShortCut).toStrictEqual(['G', 'I', expect.anything()]); (firstShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/inbox'); mockedPush.mockClear(); const secondShortCut = shortcuts[1]; expect(secondShortCut).toStrictEqual(['G', 'D', expect.anything()]); (secondShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/drafts'); mockedPush.mockClear(); const thirdShortCut = shortcuts[2]; expect(thirdShortCut).toStrictEqual(['G', 'E', expect.anything()]); (thirdShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/sent'); mockedPush.mockClear(); const fourthShortCut = shortcuts[3]; expect(fourthShortCut).toStrictEqual(['G', KeyboardKey.Star, expect.anything()]); (fourthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/starred'); mockedPush.mockClear(); const fifthShortCut = shortcuts[4]; expect(fifthShortCut).toStrictEqual(['G', 'A', expect.anything()]); (fifthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/archive'); mockedPush.mockClear(); const sixthShortCut = shortcuts[5]; expect(sixthShortCut).toStrictEqual(['G', 'S', expect.anything()]); (sixthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/spam'); mockedPush.mockClear(); const seventhShortCut = shortcuts[6]; expect(seventhShortCut).toStrictEqual(['G', 'T', expect.anything()]); (seventhShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/trash'); mockedPush.mockClear(); const eigthShortCut = shortcuts[7]; expect(eigthShortCut).toStrictEqual(['G', 'M', expect.anything()]); (eigthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/all-mail'); mockedPush.mockClear(); }); describe('when shortcut is set to false', () => { it('should return no shortcut', () => { mockUseMailSettings([{ Shortcuts: SHORTCUTS.DISABLED }]); const shortcuts = useFolderNavigationHotkeys(); expect(shortcuts).toHaveLength(0); }); }); describe('when ShowMoved is true', () => { it('should navigate to correct url', () => { mockUseMailSettings([{ Shortcuts: SHORTCUTS.ENABLED, ShowMoved: SHOW_MOVED.DRAFTS }]); const shortcuts = useFolderNavigationHotkeys(); expect(shortcuts).toHaveLength(8); const secondShortCut = shortcuts[1]; expect(secondShortCut).toStrictEqual(['G', 'D', expect.anything()]); (secondShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/all-drafts'); mockedPush.mockClear(); }); }); describe('when AlmostAllMail is true', () => { it('should navigate to correct url', () => { mockUseMailSettings([{ Shortcuts: SHORTCUTS.ENABLED, AlmostAllMail: ALMOST_ALL_MAIL.ENABLED }]); const shortcuts = useFolderNavigationHotkeys(); expect(shortcuts).toHaveLength(8); const eigthShortCut = shortcuts[7]; expect(eigthShortCut).toStrictEqual(['G', 'M', expect.anything()]); (eigthShortCut[2] as (e: KeyboardEvent) => void)(event); expect(mockedPush).toHaveBeenCalledTimes(1); expect(mockedPush).toHaveBeenCalledWith('/almost-all-mail'); mockedPush.mockClear(); }); }); });
4,023
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useFolderNavigationHotkeys.ts
import { useHistory } from 'react-router-dom'; import { HotkeyTuple } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { KeyboardKey } from '@proton/shared/lib/interfaces'; import { SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings'; import { isBusy } from '@proton/shared/lib/shortcuts/helpers'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { LABEL_IDS_TO_HUMAN } from '../../constants'; const { DRAFTS, ALL_DRAFTS, SENT, ALL_SENT, TRASH, SPAM, ARCHIVE, INBOX, STARRED, ALL_MAIL, ALMOST_ALL_MAIL } = MAILBOX_LABEL_IDS; export const useFolderNavigationHotkeys = (): HotkeyTuple[] => { const history = useHistory<any>(); const { Shortcuts, ShowMoved, AlmostAllMail } = useMailModel('MailSettings'); const navigateTo = (labelID: MAILBOX_LABEL_IDS) => { history.push(`/${LABEL_IDS_TO_HUMAN[labelID]}`); }; return Shortcuts ? [ [ 'G', 'I', (e) => { if (!isBusy(e)) { e.stopPropagation(); e.preventDefault(); navigateTo(INBOX); } }, ], [ 'G', 'D', (e) => { if (!isBusy(e)) { e.stopPropagation(); e.preventDefault(); navigateTo(hasBit(ShowMoved, SHOW_MOVED.DRAFTS) ? ALL_DRAFTS : DRAFTS); } }, ], [ 'G', 'E', (e) => { if (!isBusy(e)) { e.stopPropagation(); e.preventDefault(); navigateTo(hasBit(ShowMoved, SHOW_MOVED.SENT) ? ALL_SENT : SENT); } }, ], [ 'G', KeyboardKey.Star, (e) => { if (!isBusy(e)) { e.stopPropagation(); e.preventDefault(); navigateTo(STARRED); } }, ], [ 'G', 'A', (e) => { if (!isBusy(e)) { e.stopPropagation(); e.preventDefault(); navigateTo(ARCHIVE); } }, ], [ 'G', 'S', (e) => { if (!isBusy(e)) { e.stopPropagation(); e.preventDefault(); navigateTo(SPAM); } }, ], [ 'G', 'T', (e) => { if (!isBusy(e)) { e.stopPropagation(); e.preventDefault(); navigateTo(TRASH); } }, ], [ 'G', 'M', (e) => { if (!isBusy(e)) { e.stopPropagation(); e.preventDefault(); navigateTo(AlmostAllMail ? ALMOST_ALL_MAIL : ALL_MAIL); } }, ], ] : []; };
4,024
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useMailboxFavicon.ts
import { Location } from 'history'; import { FeatureCode } from '@proton/components/containers'; import { useConversationCounts, useDynamicFavicon, useFeature, useMessageCounts } from '@proton/components/hooks'; import useMailModel from 'proton-mail/hooks/useMailModel'; import favicons, { baseFavicon } from '../../../assets/favicons'; import { getCountersByLabelId } from '../../helpers/counter'; import { isConversationMode } from '../../helpers/mailSettings'; export const useMailboxFavicon = (labelID: string, location: Location) => { const mailSettings = useMailModel('MailSettings'); const [conversationCounts] = useConversationCounts(); const [messageCounts] = useMessageCounts(); const conversationMode = isConversationMode(labelID, mailSettings, location); const counters = conversationMode ? conversationCounts : messageCounts; const countersByLabelId = getCountersByLabelId(counters); const unreads = countersByLabelId[labelID]?.Unread ?? 0; const shouldDisplayUnreadFavicon = useFeature(FeatureCode.UnreadFavicon).feature?.Value && mailSettings.UnreadFavicon; const unreadFavicon = !unreads ? baseFavicon : unreads > 99 ? favicons[100] : favicons[unreads]; const faviconSrc = !shouldDisplayUnreadFavicon ? baseFavicon : unreadFavicon; useDynamicFavicon(faviconSrc); };
4,025
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useMailboxFocus.tsx
import { MutableRefObject, useCallback, useEffect, useRef, useState } from 'react'; import { useHandler } from '@proton/components'; import useIsMounted from '@proton/hooks/useIsMounted'; export interface MailboxFocusContext { elementIDs: string[]; page: number; showList: boolean; listRef: MutableRefObject<HTMLElement | null>; labelID: string; isComposerOpened: boolean; } export const useMailboxFocus = ({ elementIDs, page, showList, listRef, labelID, isComposerOpened, }: MailboxFocusContext) => { const isMounted = useIsMounted(); const [focusIndex, setFocusIndex] = useState<number>(); const getFocusedId = useCallback( () => (focusIndex !== undefined ? elementIDs[focusIndex] : undefined), [focusIndex, elementIDs] ); const labelIDRef = useRef(labelID); const focusedIDRef = useRef(getFocusedId()); const handleFocus = useHandler((index) => setFocusIndex(index)); const focusOnElementByIndex = (index: number) => { // Selecting on index may fail during loading time with placeholders // Selecting by sibblings is a bit more stable but we have to skip "ListSettings" const element = listRef.current?.querySelector( `.item-container-wrapper:nth-child(${index + 1}) [data-shortcut-target="item-container"]` ) as HTMLElement; element?.focus(); }; const focusOnLastMessage = useCallback(() => { const messages = document.querySelectorAll('[data-shortcut-target="message-container"]'); if (messages.length) { const lastMessage = messages[messages.length - 1] as HTMLElement; lastMessage.focus(); setFocusIndex(undefined); return; } const trashWarning = document.querySelector('[data-shortcut-target="trash-warning"]') as HTMLElement; trashWarning?.focus(); }, []); const focusOnElementByID = (elementID?: string) => { if (!elementID) { return; } const index = elementIDs.findIndex((id) => id === elementID); setFocusIndex(index); }; useEffect(() => { if (labelIDRef.current !== labelID) { setFocusIndex(undefined); focusedIDRef.current = undefined; labelIDRef.current = labelID; return; } if (isComposerOpened || !elementIDs.length) { return; } // keep focus on the same element if new messages are coming in if (focusedIDRef.current && elementIDs.includes(focusedIDRef.current)) { setTimeout(() => { if (isMounted()) { focusOnElementByID(focusedIDRef.current); } }); return; } // keep focus position when updating the list (moving/deleting items) if (typeof focusIndex !== 'undefined') { if (elementIDs[focusIndex]) { setTimeout(() => focusOnElementByIndex(focusIndex)); return; } setTimeout(() => focusOnElementByIndex(elementIDs.length - 1)); } }, [labelID, elementIDs]); // Show flag change: focus on current index if defined fallback on first useEffect(() => { if (showList) { if (focusIndex !== undefined) { focusOnElementByIndex(focusIndex); } else if (elementIDs.length) { setFocusIndex(0); } } }, [showList]); // Page change: focus on first element useEffect(() => { if (showList && elementIDs.length) { setFocusIndex(0); } }, [page]); useEffect(() => { if (typeof focusIndex !== 'undefined') { focusOnElementByIndex(focusIndex); } focusedIDRef.current = getFocusedId(); }, [focusIndex]); return { focusIndex, getFocusedId, setFocusIndex, handleFocus, focusOnLastMessage, }; };
4,026
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useMailboxHotkeys.tsx
import { useRef } from 'react'; import { useHistory } from 'react-router-dom'; import { Location } from 'history'; import { HotkeyTuple, useFolders, useHotkeys } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { KeyboardKey } from '@proton/shared/lib/interfaces'; import { VIEW_LAYOUT } from '@proton/shared/lib/mail/mailSettings'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { isStarred } from '../../helpers/elements'; import { getFolderName, labelIncludes } from '../../helpers/labels'; import { isConversationMode } from '../../helpers/mailSettings'; import { setParamsInLocation } from '../../helpers/mailboxUrl'; import { Element } from '../../models/element'; import { Filter } from '../../models/tools'; import { MARK_AS_STATUS, useMarkAs } from '../actions/useMarkAs'; import { useMoveToFolder } from '../actions/useMoveToFolder'; import { usePermanentDelete } from '../actions/usePermanentDelete'; import { useStar } from '../actions/useStar'; import { useGetElementsFromIDs } from './useElements'; import { useFolderNavigationHotkeys } from './useFolderNavigationHotkeys'; const { TRASH, SPAM, ARCHIVE, INBOX, DRAFTS, ALL_DRAFTS, SENT, ALL_SENT } = MAILBOX_LABEL_IDS; export interface MailboxHotkeysContext { labelID: string; elementID?: string; messageID?: string; elementIDs: string[]; checkedIDs: string[]; selectedIDs: string[]; focusIndex?: number; columnLayout: boolean; isMessageOpening: boolean; location: Location; } export interface MailboxHotkeysHandlers { handleBack: () => void; getFocusedId: () => string | undefined; setFocusIndex: (index?: number) => void; focusOnLastMessage: () => void; handleElement: (ID: string, preventComposer?: boolean) => void; handleCheck: (IDs: string[], checked: boolean, replace: boolean) => void; handleCheckAll: (checked: boolean) => void; handleCheckOnlyOne: (ID: string) => void; handleCheckRange: (ID: string) => void; handleFilter: (filter: Filter) => void; showCommander: (status: boolean) => void; } export const useMailboxHotkeys = ( { labelID, elementID, messageID, elementIDs, checkedIDs, selectedIDs, focusIndex, columnLayout, isMessageOpening, location, }: MailboxHotkeysContext, { handleBack, getFocusedId, setFocusIndex, focusOnLastMessage, handleElement, handleCheck, handleCheckAll, handleCheckOnlyOne, handleCheckRange, handleFilter, showCommander, }: MailboxHotkeysHandlers ) => { const mailSettings = useMailModel('MailSettings'); const { Shortcuts, ViewLayout } = mailSettings; const getElementsFromIDs = useGetElementsFromIDs(); const history = useHistory<any>(); const [folders] = useFolders(); const folderNavigationHotkeys = useFolderNavigationHotkeys(); const elementIDForList = checkedIDs.length ? undefined : elementID; const elementRef = useRef<HTMLDivElement>(null); const labelDropdownToggleRef = useRef<() => void>(noop); const moveDropdownToggleRef = useRef<() => void>(noop); const { moveToFolder, moveScheduledModal, moveSnoozedModal, moveAllModal, moveToSpamModal } = useMoveToFolder(); const star = useStar(); const markAs = useMarkAs(); const { handleDelete: permanentDelete, modal: permanentDeleteModal } = usePermanentDelete(labelID); // Disable selection shortcut in row mode when consulting an message // If no element is selected, it means that the user is on the message list, where we want the shortcut to be enabled const canSelectItem = ViewLayout === VIEW_LAYOUT.COLUMN || !elementID; const getElementsForShortcuts = () => { let elements: Element[] = []; if (elementID) { elements = getElementsFromIDs([elementID]); } if (checkedIDs.length) { elements = getElementsFromIDs(checkedIDs); } return elements; }; const moveElementsTo = async (e: KeyboardEvent, LabelID: MAILBOX_LABEL_IDS) => { const elements = getElementsForShortcuts(); if (!elements.length) { return; } e.stopPropagation(); const folderName = getFolderName(LabelID, folders); await moveToFolder(elements, LabelID, folderName, labelID, false); if (elementIDForList) { handleBack(); } }; const shortcutHandlers: HotkeyTuple[] = [ ...folderNavigationHotkeys, [ 'ArrowRight', (e) => { if (columnLayout) { e.preventDefault(); e.stopPropagation(); focusOnLastMessage(); } }, ], [ 'ArrowLeft', (e) => { e.preventDefault(); const sidebarLink = document.querySelector( '[data-shortcut-target~="navigation-link"][aria-current="page"]' ) as HTMLElement; if (sidebarLink) { sidebarLink.focus(); setFocusIndex(undefined); } }, ], [ ['Meta', 'K'], (e) => { e.preventDefault(); showCommander(true); }, ], [ ['Meta', 'ArrowUp'], (e) => { e.preventDefault(); setFocusIndex(0); }, ], [ 'ArrowUp', (e) => { e.preventDefault(); const previousIndex = focusIndex !== undefined ? Math.max(0, focusIndex - 1) : elementIDs.length - 1; setFocusIndex(previousIndex); }, ], [ ['Meta', 'ArrowDown'], (e) => { e.preventDefault(); setFocusIndex(elementIDs.length - 1); }, ], [ 'ArrowDown', (e) => { e.preventDefault(); const nextIndex = focusIndex !== undefined ? Math.min(elementIDs.length - 1, focusIndex + 1) : 0; setFocusIndex(nextIndex); }, ], [ 'Enter', (e) => { const id = getFocusedId(); const { activeElement } = document; if (id && activeElement?.tagName.toLocaleLowerCase() !== 'button') { e.stopPropagation(); handleElement(id); } }, ], [ ['Meta', 'A'], (e) => { if (Shortcuts) { e.preventDefault(); e.stopPropagation(); const allChecked = elementIDs.length === checkedIDs.length; handleCheck(elementIDs, !allChecked, true); } }, ], [ 'X', (e) => { if (Shortcuts) { const id = getFocusedId(); if (id) { e.preventDefault(); handleCheckOnlyOne(id); } } }, ], [ ['Shift', 'X'], (e) => { if (Shortcuts) { const id = getFocusedId(); if (id) { e.preventDefault(); handleCheckRange(id); } } }, ], [ KeyboardKey.Spacebar, (e) => { const id = getFocusedId(); const { activeElement } = document; if (id && activeElement?.tagName.toLocaleLowerCase() !== 'button' && canSelectItem) { e.preventDefault(); handleCheckOnlyOne(id); } }, ], [ ['Shift', KeyboardKey.Spacebar], (e) => { const id = getFocusedId(); if (id) { e.preventDefault(); handleCheckRange(id); } }, ], [ 'Escape', (e) => { if (checkedIDs.length) { e.stopPropagation(); handleCheckAll(false); } const tmpIndex = focusIndex; history.push( setParamsInLocation(history.location, { labelID, }) ); setFocusIndex(tmpIndex); }, ], [ ['Shift', 'A'], (e) => { if (Shortcuts) { e.stopPropagation(); handleFilter({}); } }, ], [ ['Shift', 'U'], (e) => { if (Shortcuts) { e.stopPropagation(); handleFilter({ Unread: 1 }); } }, ], [ 'U', async (e) => { if (Shortcuts) { const elements = getElementsForShortcuts(); if (!elements.length) { return; } e.stopPropagation(); handleBack(); markAs(elements, labelID, MARK_AS_STATUS.UNREAD); } }, ], [ 'R', async (e) => { if (Shortcuts) { const elements = getElementsForShortcuts(); if (!elements.length) { return; } e.stopPropagation(); markAs(elements, labelID, MARK_AS_STATUS.READ); } }, ], [ 'A', async (e) => { if (Shortcuts) { await moveElementsTo(e, ARCHIVE); } }, ], [ 'I', async (e) => { if (Shortcuts) { await moveElementsTo(e, INBOX); } }, ], [ 'S', async (e) => { if (Shortcuts) { await moveElementsTo(e, SPAM); } }, ], [ KeyboardKey.Star, async (e) => { if (Shortcuts) { const elements = getElementsForShortcuts(); if (!elements.length) { return; } e.stopPropagation(); const isAllStarred = elements.filter((element) => isStarred(element)).length === elements.length; await star(elements, !isAllStarred); } }, ], [ 'T', async (e) => { if (Shortcuts) { await moveElementsTo(e, TRASH); } }, ], [ ['Meta', 'Backspace'], async () => { if (Shortcuts && labelIncludes(labelID, DRAFTS, ALL_DRAFTS, SPAM, TRASH, SENT, ALL_SENT)) { const elements = getElementsForShortcuts(); if (!elements.length) { return; } await permanentDelete(elements.map((e) => e.ID).filter(isTruthy)); } }, ], [ 'L', (e) => { if (Shortcuts && selectedIDs.length) { e.preventDefault(); labelDropdownToggleRef.current?.(); } }, ], [ 'M', (e) => { if (Shortcuts && selectedIDs.length) { e.preventDefault(); moveDropdownToggleRef.current?.(); } }, ], [ 'K', (e) => { if (Shortcuts && elementID && !isMessageOpening) { e.preventDefault(); const ID = !isConversationMode(labelID, mailSettings, location) && messageID ? messageID : elementID; const index = elementIDs.findIndex((id: string) => id === ID); const previousIndex = index !== null ? Math.max(0, index - 1) : elementIDs.length - 1; if (index === previousIndex) { return; } setFocusIndex(previousIndex); handleElement(elementIDs[previousIndex], true); } }, ], [ 'J', (e) => { if (Shortcuts && elementID && !isMessageOpening) { e.preventDefault(); const ID = !isConversationMode(labelID, mailSettings, location) && messageID ? messageID : elementID; const index = elementIDs.findIndex((id: string) => id === ID); const nextIndex = index !== null ? Math.min(elementIDs.length - 1, index + 1) : 0; if (index === nextIndex) { return; } setFocusIndex(nextIndex); handleElement(elementIDs[nextIndex], true); } }, ], [ 'Tab', () => { const focusedElement = document.querySelector(':focus'); if (focusedElement && focusedElement !== elementRef.current) { return; } const element = (document.querySelector( '[data-shortcut-target="item-container"][data-shortcut-target-selected="true"]' ) as HTMLElement) || (document.querySelector('[data-shortcut-target="item-container"]') as HTMLElement); element?.focus(); }, ], ]; useHotkeys(elementRef, shortcutHandlers); return { elementRef, labelDropdownToggleRef, moveToFolder, moveDropdownToggleRef, moveScheduledModal, moveSnoozedModal, permanentDeleteModal, moveAllModal, moveToSpamModal, }; };
4,027
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useMailboxPageTitle.ts
import { useEffect } from 'react'; import { Location } from 'history'; import { FeatureCode, useConversationCounts, useFeature, useFolders, useLabels, useMessageCounts, useUser, } from '@proton/components'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { getCountersByLabelId } from '../../helpers/counter'; import { getLabelName } from '../../helpers/labels'; import { isConversationMode } from '../../helpers/mailSettings'; export const useMailboxPageTitle = (labelID: string, location: Location) => { const mailSettings = useMailModel('MailSettings'); const [labels] = useLabels(); const [folders] = useFolders(); const [user] = useUser(); const [conversationCounts] = useConversationCounts(); const [messageCounts] = useMessageCounts(); const shouldDisplayUnreadsInPageTitle = !( useFeature(FeatureCode.UnreadFavicon).feature?.Value && mailSettings.UnreadFavicon ); useEffect(() => { const conversationMode = isConversationMode(labelID, mailSettings, location); const counters = conversationMode ? conversationCounts : messageCounts; const countersByLabelId = getCountersByLabelId(counters); const unreads = countersByLabelId[labelID]?.Unread ?? 0; const unreadString = unreads > 0 ? `(${unreads}) ` : ''; const labelName = getLabelName(labelID, labels, folders); const mainTitle = `${labelName} | ${user.Email} | ${MAIL_APP_NAME}`; document.title = shouldDisplayUnreadsInPageTitle ? `${unreadString}${mainTitle}` : mainTitle; }, [ labelID, mailSettings, user, labels, folders, conversationCounts, messageCounts, shouldDisplayUnreadsInPageTitle, ]); };
4,028
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useNewEmailNotification.ts
import { useHistory } from 'react-router-dom'; import { History } from 'history'; import { c } from 'ttag'; import { useFolders, useSubscribeEventManager } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { create } from '@proton/shared/lib/helpers/desktopNotification'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { isImported } from '@proton/shared/lib/mail/messages'; import notificationIcon from '../../assets/notification.png'; import { isConversationMode } from '../../helpers/mailSettings'; import { setParamsInLocation } from '../../helpers/mailboxUrl'; import useMailModel from '../../hooks/useMailModel'; import { isElementReminded } from '../../logic/snoozehelpers'; import { Event } from '../../models/event'; const displayNotification = ( Message: Message, history: History<unknown>, mailSettings: any, notifier: any, onOpenElement: () => void ) => { const { Subject, Sender, ID, ConversationID, LabelIDs } = Message; const sender = Sender.Name || Sender.Address; const title = c('Desktop notification title').t`New email received`; const labelID = LabelIDs.find((labelID) => notifier.includes(labelID)) || MAILBOX_LABEL_IDS.ALL_MAIL; return create(title, { tag: ID, body: c('Desktop notification body').t`From: ${sender} - ${Subject}`, icon: notificationIcon, onClick() { // Remove the search keyword from the URL to find the message or conversation. Otherwise we can have a 'Conversation does not exists' error. const cleanHistoryLocation = { ...history.location, hash: '' }; window.focus(); history.push( setParamsInLocation(cleanHistoryLocation, { labelID, elementID: isConversationMode(labelID, mailSettings, cleanHistoryLocation) ? ConversationID : ID, }) ); onOpenElement(); }, }); }; const useNewEmailNotification = (onOpenElement: () => void) => { const history = useHistory(); const mailSettings = useMailModel('MailSettings'); const [folders = []] = useFolders(); const notifier = [ MAILBOX_LABEL_IDS.INBOX, MAILBOX_LABEL_IDS.STARRED, ...folders.filter(({ Notify }) => Notify).map(({ ID }) => ID), ]; useSubscribeEventManager(({ Messages = [], Conversations = [] }: Event) => { Messages.filter( ({ Action, Message }) => !isImported(Message) && Action === 1 && Message?.Unread === 1 && Message.LabelIDs.some((labelID) => notifier.includes(labelID)) ).forEach(({ Message }) => { displayNotification(Message as Message, history, mailSettings, notifier, onOpenElement); }); // Used to display the notification for the reminded messages Conversations.filter(({ Action, Conversation }) => Action === 3 && isElementReminded(Conversation)).forEach( ({ Conversation }) => { Messages.filter(({ Message }) => Message?.ConversationID === Conversation?.ID).forEach(({ Message }) => displayNotification(Message as Message, history, mailSettings, notifier, onOpenElement) ); } ); }); }; export default useNewEmailNotification;
4,029
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/usePageHotkeys.tsx
import { useRef } from 'react'; import { HotkeyTuple, useHotkeys } from '@proton/components'; import { KeyboardKey } from '@proton/shared/lib/interfaces'; import { isBusy } from '@proton/shared/lib/shortcuts/helpers'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { MESSAGE_ACTIONS } from '../../constants'; import { useOnCompose } from '../../containers/ComposeProvider'; import { ComposeTypes } from '../composer/useCompose'; export interface PageHotkeysHandlers { onOpenShortcutsModal: () => void; } export const usePageHotkeys = ({ onOpenShortcutsModal }: PageHotkeysHandlers) => { const { Shortcuts } = useMailModel('MailSettings'); const onCompose = useOnCompose(); const documentRef = useRef(window.document); const shortcutHandlers: HotkeyTuple[] = [ [ KeyboardKey.QuestionMark, (e) => { if (!isBusy(e)) { onOpenShortcutsModal(); } }, ], [ 'Tab', () => { const focusedElement = document.querySelector(':focus'); if (focusedElement) { return; } const element = (document.querySelector( '[data-shortcut-target="item-container"][data-shortcut-target-selected="true"]' ) as HTMLElement) || (document.querySelector('[data-shortcut-target="item-container"]') as HTMLElement); element?.focus(); }, ], [ KeyboardKey.Slash, (e) => { if (Shortcuts && !isBusy(e)) { e.preventDefault(); const button = document.querySelector('[data-shorcut-target="searchbox-button"]') as HTMLElement; button?.dispatchEvent( new MouseEvent('click', { view: window, bubbles: true, cancelable: false, }) ); } }, ], [ 'N', (e) => { if (Shortcuts && !isBusy(e)) { onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.NEW }); } }, ], ]; useHotkeys(documentRef, shortcutHandlers); };
4,030
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/usePreLoadElements.ts
import { useEffect } from 'react'; import { useSelector } from 'react-redux'; import { unwrapResult } from '@reduxjs/toolkit'; import { FeatureCode } from '@proton/components/containers'; import { useFeature } from '@proton/components/hooks'; import { isConversation } from 'proton-mail/helpers/elements'; import { allConversations } from 'proton-mail/logic/conversations/conversationsSelectors'; import { Element } from 'proton-mail/models/element'; import { findMessageToExpand } from '../../helpers/message/messageExpandable'; import { load } from '../../logic/conversations/conversationsActions'; import { initialize } from '../../logic/messages/read/messagesReadActions'; import { useAppDispatch } from '../../logic/store'; interface Props { elements: Element[]; labelID: string; loading: boolean; } const usePreLoadElements = ({ elements, labelID, loading }: Props) => { const dispatch = useAppDispatch(); const { feature } = useFeature(FeatureCode.NumberOfPreloadedConversations); const numberOfPreloadedConversations = feature?.Value || 0; const firstElements = elements.slice(0, numberOfPreloadedConversations); const conversations = useSelector(allConversations); const isAllConversation = elements.every((element) => isConversation(element)); useEffect(() => { const conversationsIDs = conversations.map((item) => item?.Conversation.ID); const preload = async () => { try { await Promise.all( firstElements.map(async ({ ID }) => { const conversationAlreadyCached = conversationsIDs.includes(ID); if (!conversationAlreadyCached) { const resultAction = await dispatch( load({ silentFetch: true, conversationID: ID, messageID: undefined }) ); const conversationResult = await unwrapResult(resultAction); const { Messages } = conversationResult; const messageToExpand = findMessageToExpand(labelID, Messages); if (messageToExpand) { dispatch(initialize({ localID: messageToExpand.ID, data: messageToExpand })); } } }) ); } catch { // ignore } }; if (!loading && firstElements.length > 0 && isAllConversation) { void preload(); } }, [firstElements.join(), labelID, loading]); // "firstElementIDs.join()" makes firstElementIDs dependency stable }; export default usePreLoadElements;
4,031
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/mailbox/useWelcomeFlag.ts
import { DependencyList, useEffect, useState } from 'react'; import { useAuthentication } from '@proton/components'; import { getItem, setItem } from '@proton/shared/lib/helpers/sessionStorage'; /** * Returns true the first time (depending on deps) it's called after a login, false every time after */ export const useWelcomeFlag = (deps: DependencyList) => { const { UID } = useAuthentication(); const [welcomeFlag, setWelcomeFlag] = useState(() => { const key = `w-${UID}`; const hasSession = getItem(key, '0'); setItem(key, '1'); return hasSession === '0'; }); const [welcomeShown, setWelcomeShown] = useState(false); useEffect(() => { if (!welcomeShown) { setWelcomeFlag(true); setWelcomeShown(true); } else { setWelcomeFlag(false); } }, deps); return welcomeFlag; };
4,032
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useFutureTimeDate.test.tsx
import { act, renderHook } from '@testing-library/react-hooks'; import { addDays, addHours, format, isSameDay, isSameHour, set, startOfTomorrow, startOfYesterday } from 'date-fns'; import { dateLocale } from '@proton/shared/lib/i18n'; import { getMinScheduleTime } from '../../helpers/schedule'; import useFutureTimeDate from './useFutureTimeDate'; describe('useFutureTimeDate', () => { it('should return no errors and the new date if date is changed to tomorrow', () => { const tomorrow = startOfTomorrow(); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); act(() => { result.current.handleChangeDate(tomorrow); }); expect(result.current.errorDate).toBeUndefined(); expect(result.current.date).toEqual(tomorrow); }); it('should not change anything if no date is passed to handleChangeDate', () => { const date = new Date(); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: date })); act(() => { result.current.handleChangeDate(); }); expect(result.current.errorDate).toBeUndefined(); expect(result.current.date).toEqual(date); }); it('should return an error if date is changed to yesterday', () => { const yesterday = startOfYesterday(); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); act(() => { result.current.handleChangeDate(yesterday); }); expect(result.current.errorDate).toBe('Choose a date in the future.'); }); it('should return custom error if date is larger than max day', () => { const future = addDays(new Date(), 20); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date(), maxDaysAllowed: 10, maxDateErrorMessage: 'Custom error' }) ); act(() => { result.current.handleChangeDate(future); }); expect(isSameDay(addDays(new Date(), 10), result.current.maxDate ?? startOfTomorrow())).toBe(true); expect(result.current.errorDate).toBe('Custom error'); }); it('should return next available slot when changing date to today with time before now', () => { const today = new Date(); const before = set(today, { hours: today.getHours() - 2 }); // Set the time to the start of the hour to avoid issue if we're more than 30 minutes into the hour const defaultDate = set(today, { minutes: 0, seconds: 0, milliseconds: 0 }); const { result } = renderHook(() => useFutureTimeDate({ defaultDate })); act(() => { result.current.handleChangeDate(before); }); const nextAvailableTime = getMinScheduleTime(before); // make sure the test fails if nextAvailableTime is undefined by comparing it to yesterday expect(isSameDay(result.current.date, nextAvailableTime ?? startOfYesterday())).toBe(true); expect(isSameHour(result.current.date, nextAvailableTime ?? startOfYesterday())).toBe(true); }); it('should return no errors and the new time if time is changed to the future', () => { const inTwoHours = addHours(new Date(), 2); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); act(() => { result.current.handleChangeTime(inTwoHours); }); expect(result.current.errorTime).toBeUndefined(); expect(result.current.time).toEqual(inTwoHours); }); it('should return today if date is set to today', () => { const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); const today = new Date(); let res = result.current.formatDateInput(today, { code: 'en-US' }); expect(res).toEqual('Today'); const tomorrow = startOfTomorrow(); res = result.current.formatDateInput(tomorrow, { code: 'en-US' }); expect(res).toEqual('Tomorrow'); const inTwoDays = addDays(new Date(), 2); const formatted = format(inTwoDays, 'PP', { locale: dateLocale }); res = result.current.formatDateInput(inTwoDays, dateLocale); expect(res).toEqual(formatted); }); it('should update date and time', () => { const randomDateInFuture = set(new Date(), { year: 2100, month: 10, date: 10, hours: 10, minutes: 10, seconds: 10, }); const { result } = renderHook(() => useFutureTimeDate({ defaultDate: new Date() })); act(() => { result.current.updateDateAndTime(randomDateInFuture); }); expect(result.current.date).toEqual(randomDateInFuture); expect(result.current.time).toEqual(randomDateInFuture); }); });
4,033
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useFutureTimeDate.tsx
import { useEffect, useMemo, useState } from 'react'; import { addDays, addSeconds, endOfDay, format, getHours, getMinutes, isBefore, isToday, isTomorrow, set, startOfToday, } from 'date-fns'; import { c } from 'ttag'; import { FUTURE_MESSAGES_BUFFER } from '../../constants'; import { getMinScheduleTime } from '../../helpers/schedule'; interface Props { defaultDate: Date; maxDaysAllowed?: number; maxDateErrorMessage?: string; } const useFutureTimeDate = ({ defaultDate, maxDaysAllowed, maxDateErrorMessage }: Props) => { const [date, setDate] = useState(defaultDate); const [time, setTime] = useState(defaultDate); const [errorTime, setErrorTime] = useState<string>(); // Refresh error time each second so that the user cannot send a message in the past // If we don't refresh it, a user can create a schedule message, select a date in the future. // If he waits too much, the sending will still be possible, but the date will become from the past // Leading to a not user-friendly error useEffect(() => { const updateErrorTime = () => { /* If the user chose a time (Hour + minutes) before the hour of the actual day, the time input returns the date for the next day * Ex : This is Jan, 1 2021 at 9:00AM. The user wants to send the scheduled today at 8:00PM, but in the time input he lets 'AM' * => The Time input is returning the date Jan, 2 2021 at 8:00AM * From our side we are using hour + minutes from the returned date of the time input to build the date when we want to send the scheduled * To check if the user is making an error, we need to compare the Time input value with the current date */ const timeInputDate = startOfToday(); timeInputDate.setHours(time.getHours(), time.getMinutes()); // It should be impossible to schedule a message within the next 120s const limit = addSeconds(new Date(), FUTURE_MESSAGES_BUFFER); // If the scheduled date is in the past or within the next 120s, we need to disable the schedule button const isDateToEarly = isToday(date) && timeInputDate <= limit; const error = isDateToEarly ? c('Error').t`Choose a date in the future.` : undefined; setErrorTime(error); }; const handle = setInterval(updateErrorTime, 1000); return () => { clearInterval(handle); }; }, [date, time]); const minDate = startOfToday(); const maxDate = maxDaysAllowed ? addDays(minDate, maxDaysAllowed) : undefined; const scheduleDateTime = useMemo(() => { const tmpDate = date; const hours = getHours(time); const minutes = getMinutes(time); tmpDate.setHours(hours, minutes, 0, 0); return tmpDate; }, [date, time]); const errorDate = useMemo(() => { if (date < minDate) { return c('Error').t`Choose a date in the future.`; } if (maxDate && date > maxDate) { return maxDateErrorMessage; } return undefined; }, [date]); const disabled = useMemo(() => { const min = addSeconds(Date.now(), FUTURE_MESSAGES_BUFFER); return !date || !time || scheduleDateTime < min || (maxDate && scheduleDateTime > endOfDay(maxDate)); }, [date, time, scheduleDateTime, minDate, maxDate]); const handleChangeDate = (selectedDate?: Date) => { if (!selectedDate) { return; } // It's possible that the selected time is in the past when changing date to today. // In this case, we need to update the time to the next available time const newTime = set(selectedDate, { hours: getHours(time), minutes: getMinutes(time) }); const nextAvailableTime = getMinScheduleTime(newTime); if (isToday(selectedDate) && isBefore(newTime, new Date()) && nextAvailableTime) { setTime(nextAvailableTime); } setDate(selectedDate); }; const handleChangeTime = (selectedTime: Date) => { setTime(selectedTime); }; const formatDateInput = (value: Date, locale: Locale) => { if (isToday(value)) { return c('Date label').t`Today`; } if (isTomorrow(value)) { return c('Date label').t`Tomorrow`; } return format(value, 'PP', { locale }); }; const updateDateAndTime = (date: Date) => { setDate(date); setTime(date); }; return { date, time, disabled, handleChangeDate, handleChangeTime, scheduleDateTime, minDate, maxDate, formatDateInput, errorDate, errorTime, updateDateAndTime, }; }; export default useFutureTimeDate;
4,034
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useGetMessageKeys.ts
import { useCallback } from 'react'; import { useGetAddressKeys } from '@proton/components'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { splitKeys } from '@proton/shared/lib/keys/keys'; import { PublicPrivateKey } from '../../logic/messages/messagesTypes'; export type GetMessageKeys = (message: Pick<Message, 'AddressID'>) => Promise<PublicPrivateKey>; export type UseGetMessageKeys = () => GetMessageKeys; /** * Add user public and private keys to the MessageExtended if not already there */ export const useGetMessageKeys: UseGetMessageKeys = () => { const getAddressKeys = useGetAddressKeys(); return useCallback( async (message: Pick<Message, 'AddressID'>) => { const { publicKeys, privateKeys } = splitKeys(await getAddressKeys(message.AddressID)); return { publicKeys, privateKeys, type: 'publicPrivate' }; }, [getAddressKeys] ); };
4,035
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useInitializeMessage.tsx
import { useCallback } from 'react'; import { PayloadAction } from '@reduxjs/toolkit'; import { FeatureCode, useApi, useAuthentication, useFeature, useProgressiveRollout } from '@proton/components'; import { WorkerDecryptionResult } from '@proton/crypto'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { isDraft, isPlainText } from '@proton/shared/lib/mail/messages'; import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers'; import uniqueBy from '@proton/utils/uniqueBy'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { LOAD_RETRY_COUNT, LOAD_RETRY_DELAY } from '../../constants'; import { getPureAttachments } from '../../helpers/attachment/attachment'; import { isUnreadMessage } from '../../helpers/elements'; import { isNetworkError } from '../../helpers/errors'; import { decryptMessage } from '../../helpers/message/messageDecrypt'; import { handleDispatchLoadFakeImagesProxy, handleDispatchLoadImagesProxy, handleDispatchLoadRemoteImagesDirect, } from '../../helpers/message/messageImages'; import { loadMessage } from '../../helpers/message/messageRead'; import { Preparation, prepareHtml, preparePlainText } from '../../helpers/transforms/transforms'; import { updateAttachment } from '../../logic/attachments/attachmentsActions'; import { loadEmbedded } from '../../logic/messages/images/messagesImagesActions'; import { LoadEmbeddedParams, LoadEmbeddedResults, LoadRemoteResults, MessageErrors, MessageImages, MessageRemoteImage, MessageState, MessageStateWithDataFull, } from '../../logic/messages/messagesTypes'; import { cleanUTMTrackers, documentInitializeFulfilled, documentInitializePending, load, } from '../../logic/messages/read/messagesReadActions'; import { useAppDispatch } from '../../logic/store'; import { MARK_AS_STATUS, useMarkAs } from '../actions/useMarkAs'; import { useGetAttachment } from '../attachments/useAttachment'; import { useBase64Cache } from '../useBase64Cache'; import { useGetMessageKeys } from './useGetMessageKeys'; import { useKeyVerification } from './useKeyVerification'; import { useGetMessage } from './useMessage'; export const useInitializeMessage = () => { const api = useApi(); const markAs = useMarkAs(); const dispatch = useAppDispatch(); const getMessage = useGetMessage(); const getMessageKeys = useGetMessageKeys(); const getAttachment = useGetAttachment(); const base64Cache = useBase64Cache(); const mailSettings = useMailModel('MailSettings'); const { verifyKeys } = useKeyVerification(); const authentication = useAuthentication(); const { feature } = useFeature(FeatureCode.NumAttachmentsWithoutEmbedded); const isNumAttachmentsWithoutEmbedded = feature?.Value; const canCleanUTMTrackers = useProgressiveRollout(FeatureCode.CleanUTMTrackers); const onUpdateAttachment = (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => { dispatch(updateAttachment({ ID, attachment })); }; return useCallback(async (localID: string, labelID?: string) => { // Message can change during the whole initialization sequence // To have the most up to date version, best is to get back to the cache version each time const getData = () => (getMessage(localID) as MessageStateWithDataFull).data; // Cache entry will be (at least) initialized by the queue system const messageFromState = { ...getMessage(localID) } as MessageState; // If the message is not yet loaded at all, the localID is the message ID if (!messageFromState || !messageFromState.data) { messageFromState.data = { ID: localID } as Message; } dispatch(documentInitializePending(localID)); const errors: MessageErrors = {}; const { loadRetry = 0 } = messageFromState; let initialized: boolean | undefined = true; let decryption; let preparation: Preparation | undefined; let dataChanges = {} as Partial<Message>; let messageImages: MessageImages | undefined; try { // Ensure the message data is loaded const message = await loadMessage(messageFromState, api); dispatch(load.fulfilled(message.data, load.fulfilled.toString(), { ID: localID })); const messageKeys = await getMessageKeys(message.data); decryption = await decryptMessage(getData(), messageKeys.privateKeys, getAttachment, onUpdateAttachment); if (decryption.mimetype) { dataChanges = { ...dataChanges, MIMEType: decryption.mimetype }; } const mimeAttachments = decryption.attachments || []; // Get Pure Mime Attachments to prevent display of embedded images in the attachment list const pureMimeAttachments = getPureAttachments(mimeAttachments, isNumAttachmentsWithoutEmbedded); // The backend is supposed to filter embedded images, // but we sometimes we receive messages with a NumAttachment = 0 which contains pure attachments, // This leads to hide the attachment list, and the user is not able to see the message attachments // We are doing an additional verification to update NumAttachments if needed const pureAttachments = getPureAttachments(getData().Attachments, isNumAttachmentsWithoutEmbedded) || []; // If we calculate a different NumAttachments than the one received, // we need to update the message to display the attachment list const numAttachments = pureAttachments.length !== getData().NumAttachments ? pureAttachments.length : getData().NumAttachments; const allAttachments = [...(getData().Attachments || []), ...mimeAttachments]; dataChanges = { ...dataChanges, Attachments: allAttachments, NumAttachments: numAttachments + pureMimeAttachments.length, }; if (decryption.errors) { Object.assign(errors, decryption.errors); // Get message decryption key to display a notification to the user that its password may have been reset recently await verifyKeys(message.data); } if (isUnreadMessage(getData())) { markAs([getData()], labelID, MARK_AS_STATUS.READ); dataChanges = { ...dataChanges, Unread: 0 }; } const MIMEType = dataChanges.MIMEType || getData().MIMEType; const handleLoadEmbeddedImages = async (attachments: Attachment[]) => { const dispatchResult = dispatch( loadEmbedded({ ID: localID, attachments, api, messageKeys, messageVerification: message.verification, getAttachment, onUpdateAttachment, messageFlags: message.data.Flags, }) ) as any as Promise<PayloadAction<LoadEmbeddedResults, string, { arg: LoadEmbeddedParams }>>; const { payload } = await dispatchResult; return payload; }; const handleLoadRemoteImagesProxy = (imagesToLoad: MessageRemoteImage[]) => { return handleDispatchLoadImagesProxy(localID, imagesToLoad, authentication, dispatch); }; const handleLoadFakeImagesProxy = (imagesToLoad: MessageRemoteImage[], firstLoad?: boolean) => { return handleDispatchLoadFakeImagesProxy(localID, imagesToLoad, api, dispatch, firstLoad); }; const handleLoadRemoteImagesDirect = (imagesToLoad: MessageRemoteImage[]) => { return handleDispatchLoadRemoteImagesDirect(localID, imagesToLoad, dispatch); }; const handleCleanUTMTrackers = (utmTrackers: MessageUTMTracker[]) => { const uniqueTrackers = uniqueBy(utmTrackers, (tracker) => tracker.originalURL); const dispatchResult = dispatch(cleanUTMTrackers({ ID: localID, utmTrackers: uniqueTrackers })); return dispatchResult as any as Promise<LoadRemoteResults[]>; }; preparation = isPlainText({ MIMEType }) ? await preparePlainText( decryption.decryptedBody, isDraft(message.data), mailSettings, canCleanUTMTrackers, handleCleanUTMTrackers ) : await prepareHtml( { ...message, decryption, data: { ...message.data, Attachments: allAttachments }, }, base64Cache, mailSettings, handleLoadEmbeddedImages, handleLoadRemoteImagesProxy, handleLoadFakeImagesProxy, handleLoadRemoteImagesDirect, handleCleanUTMTrackers, canCleanUTMTrackers ); if (!isPlainText({ MIMEType })) { messageImages = { hasRemoteImages: preparation.hasRemoteImages as boolean, showRemoteImages: preparation.showRemoteImages as boolean, hasEmbeddedImages: preparation.hasEmbeddedImages as boolean, showEmbeddedImages: preparation.showEmbeddedImages as boolean, trackersStatus: 'not-loaded', images: [...(preparation.remoteImages || []), ...(preparation.embeddedImages || [])], }; } } catch (error: any) { if (isNetworkError(error)) { errors.network = [error]; if (loadRetry < LOAD_RETRY_COUNT) { initialized = undefined; await wait(LOAD_RETRY_DELAY); } } else { errors.processing = [error]; } console.error('Message initialization error', error); } finally { dispatch( documentInitializeFulfilled({ ID: localID, dataChanges, initialized, preparation, decryption, errors, messageImages, }) ); } }, []); };
4,036
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useKeyVerification.tsx
import * as React from 'react'; import { useAddresses, useNotifications } from '@proton/components'; import type { KeyID } from '@proton/crypto'; import { getItem, setItem } from '@proton/shared/lib/helpers/storage'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import DecryptionErrorNotification from '../../components/notifications/DecryptionErrorNotification'; import { getMessageDecryptionKeyIDFromAddress } from '../../helpers/message/messageDecrypt'; export const useKeyVerification = () => { const { createNotification } = useNotifications(); const [addresses] = useAddresses(); /** * Try to find the key responsible for message encryption and display a notification to the user * If we find the key, and there is a decryption error, it means that the key is disabled, and that the password has been reset * The notification is displayed once per key and per browser, so that for every password change we display a notification, without spamming the user */ const verifyKeys = async (message: Message) => { const address = addresses.find((address) => address.ID === message.AddressID); if (!address) { return; } // Get the key used to encrypt the message const matchingKeyID = await getMessageDecryptionKeyIDFromAddress(address, message); if (matchingKeyID) { const encounteredDecryptionErrorKeys = getItem('DecryptionErrorEncounteredKeys'); const encounteredDecryptionErrorKeysArray = encounteredDecryptionErrorKeys ? JSON.parse(encounteredDecryptionErrorKeys) : []; // If the key is not already in the localStorage, we display a notification if ( !encounteredDecryptionErrorKeysArray.some((encounteredKey: KeyID) => matchingKeyID === encounteredKey) ) { createNotification({ text: <DecryptionErrorNotification keyFound />, type: 'error', expiration: -1, showCloseButton: true, }); const updatedEncounteredKeys = JSON.stringify([...encounteredDecryptionErrorKeysArray, matchingKeyID]); setItem('DecryptionErrorEncounteredKeys', updatedEncounteredKeys); } } else { createNotification({ text: <DecryptionErrorNotification />, type: 'error', expiration: -1, showCloseButton: true, }); } }; return { verifyKeys }; };
4,037
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useLoadImages.ts
import { useCallback } from 'react'; import { useApi, useAuthentication } from '@proton/components'; import { WorkerDecryptionResult } from '@proton/crypto'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { handleDispatchLoadFakeImagesProxy, handleDispatchLoadImagesProxy, handleDispatchLoadRemoteImagesDirect, updateImages, } from '../../helpers/message/messageImages'; import { transformEmbedded } from '../../helpers/transforms/transformEmbedded'; import { transformRemote } from '../../helpers/transforms/transformRemote'; import { updateAttachment } from '../../logic/attachments/attachmentsActions'; import { loadEmbedded } from '../../logic/messages/images/messagesImagesActions'; import { LoadEmbeddedResults, MessageRemoteImage, MessageState, MessageStateWithData, } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; import { useGetAttachment } from '../attachments/useAttachment'; import { useGetMessageKeys } from './useGetMessageKeys'; import { useGetMessage } from './useMessage'; export const useLoadRemoteImages = (localID: string) => { const dispatch = useAppDispatch(); const api = useApi(); const getMessage = useGetMessage(); const mailSettings = useMailModel('MailSettings'); const authentication = useAuthentication(); return useCallback(async () => { const message = getMessage(localID) as MessageState; const handleLoadRemoteImagesProxy = (imagesToLoad: MessageRemoteImage[]) => { return handleDispatchLoadImagesProxy(localID, imagesToLoad, authentication, dispatch); }; const handleLoadFakeImagesProxy = (imagesToLoad: MessageRemoteImage[], firstLoad?: boolean) => { return handleDispatchLoadFakeImagesProxy(localID, imagesToLoad, api, dispatch, firstLoad); }; const handleLoadRemoteImagesDirect = (imagesToLoad: MessageRemoteImage[]) => { return handleDispatchLoadRemoteImagesDirect(localID, imagesToLoad, dispatch); }; transformRemote( { ...message, messageImages: updateImages(message.messageImages, { showRemoteImages: true }, undefined, undefined), }, mailSettings, handleLoadRemoteImagesDirect, handleLoadRemoteImagesProxy, handleLoadFakeImagesProxy ); }, [localID]); }; export const useLoadEmbeddedImages = (localID: string) => { const dispatch = useAppDispatch(); const api = useApi(); const getAttachment = useGetAttachment(); const getMessage = useGetMessage(); const getMessageKeys = useGetMessageKeys(); const mailSettings = useMailModel('MailSettings'); const onUpdateAttachment = (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => { dispatch(updateAttachment({ ID, attachment })); }; return useCallback(async () => { const message = getMessage(localID) as MessageStateWithData; const messageKeys = await getMessageKeys(message.data); const handleLoadEmbeddedImages = (attachments: Attachment[]) => { const dispatchResult = dispatch( loadEmbedded({ ID: localID, attachments, api, messageKeys, messageVerification: message.verification, getAttachment, onUpdateAttachment, messageFlags: message.data.Flags, }) ); return dispatchResult as any as Promise<LoadEmbeddedResults>; }; await transformEmbedded( { ...message, messageImages: updateImages(message.messageImages, { showEmbeddedImages: true }, undefined, undefined), }, mailSettings, handleLoadEmbeddedImages ); }, [localID]); };
4,038
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useLoadMessage.ts
import { useCallback } from 'react'; import { MessageWithOptionalBody } from '../../logic/messages/messagesTypes'; import { load, reload } from '../../logic/messages/read/messagesReadActions'; import { useAppDispatch } from '../../logic/store'; import { useInitializeMessage } from './useInitializeMessage'; export const useLoadMessage = (inputMessage: MessageWithOptionalBody) => { const dispatch = useAppDispatch(); return useCallback(async () => { dispatch(load({ ID: inputMessage.ID })); }, [inputMessage]); }; export const useReloadMessage = (localID: string) => { const dispatch = useAppDispatch(); const initializeMessage = useInitializeMessage(); return useCallback(async () => { dispatch(reload({ ID: localID })); await initializeMessage(localID); }, [localID]); };
4,039
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useMessage.ts
import { useCallback, useEffect, useState } from 'react'; import { useSelector, useStore } from 'react-redux'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { allMessages, localID, messageByID } from '../../logic/messages/messagesSelectors'; import { MessageState } from '../../logic/messages/messagesTypes'; import { initialize } from '../../logic/messages/read/messagesReadActions'; import { RootState, useAppDispatch } from '../../logic/store'; import { useGetConversation } from '../conversation/useConversation'; import { useGetElementsFromIDs } from '../mailbox/useElements'; export const useGetLocalID = () => { const store = useStore<RootState>(); return useCallback((ID: string) => localID(store.getState(), { ID }), []); }; export const useGetMessage = () => { const store = useStore<RootState>(); return useCallback((ID: string) => messageByID(store.getState(), { ID }), []); }; export const useGetAllMessages = () => { const store = useStore<RootState>(); return useCallback(() => { return allMessages(store.getState()); }, []); }; interface ReturnValue { message: MessageState; messageLoaded: boolean; bodyLoaded: boolean; } interface UseMessage { (localID: string, conversationID?: string): ReturnValue; } export const useMessage: UseMessage = (inputLocalID: string, conversationID = '') => { const dispatch = useAppDispatch(); const getLocalID = useGetLocalID(); const getElementsFromIDs = useGetElementsFromIDs(); const getMessage = useGetMessage(); const getConversationFromState = useGetConversation(); const messageState = useSelector((state: RootState) => messageByID(state, { ID: inputLocalID })); const initMessage = (canDispatch = true) => { const localID = getLocalID(inputLocalID); // Selector may be late const messageState = getMessage(inputLocalID); if (messageState) { return messageState; } const [messageFromElementsCache] = getElementsFromIDs([localID]) as Message[]; const conversationState = getConversationFromState(conversationID); const messageFromConversationState = conversationState?.Messages?.find((Message) => Message.ID === localID); const messageFromCache = messageFromElementsCache || messageFromConversationState; const message = messageFromCache ? { localID, data: messageFromCache } : { localID }; if (canDispatch) { dispatch(initialize(message)); } return message; }; // Main subject of the hook // Will be updated based on an effect listening on the event manager // Not allowed to dispatch if not inside a useEffect to avoid warnings const [message, setMessage] = useState<MessageState>(() => initMessage(false)); // Update message state and listen to cache for updates on the current message useEffect(() => { setMessage(initMessage()); }, [inputLocalID]); // The hook can be re-used for a different message useEffect(() => { if (messageState) { setMessage(messageState); } }, [messageState]); const messageLoaded = !!message.data?.Subject; const bodyLoaded = !!message.messageDocument?.initialized; return { message, messageLoaded, bodyLoaded }; };
4,040
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useMessageHotkeys.tsx
import { useRef } from 'react'; import { useLocation } from 'react-router-dom'; import { HotkeyTuple, useEventManager, useFolders, useHotkeys } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { KeyboardKey, MailSettings } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { MESSAGE_ACTIONS } from '../../constants'; import { useOnCompose } from '../../containers/ComposeProvider'; import { isStarred } from '../../helpers/elements'; import { getFolderName } from '../../helpers/labels'; import { isConversationMode } from '../../helpers/mailSettings'; import { MessageState } from '../../logic/messages/messagesTypes'; import { Element } from '../../models/element'; import { MARK_AS_STATUS, useMarkAs } from '../actions/useMarkAs'; import { useMoveToFolder } from '../actions/useMoveToFolder'; import { useStar } from '../actions/useStar'; import { ComposeTypes } from '../composer/useCompose'; const { TRASH, SPAM, ARCHIVE, INBOX } = MAILBOX_LABEL_IDS; enum ARROW_SCROLL_DIRECTIONS { UP, DOWN, } interface MessageHotkeysContext { labelID: string; conversationIndex: number; message: MessageState; messageLoaded: boolean; bodyLoaded: boolean; expanded: boolean; draft: boolean; conversationMode: boolean; mailSettings: MailSettings; messageRef: React.RefObject<HTMLElement>; } interface MessageHotkeysHandlers { hasFocus: boolean; setExpanded: (expanded: boolean) => void; toggleOriginalMessage: () => void; handleLoadRemoteImages: () => void; handleLoadEmbeddedImages: () => void; onBack: () => void; } export const useMessageHotkeys = ( elementRef: React.RefObject<HTMLElement | undefined>, { labelID, message, bodyLoaded, expanded, messageLoaded, draft, conversationMode, mailSettings, messageRef, }: MessageHotkeysContext, { hasFocus, setExpanded, toggleOriginalMessage, handleLoadRemoteImages, handleLoadEmbeddedImages, onBack, }: MessageHotkeysHandlers ) => { const location = useLocation(); const { Shortcuts } = useMailModel('MailSettings'); const [folders] = useFolders(); const { call } = useEventManager(); const labelDropdownToggleRef = useRef<() => void>(noop); const moveDropdownToggleRef = useRef<() => void>(noop); const filterDropdownToggleRef = useRef<() => void>(noop); const markAs = useMarkAs(); const { moveToFolder, moveScheduledModal, moveSnoozedModal, moveAllModal, moveToSpamModal } = useMoveToFolder(); const star = useStar(); const onCompose = useOnCompose(); const isMessageReady = messageLoaded && bodyLoaded; const hotkeysEnabledAndMessageReady = Shortcuts && isMessageReady && expanded && message.messageDocument?.initialized; const isScheduledMessage = message.data?.LabelIDs?.includes(MAILBOX_LABEL_IDS.SCHEDULED); const moveElementTo = async (e: KeyboardEvent, LabelID: MAILBOX_LABEL_IDS) => { if (!message.data) { return; } const folderName = getFolderName(LabelID, folders); await moveToFolder([message.data], LabelID, folderName, labelID, false); }; const shouldStopPropagation = (e: KeyboardEvent, direction: ARROW_SCROLL_DIRECTIONS) => { const dataShortcutTarget = 'mailbox-toolbar'; const { bottom: topLimit } = document.querySelector(`[data-shortcut-target="${dataShortcutTarget}"]`)?.getBoundingClientRect() || {}; const bottomLimit = window.innerHeight; const { top: elementTop, bottom: elementBottom } = elementRef?.current?.getBoundingClientRect() || {}; if (!elementTop || !elementBottom || !topLimit) { return; } const THRESHOLD = 28; const distanceFromTop = elementTop - topLimit; const distanceFromBottom = bottomLimit - elementBottom; if (direction === ARROW_SCROLL_DIRECTIONS.UP && distanceFromTop < THRESHOLD) { e.stopPropagation(); } if (direction === ARROW_SCROLL_DIRECTIONS.DOWN && distanceFromBottom < THRESHOLD) { e.stopPropagation(); } }; const shortcutHandlers: HotkeyTuple[] = [ [ 'Enter', (e) => { if (draft) { e.stopPropagation(); e.preventDefault(); onCompose({ type: ComposeTypes.existingDraft, existingDraft: message, fromUndo: false }); } }, ], [ 'ArrowUp', (e) => { shouldStopPropagation(e, ARROW_SCROLL_DIRECTIONS.UP); }, ], [ 'ArrowDown', (e) => { shouldStopPropagation(e, ARROW_SCROLL_DIRECTIONS.DOWN); }, ], [ 'Escape', (e) => { if (isMessageReady && expanded && conversationMode) { e.stopPropagation(); setExpanded(false); } }, ], [ 'O', () => { if (Shortcuts && isMessageReady && expanded) { toggleOriginalMessage(); } }, ], [ 'R', (e) => { if (hotkeysEnabledAndMessageReady && !isScheduledMessage) { e.preventDefault(); e.stopPropagation(); onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.REPLY, referenceMessage: message, }); } }, ], [ ['Shift', 'R'], (e) => { if (hotkeysEnabledAndMessageReady && !isScheduledMessage) { e.preventDefault(); e.stopPropagation(); onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.REPLY_ALL, referenceMessage: message, }); } }, ], [ ['Shift', 'F'], (e) => { if (hotkeysEnabledAndMessageReady && !isScheduledMessage) { e.preventDefault(); e.stopPropagation(); onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.FORWARD, referenceMessage: message, }); } }, ], [ ['Shift', 'C'], async (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); await handleLoadRemoteImages(); } }, ], [ ['Shift', 'E'], async (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); await handleLoadEmbeddedImages(); } }, ], [ 'U', async (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); setExpanded(false); if (isConversationMode(labelID, mailSettings, location)) { messageRef.current?.focus(); } else { onBack(); } markAs([message.data as Element], labelID, MARK_AS_STATUS.UNREAD); await call(); } }, ], [ KeyboardKey.Star, async (e) => { if (hotkeysEnabledAndMessageReady && message.data) { e.stopPropagation(); await star([message.data as Element], !isStarred(message.data)); } }, ], [ 'I', async (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); await moveElementTo(e, INBOX); } }, ], [ 'A', async (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); await moveElementTo(e, ARCHIVE); } }, ], [ 'S', async (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); await moveElementTo(e, SPAM); } }, ], [ 'T', async (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); await moveElementTo(e, TRASH); } }, ], [ 'L', (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); e.preventDefault(); // FF has an issue when we propagate custom events // adding a timeout there ensure event is done when // other components are rendered setTimeout(() => { labelDropdownToggleRef.current?.(); }, 0); } }, ], [ 'M', (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); e.preventDefault(); // FF has an issue when we propagate custom events // adding a timeout there ensure event is done when // other components are rendered setTimeout(() => { moveDropdownToggleRef.current?.(); }); } }, ], [ 'F', (e) => { if (hotkeysEnabledAndMessageReady) { e.stopPropagation(); filterDropdownToggleRef.current?.(); } }, ], ]; useHotkeys(elementRef, shortcutHandlers, { dependencies: [hasFocus], }); return { labelDropdownToggleRef, moveDropdownToggleRef, filterDropdownToggleRef, moveScheduledModal, moveSnoozedModal, moveAllModal, moveToSpamModal, }; };
4,041
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useMessageTrackers.tsx
import { useMemo } from 'react'; import { FeatureCode, useProgressiveRollout } from '@proton/components'; import { IMAGE_PROXY_FLAGS } from '@proton/shared/lib/mail/mailSettings'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { getImageTrackerText, getImageTrackersFromMessage, getUTMTrackerText, getUTMTrackersFromMessage, } from '../../helpers/message/trackers'; import { MessageState } from '../../logic/messages/messagesTypes'; export interface Tracker { name: string; urls: string[]; } export const useMessageTrackers = (message: MessageState) => { const mailSettings = useMailModel('MailSettings'); const isCleanUTMTrackersAvailable = useProgressiveRollout(FeatureCode.CleanUTMTrackers); const hasProtection = (mailSettings.ImageProxy ? mailSettings.ImageProxy : IMAGE_PROXY_FLAGS.NONE) > IMAGE_PROXY_FLAGS.NONE; const { trackers: imageTrackers, numberOfTrackers: numberOfImageTrackers } = useMemo( () => getImageTrackersFromMessage(message), [message] ); const imageTrackerText = useMemo(() => getImageTrackerText(numberOfImageTrackers), [numberOfImageTrackers]); const imageTrackersLoaded = useMemo(() => { return message.messageImages?.trackersStatus === 'loaded'; }, [message.messageImages?.trackersStatus]); const { trackers: utmTrackers, numberOfTrackers: numberOfUTMTrackers } = getUTMTrackersFromMessage(message); const utmTrackerText = useMemo(() => getUTMTrackerText(numberOfUTMTrackers), [numberOfUTMTrackers]); return { // Image trackers numberOfImageTrackers, needsMoreProtection: !hasProtection, imageTrackerText, imageTrackers, imageTrackersLoaded, hasImageTrackers: numberOfImageTrackers > 0, // UTM trackers canCleanUTMTrackers: isCleanUTMTrackersAvailable, utmTrackers, numberOfUTMTrackers, utmTrackerText, hasUTMTrackers: numberOfUTMTrackers > 0, // Shared hasTrackers: numberOfImageTrackers + numberOfUTMTrackers > 0, }; };
4,042
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useResignContact.ts
import { useCallback } from 'react'; import { useApi, useGetEncryptionPreferences } from '@proton/components'; import { loadMessage } from '../../helpers/message/messageRead'; import { MessageState } from '../../logic/messages/messagesTypes'; import { resign } from '../../logic/messages/read/messagesReadActions'; import { useAppDispatch } from '../../logic/store'; import { useGetMessage } from './useMessage'; export const useResignContact = (localID: string) => { const getEncryptionPreferences = useGetEncryptionPreferences(); const getMessage = useGetMessage(); const dispatch = useAppDispatch(); const api = useApi(); return useCallback(async () => { const messageFromState = getMessage(localID) as MessageState; const message = await loadMessage(messageFromState, api); const address = message.data.Sender?.Address; if (!address || !messageFromState.verification) { return; } const { isContactSignatureVerified } = await getEncryptionPreferences({ email: address }); dispatch(resign({ ID: localID, isContactSignatureVerified })); }, [localID]); };
4,043
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useSaveDraft.ts
import { useCallback } from 'react'; import { c } from 'ttag'; import { useApi, useEventManager, useNotifications } from '@proton/components'; import { deleteMessages } from '@proton/shared/lib/api/messages'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { SAVE_DRAFT_ERROR_CODES } from '../../constants'; import { isDecryptionError, isNetworkError, pickMessageInfosForSentry } from '../../helpers/errors'; import { createMessage, updateMessage } from '../../helpers/message/messageExport'; import { deleteConversation } from '../../logic/conversations/conversationsActions'; import { deleteDraft, draftSaved } from '../../logic/messages/draft/messagesDraftActions'; import { MessageState, MessageStateWithData } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; import { useGetConversation } from '../conversation/useConversation'; import { useGetMessageKeys } from './useGetMessageKeys'; import { useGetMessage } from './useMessage'; const { ALL_DRAFTS } = MAILBOX_LABEL_IDS; export const useCreateDraft = () => { const api = useApi(); const dispatch = useAppDispatch(); const { call } = useEventManager(); const getMessageKeys = useGetMessageKeys(); const { createNotification } = useNotifications(); return useCallback(async (message: MessageStateWithData) => { try { const newMessage = await createMessage(message, api, getMessageKeys); dispatch(draftSaved({ ID: message.localID, message: newMessage, draftFlags: message?.draftFlags })); await call(); } catch (error: any) { if (!error.data) { createNotification({ text: c('Error').t`Error while saving draft. Please try again.`, type: 'error' }); } throw error; } }, []); }; const useUpdateDraft = () => { const api = useApi(); const dispatch = useAppDispatch(); const getMessage = useGetMessage(); const { call } = useEventManager(); const getMessageKeys = useGetMessageKeys(); const { createNotification } = useNotifications(); return useCallback(async (message: MessageStateWithData, onMessageAlreadySent?: () => void) => { try { const messageFromCache = getMessage(message.localID) as MessageState; const previousAddressID = messageFromCache.data?.AddressID || ''; const messageToSave = { ...messageFromCache, ...message, data: { ...messageFromCache.data, ...message.data }, }; const newMessage = await updateMessage(messageToSave, previousAddressID, api, getMessageKeys); dispatch(draftSaved({ ID: message.localID, message: newMessage })); await call(); } catch (error: any) { if (!error.data) { const errorMessage = c('Error').t`Error while saving draft. Please try again.`; createNotification({ text: errorMessage, type: 'error' }); if (!isNetworkError(error) && !isDecryptionError(error)) { captureMessage(errorMessage, { extra: { message: pickMessageInfosForSentry(message), error } }); } throw error; } if (error.data.Code === SAVE_DRAFT_ERROR_CODES.MESSAGE_ALREADY_SENT) { onMessageAlreadySent?.(); throw error; } if (error.data.Code === SAVE_DRAFT_ERROR_CODES.DRAFT_DOES_NOT_EXIST) { dispatch(deleteDraft(message.localID)); } createNotification({ text: error.data.Error, type: 'error', }); throw error; } }, []); }; interface UseUpdateDraftParameters { onMessageAlreadySent?: () => void; } export const useSaveDraft = ({ onMessageAlreadySent }: UseUpdateDraftParameters = {}) => { const getMessage = useGetMessage(); const updateDraft = useUpdateDraft(); const createDraft = useCreateDraft(); return useCallback(async (message: MessageStateWithData) => { const messageFromCache = getMessage(message.localID) as MessageState; if (messageFromCache?.data?.ID) { await updateDraft(message, onMessageAlreadySent); } else { await createDraft(message); } }, []); }; export const useDeleteDraft = () => { const api = useApi(); const mailSettings = useMailModel('MailSettings'); const dispatch = useAppDispatch(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const getConversation = useGetConversation(); const getMessage = useGetMessage(); return useCallback( async (message: MessageState) => { // Need to get again the message from state because if we are saving the draft for the first time, // it might have been saved in the meantime. // So the old reference would not be up to date, and we would not be able to delete the message const messageFromState = getMessage(message.localID); const messageID = messageFromState?.data?.ID; if (!messageID) { return; } const response: any = await api(deleteMessages([messageID], ALL_DRAFTS)); // For the "Please refresh your page, the message has moved." // Backend is not replying with an HTTP error but with an error inside the Response // (it's to deal about potentially different statuses in several deletions) if (response?.Responses?.[0]?.Response?.Error) { const { Response } = response.Responses[0]; createNotification({ text: Response.Error, type: 'error' }); const error = new Error(Response.Error); (error as any).code = Response.Code; throw error; } dispatch(deleteDraft(message.data?.ID || message.localID)); const conversationID = message.data?.ConversationID || ''; const conversationFromConversationState = getConversation(conversationID); if (conversationFromConversationState && conversationFromConversationState.Messages?.length === 1) { dispatch(deleteConversation(conversationID)); } await call(); }, [api, mailSettings] ); };
4,044
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/message/useVerifyMessage.ts
import { useCallback } from 'react'; import { useApi, useGetVerificationPreferences } from '@proton/components'; import { PublicKeyReference, WorkerDecryptionResult, getMatchingSigningKey } from '@proton/crypto'; import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { isNetworkError } from '../../helpers/errors'; import { verifyMessage } from '../../helpers/message/messageDecrypt'; import { extractKeysFromAttachments, extractKeysFromAutocrypt } from '../../helpers/message/messageKeys'; import { updateAttachment } from '../../logic/attachments/attachmentsActions'; import { MessageErrors, MessageStateWithDataFull } from '../../logic/messages/messagesTypes'; import { verificationComplete } from '../../logic/messages/read/messagesReadActions'; import { useAppDispatch } from '../../logic/store'; import { useGetAttachment } from '../attachments/useAttachment'; import { useContactsMap } from '../contact/useContacts'; import { useGetMessageKeys } from './useGetMessageKeys'; import { useGetMessage } from './useMessage'; export const useVerifyMessage = (localID: string) => { const api = useApi(); const getMessage = useGetMessage(); const getAttachment = useGetAttachment(); const dispatch = useAppDispatch(); const getVerificationPreferences = useGetVerificationPreferences(); const getMessageKeys = useGetMessageKeys(); const contactsMap = useContactsMap(); const onUpdateAttachment = (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => { dispatch(updateAttachment({ ID, attachment })); }; return useCallback( async (decryptedRawContent: Uint8Array = new Uint8Array(), signature?: Uint8Array) => { // Message can change during the whole sequence // To have the most up to date version, best is to get back to the cache version each time const getData = () => (getMessage(localID) as MessageStateWithDataFull).data; const errors: MessageErrors = {}; let verificationPreferences; let verification; let signingPublicKey: PublicKeyReference | undefined; let attachedPublicKeys: PublicKeyReference[] | undefined; try { const senderAddress = getData().Sender.Address; verificationPreferences = await getVerificationPreferences({ email: senderAddress, lifetime: 0, contactEmailsMap: contactsMap, }); const messageKeys = await getMessageKeys(getData()); verification = await verifyMessage( decryptedRawContent, signature, getData(), verificationPreferences.verifyingKeys ); const messageData = getData(); attachedPublicKeys = await extractKeysFromAttachments( messageData.Attachments, messageKeys, getAttachment, onUpdateAttachment, api, messageData.Flags ); const autocryptKeys = await extractKeysFromAutocrypt(getData().ParsedHeaders, senderAddress); const allSenderPublicKeys = [ ...verificationPreferences.apiKeys, ...verificationPreferences.pinnedKeys, ...attachedPublicKeys, ...autocryptKeys, ]; const signed = verification.verified !== VERIFICATION_STATUS.NOT_SIGNED; signingPublicKey = signed && verification.signature ? await getMatchingSigningKey({ binarySignature: verification.signature, keys: allSenderPublicKeys, }) : undefined; } catch (error: any) { if (isNetworkError(error)) { errors.network = [error]; } else { errors.signature = [error]; } } finally { dispatch( verificationComplete({ ID: localID, verificationPreferences, verification, signingPublicKey, attachedPublicKeys, errors, }) ); } }, [localID, contactsMap] ); };
4,045
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/optimistic/useOptimisticApplyLabels.ts
import { useCache, useFolders, useHandler } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { RequireSome } from '@proton/shared/lib/interfaces/utils'; import { ConversationCountsModel, MessageCountsModel } from '@proton/shared/lib/models'; import { STATUS } from '@proton/shared/lib/models/cache'; import { updateCounters } from '../../helpers/counter'; import { getCurrentFolderIDs, hasLabel, isMessage as testIsMessage } from '../../helpers/elements'; import { LabelChanges, UnreadStatus, applyLabelChangesOnConversation, applyLabelChangesOnMessage, applyLabelChangesOnOneMessageOfAConversation, } from '../../helpers/labels'; import { applyLabelsOnConversation, applyLabelsOnConversationMessages, } from '../../logic/conversations/conversationsActions'; import { optimisticApplyLabels as optimisticApplyLabelsElementsAction } from '../../logic/elements/elementsActions'; import { optimisticApplyLabels as optimisticApplyLabelsMessageAction } from '../../logic/messages/optimistic/messagesOptimisticActions'; import { useAppDispatch } from '../../logic/store'; import { Conversation } from '../../models/conversation'; import { Element } from '../../models/element'; import { CacheEntry } from '../../models/tools'; import { useGetConversation } from '../conversation/useConversation'; import { useGetElementByID } from '../mailbox/useElements'; const { SENT, DRAFTS } = MAILBOX_LABEL_IDS; const computeRollbackLabelChanges = (element: Element, changes: LabelChanges) => { const rollbackChange = {} as LabelChanges; Object.keys(changes).forEach((labelID) => { if (changes[labelID] && !hasLabel(element, labelID)) { rollbackChange[labelID] = false; } if (!changes[labelID] && hasLabel(element, labelID)) { rollbackChange[labelID] = true; } }); return rollbackChange; }; export const useOptimisticApplyLabels = () => { const dispatch = useAppDispatch(); const getElementByID = useGetElementByID(); const [folders = []] = useFolders(); const globalCache = useCache(); const getConversation = useGetConversation(); /** * Apply optimistically changes in the cache * @param elements * @param inputChanges * @param isMove Is the label change is a move to folder * @param unreadStatuses unread statuses of all elements to be able to use them when using optimistic rollback. Is [] by default when moving, but can be filled when rollback * @param currentLabelID The current label ID on the UI, only used for moves, moving from sent or draft folders have specific meaning * @returns a rollback function to undo all changes */ const optimisticApplyLabels = useHandler( ( elements: Element[], inputChanges: LabelChanges, isMove = false, unreadStatuses?: UnreadStatus[], currentLabelID?: string ) => { const rollbackChanges = [] as { element: Element; changes: LabelChanges }[]; const updatedElements = [] as Element[]; const elementsUnreadStatuses = [] as UnreadStatus[]; const isMessage = testIsMessage(elements[0]); let { value: messageCounters } = globalCache.get(MessageCountsModel.key) as CacheEntry<LabelCount[]>; let { value: conversationCounters } = globalCache.get(ConversationCountsModel.key) as CacheEntry< LabelCount[] >; // Updates in message cache elements.forEach((element) => { const changes = { ...inputChanges }; if (isMove) { const currentFolderIDs = ([SENT, DRAFTS] as string[]).includes(currentLabelID || '') ? [currentLabelID as string] : getCurrentFolderIDs(element, folders); const isMoveToCurrentFolder = currentFolderIDs.every((folderID) => changes[folderID]); if (isMoveToCurrentFolder) { // It's a move to the folder where the elements is already, so nothing to do or undo return; } /* * When moving elements to trash, we store the unread status of all elements so that * we can use the previous unread status for the optimistic rollback */ if (Object.keys(inputChanges).includes(MAILBOX_LABEL_IDS.TRASH)) { if (isMessage) { const message = element as Message; elementsUnreadStatuses.push({ id: message.ID, unread: message.Unread }); } else { const conversation = element as Conversation; elementsUnreadStatuses.push({ id: conversation.ID ? conversation.ID : '', unread: conversation.NumUnread ? conversation.NumUnread : 0, }); } } currentFolderIDs.forEach((folderID) => { changes[folderID] = false; }); } rollbackChanges.push({ element, changes: computeRollbackLabelChanges(element, changes) }); if (isMessage) { const message = element as Message; dispatch(optimisticApplyLabelsMessageAction({ ID: element.ID || '', changes, unreadStatuses })); // Update in conversation cache const conversationResult = getConversation(message.ConversationID); if (conversationResult && conversationResult.Conversation) { const conversation = conversationResult.Conversation; const { updatedConversation, conversationChanges } = applyLabelChangesOnOneMessageOfAConversation(conversation, changes); dispatch( applyLabelsOnConversationMessages({ ID: message.ConversationID, messageID: message.ID, changes, unreadStatuses, updatedConversation, conversationResult, // TODO: Check if needed }) ); // Update conversation count when the conversation is loaded conversationCounters = updateCounters(conversation, conversationCounters, conversationChanges); } // Updates in elements cache if message mode const messageElement = getElementByID(message.ID); if (messageElement && messageElement.ID) { updatedElements.push( applyLabelChangesOnMessage(messageElement as Message, changes, unreadStatuses) ); } // Update in elements cache if conversation mode const conversationElement = getElementByID(message.ConversationID); if (conversationElement && conversationElement.ID) { const { updatedConversation } = applyLabelChangesOnOneMessageOfAConversation( conversationElement, changes ); updatedElements.push(updatedConversation); } // Update message and conversation counters messageCounters = updateCounters(message, messageCounters, changes); } else { // isConversation const conversation = element as RequireSome<Conversation, 'ID'>; // Update in conversation cache const conversationFromState = getConversation(conversation.ID); dispatch(applyLabelsOnConversation({ ID: conversation.ID, changes, unreadStatuses })); // Update in elements cache if conversation mode const conversationElement = getElementByID(conversation.ID); if (conversationElement && conversationElement.ID) { updatedElements.push( applyLabelChangesOnConversation(conversationElement, changes, unreadStatuses) ); } // Update messages from the conversation (if loaded) conversationFromState?.Messages?.forEach((message) => { dispatch(optimisticApplyLabelsMessageAction({ ID: message.ID, changes, unreadStatuses })); }); // Update conversation counters conversationCounters = updateCounters(conversation, conversationCounters, changes); } }); if (updatedElements.length) { dispatch(optimisticApplyLabelsElementsAction({ elements: updatedElements, isMove })); } globalCache.set(MessageCountsModel.key, { value: messageCounters, status: STATUS.RESOLVED }); globalCache.set(ConversationCountsModel.key, { value: conversationCounters, status: STATUS.RESOLVED }); return () => { rollbackChanges.forEach((rollbackChange) => { optimisticApplyLabels( [rollbackChange.element], rollbackChange.changes, false, elementsUnreadStatuses ); }); }; } ); return optimisticApplyLabels; };
4,046
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/optimistic/useOptimisticDelete.ts
import { useCache, useHandler } from '@proton/components'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import { ConversationCountsModel, MessageCountsModel } from '@proton/shared/lib/models'; import isTruthy from '@proton/utils/isTruthy'; import { replaceCounter } from '../../helpers/counter'; import { isConversation, isUnread } from '../../helpers/elements'; import { optimisticDelete as optimisticDeleteConversationAction, optimisticDeleteConversationMessages, optimisticRestore as optimisticRestoreConversationsAction, } from '../../logic/conversations/conversationsActions'; import { ConversationState } from '../../logic/conversations/conversationsTypes'; import { optimisticDelete as optimisticDeleteElementAction, optimisticRestoreDelete as optimisticRestoreDeleteElementAction, } from '../../logic/elements/elementsActions'; import { MessageState } from '../../logic/messages/messagesTypes'; import { optimisticDelete as optimisticDeleteMessageAction, optimisticRestore as optimisticRestoreMessageAction, } from '../../logic/messages/optimistic/messagesOptimisticActions'; import { useAppDispatch } from '../../logic/store'; import { Element } from '../../models/element'; import { CacheEntry } from '../../models/tools'; import { useGetAllConversations } from '../conversation/useConversation'; import { useGetElementByID } from '../mailbox/useElements'; import { useGetMessage } from '../message/useMessage'; const useOptimisticDelete = () => { const dispatch = useAppDispatch(); const getElementByID = useGetElementByID(); const globalCache = useCache(); const getAllConversations = useGetAllConversations(); const getMessage = useGetMessage(); return useHandler((elements: Element[], labelID: string) => { const elementIDs = elements.map(({ ID }) => ID || ''); const conversationMode = isConversation(elements[0]); const total = elementIDs.length; const totalUnread = elements.filter((element) => isUnread(element, labelID)).length; const rollbackMessages = [] as MessageState[]; const rollbackConversations = [] as ConversationState[]; const rollbackCounters = {} as { [key: string]: LabelCount }; // Message cache elementIDs.forEach((elementID) => { const message = getMessage(elementID); if (message) { rollbackMessages.push(message); } }); dispatch(optimisticDeleteMessageAction(elementIDs)); // Conversation cache const allConversations = getAllConversations(); allConversations.forEach((conversation) => { if (conversation?.Conversation.ID && elementIDs.includes(conversation?.Conversation.ID)) { dispatch(optimisticDeleteConversationAction(conversation?.Conversation.ID)); rollbackConversations.push(conversation); } else if (conversation?.Messages) { const messages = conversation.Messages?.filter((message) => !elementIDs.includes(message.ID)); if (conversation && messages?.length !== conversation?.Messages?.length) { dispatch(optimisticDeleteConversationMessages({ ID: conversation.Conversation.ID, messages })); rollbackConversations.push(conversation); } } }); // Elements cache const rollbackElements = elementIDs.map((elementID) => getElementByID(elementID)).filter(isTruthy); dispatch(optimisticDeleteElementAction({ elementIDs })); if (conversationMode) { // Conversation counters const conversationCounters = globalCache.get(ConversationCountsModel.key) as CacheEntry<LabelCount[]>; const currentConversationCounter = conversationCounters.value.find( (counter: any) => counter.LabelID === labelID ) as LabelCount; rollbackCounters[ConversationCountsModel.key] = currentConversationCounter; globalCache.set(ConversationCountsModel.key, { ...conversationCounters, value: replaceCounter(conversationCounters.value, { LabelID: labelID, Total: (currentConversationCounter.Total || 0) - total, Unread: (currentConversationCounter.Unread || 0) - totalUnread, }), }); } else { // Message counters const messageCounters = globalCache.get(MessageCountsModel.key) as CacheEntry<LabelCount[]>; const currentMessageCounter = messageCounters.value.find( (counter: any) => counter.LabelID === labelID ) as LabelCount; rollbackCounters[MessageCountsModel.key] = currentMessageCounter; globalCache.set(MessageCountsModel.key, { ...messageCounters, value: replaceCounter(messageCounters.value, { LabelID: labelID, Total: (currentMessageCounter.Total || 0) - total, Unread: (currentMessageCounter.Unread || 0) - totalUnread, }), }); } return () => { dispatch(optimisticRestoreMessageAction(rollbackMessages)); dispatch(optimisticRestoreConversationsAction(rollbackConversations)); dispatch(optimisticRestoreDeleteElementAction({ elements: rollbackElements })); Object.entries(rollbackCounters).forEach(([key, value]) => { const entry = globalCache.get(key) as CacheEntry<LabelCount[]>; globalCache.set(key, { ...entry, value: replaceCounter(entry.value, value), }); }); }; }); }; export default useOptimisticDelete;
4,047
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/optimistic/useOptimisticEmptyLabel.ts
import { useStore } from 'react-redux'; import { useCache, useHandler } from '@proton/components'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import { ConversationCountsModel, MessageCountsModel } from '@proton/shared/lib/models'; import { replaceCounter } from '../../helpers/counter'; import { hasLabel } from '../../helpers/elements'; import { optimisticDelete as optimisticDeleteConversationAction, optimisticDeleteConversationMessages as optimisticDeleteConversationMessagesAction, optimisticRestore as optimisticRestoreConversationsAction, } from '../../logic/conversations/conversationsActions'; import { ConversationState } from '../../logic/conversations/conversationsTypes'; import { optimisticEmptyLabel as optimisticEmptyLabelElements, optimisticRestoreEmptyLabel as optimisticRestoreEmptyLabelElements, } from '../../logic/elements/elementsActions'; import { MessageState } from '../../logic/messages/messagesTypes'; import { optimisticEmptyLabel as optimisticEmptyLabelMessage, optimisticRestore as optimisticRestoreMessage, } from '../../logic/messages/optimistic/messagesOptimisticActions'; import { RootState, useAppDispatch } from '../../logic/store'; import { CacheEntry } from '../../models/tools'; import { useGetAllConversations } from '../conversation/useConversation'; export const useOptimisticEmptyLabel = () => { const store = useStore<RootState>(); const dispatch = useAppDispatch(); const globalCache = useCache(); const getAllConversations = useGetAllConversations(); return useHandler((labelID: string) => { const rollbackMessages = [] as MessageState[]; const rollbackConversations = [] as ConversationState[]; const rollbackCounters = {} as { [key: string]: LabelCount }; // Message cache dispatch(optimisticEmptyLabelMessage(labelID)); // Conversation cache const allConversations = getAllConversations(); allConversations.forEach((conversation) => { if (conversation?.Conversation.ID && hasLabel(conversation.Conversation, labelID)) { dispatch(optimisticDeleteConversationAction(conversation?.Conversation.ID)); rollbackConversations.push(conversation); } else if (conversation?.Messages) { const messages = conversation.Messages?.filter((message) => !hasLabel(message, labelID)); if (conversation && messages?.length !== conversation?.Messages?.length) { dispatch( optimisticDeleteConversationMessagesAction({ ID: conversation.Conversation.ID, messages }) ); rollbackConversations.push(conversation); } } }); // Elements cache const rollbackElements = Object.values(store.getState().elements.elements); dispatch(optimisticEmptyLabelElements()); // Message counters const messageCounters = globalCache.get(MessageCountsModel.key) as CacheEntry<LabelCount[]>; rollbackCounters[MessageCountsModel.key] = messageCounters.value.find( (counter: any) => counter.LabelID === labelID ) as LabelCount; globalCache.set(MessageCountsModel.key, { ...messageCounters, value: replaceCounter(messageCounters.value, { LabelID: labelID, Total: 0, Unread: 0 }), }); // Conversation counters const conversationCounters = globalCache.get(ConversationCountsModel.key) as CacheEntry<LabelCount[]>; rollbackCounters[ConversationCountsModel.key] = conversationCounters.value.find( (counter: any) => counter.LabelID === labelID ) as LabelCount; globalCache.set(ConversationCountsModel.key, { ...conversationCounters, value: replaceCounter(conversationCounters.value, { LabelID: labelID, Total: 0, Unread: 0 }), }); return () => { dispatch(optimisticRestoreMessage(rollbackMessages)); dispatch(optimisticRestoreConversationsAction(rollbackConversations)); dispatch(optimisticRestoreEmptyLabelElements({ elements: rollbackElements })); Object.entries(rollbackCounters).forEach(([key, value]) => { const entry = globalCache.get(key) as CacheEntry<LabelCount[]>; globalCache.set(key, { ...entry, value: replaceCounter(entry.value, value), }); }); }; }); };
4,048
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/optimistic/useOptimisticMarkAs.ts
import { useHistory } from 'react-router-dom'; import { useCache, useHandler } from '@proton/components'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { RequireSome } from '@proton/shared/lib/interfaces/utils'; import { ConversationCountsModel, MessageCountsModel } from '@proton/shared/lib/models'; import { STATUS } from '@proton/shared/lib/models/cache'; import { updateCountersForMarkAs } from '../../helpers/counter'; import { isUnread, isMessage as testIsMessage } from '../../helpers/elements'; import { isConversationMode } from '../../helpers/mailSettings'; import { applyMarkAsChangesOnMessage } from '../../helpers/message/messages'; import useMailModel from '../../hooks/useMailModel'; import { optimisticMarkAsConversation, optimisticMarkAsConversationMessages, } from '../../logic/conversations/conversationsActions'; import { optimisticMarkAs as optimisticMarkAsElementAction } from '../../logic/elements/elementsActions'; import { optimisticMarkAs as optimisticMarkAsMessageAction } from '../../logic/messages/optimistic/messagesOptimisticActions'; import { isElementReminded } from '../../logic/snoozehelpers'; import { useAppDispatch } from '../../logic/store'; import { Conversation } from '../../models/conversation'; import { Element } from '../../models/element'; import { CacheEntry } from '../../models/tools'; import { MARK_AS_STATUS } from '../actions/useMarkAs'; import { useGetConversation } from '../conversation/useConversation'; import { useGetElementByID } from '../mailbox/useElements'; export type MarkAsChanges = { status: MARK_AS_STATUS; displaySnoozedReminder: boolean }; const computeRollbackMarkAsChanges = (element: Element, labelID: string, changes: MarkAsChanges) => { const isElementUnread = isUnread(element, labelID); const displaySnoozedReminder = isElementReminded(element); const { status } = changes; // If same status nothing changes if ((isElementUnread && status === MARK_AS_STATUS.UNREAD) || (!isElementUnread && status === MARK_AS_STATUS.READ)) { return changes; } return { status: isElementUnread ? MARK_AS_STATUS.UNREAD : MARK_AS_STATUS.READ, displaySnoozedReminder, }; }; export const applyMarkAsChangesOnConversation = ( conversation: Conversation, labelID: string, { status, displaySnoozedReminder }: MarkAsChanges ) => { const { NumUnread = 0, Labels = [] } = conversation; const { ContextNumUnread = 0 } = Labels.find(({ ID }) => ID === labelID) || {}; const updatedNumUnread = status === MARK_AS_STATUS.UNREAD ? NumUnread + 1 : Math.max(NumUnread - ContextNumUnread, 0); const updatedContextNumUnread = status === MARK_AS_STATUS.UNREAD ? ContextNumUnread + 1 : 0; const updatedLabels = Labels.map((label) => label.ID === labelID ? { ...label, ContextNumUnread: updatedContextNumUnread, } : label ); return { ...conversation, DisplaySnoozedReminder: displaySnoozedReminder, NumUnread: updatedNumUnread, ContextNumUnread: updatedContextNumUnread, Labels: updatedLabels, }; }; // Here only one message is marked as read/unread const applyMarkAsChangesOnConversationWithMessages = ( conversation: Conversation, labelID: string, { status, displaySnoozedReminder }: MarkAsChanges ) => { const { NumUnread = 0, Labels = [] } = conversation; const { ContextNumUnread = 0 } = Labels.find(({ ID }) => ID === labelID) || {}; const updatedNumUnread = status === MARK_AS_STATUS.UNREAD ? NumUnread + 1 : Math.max(NumUnread - 1, 0); const updatedContextNumUnread = status === MARK_AS_STATUS.UNREAD ? ContextNumUnread + 1 : Math.max(ContextNumUnread - 1, 0); const updatedLabels = Labels.map((label) => label.ID === labelID ? { ...label, ContextNumUnread: updatedContextNumUnread, } : label ); return { ...conversation, DisplaySnoozedReminder: displaySnoozedReminder, NumUnread: updatedNumUnread, ContextNumUnread: updatedContextNumUnread, Labels: updatedLabels, }; }; export const useOptimisticMarkAs = () => { const dispatch = useAppDispatch(); const getElementByID = useGetElementByID(); const globalCache = useCache(); const mailSettings = useMailModel('MailSettings'); const history = useHistory(); const getConversation = useGetConversation(); const optimisticMarkAs = useHandler((elements: Element[], labelID: string, changes: MarkAsChanges) => { const rollbackChanges = [] as { element: Element; changes: MarkAsChanges }[]; const updatedElements = [] as Element[]; let { value: messageCounters } = globalCache.get(MessageCountsModel.key) as CacheEntry<LabelCount[]>; let { value: conversationCounters } = globalCache.get(ConversationCountsModel.key) as CacheEntry<LabelCount[]>; // Counters can be undefined if they are not yet fetched if (!messageCounters || !conversationCounters) { return; } elements.forEach((element) => { rollbackChanges.push({ element, changes: computeRollbackMarkAsChanges(element, labelID, changes) }); if (testIsMessage(element)) { const message = element as Message; dispatch(optimisticMarkAsMessageAction({ ID: message.ID, changes })); // Update in conversation cache const conversationState = getConversation(message.ConversationID); if (conversationState && conversationState.Conversation) { const conversation = conversationState.Conversation; const updatedConversation = applyMarkAsChangesOnConversationWithMessages( conversation, labelID, changes ); dispatch( optimisticMarkAsConversationMessages({ ID: message.ConversationID, messageID: message.ID, updatedConversation, changes, }) ); // Update conversation count when the conversation is loaded conversationCounters = updateCountersForMarkAs( conversation, updatedConversation, conversationCounters ); } // Updates in elements cache if message mode const messageElement = getElementByID(message.ID); if (messageElement && messageElement.ID) { const updatedMessage = applyMarkAsChangesOnMessage(messageElement as Message, changes); updatedElements.push(updatedMessage); // Update counters messageCounters = updateCountersForMarkAs(message, updatedMessage, messageCounters); } // Update in elements cache if conversation mode const conversationElement = getElementByID(message.ConversationID); if (conversationElement && conversationElement.ID) { updatedElements.push( applyMarkAsChangesOnConversationWithMessages(conversationElement, labelID, changes) ); } } else { // isConversation const conversation = element as RequireSome<Conversation, 'ID'>; // Update in conversation cache dispatch(optimisticMarkAsConversation({ ID: conversation.ID, labelID, changes })); // Update in elements cache if conversation mode const conversationElement = getElementByID(conversation.ID); if (conversationElement && conversationElement.ID) { const updatedConversation = applyMarkAsChangesOnConversation(conversationElement, labelID, changes); updatedElements.push(updatedConversation); // Update counters conversationCounters = updateCountersForMarkAs( conversationElement, updatedConversation, conversationCounters ); } // Update messages from the conversation (if loaded) if (changes.status === MARK_AS_STATUS.READ) { const messages = getConversation(conversation.ID)?.Messages; messages?.forEach((message) => { if (!message.LabelIDs.find((id) => id === labelID)) { return; } dispatch(optimisticMarkAsMessageAction({ ID: message.ID, changes })); }); } } }); if (updatedElements.length) { // When changing the read / unread status of an element // We want them to stay on the current filter even if it doesn't match the filter anymore // So we manually update the elements cache to mark these ids to bypass the filter logic // This will last as long as the cache is not reset (cf useElements shouldResetCache) const conversationMode = isConversationMode(labelID, mailSettings, history.location); dispatch( optimisticMarkAsElementAction({ elements: updatedElements, bypass: true, conversationMode, markAsStatus: changes.status, }) ); } globalCache.set(MessageCountsModel.key, { value: messageCounters, status: STATUS.RESOLVED }); globalCache.set(ConversationCountsModel.key, { value: conversationCounters, status: STATUS.RESOLVED }); return () => { rollbackChanges.forEach(({ element, changes }) => optimisticMarkAs([element], labelID, changes)); }; }); return optimisticMarkAs; };
4,049
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/simpleLogin/useSimpleLoginExtension.tsx
import { ReactNode, createContext, useContext, useEffect, useState } from 'react'; import { useApi } from '@proton/components/hooks'; import { getSLAccountLinked } from '@proton/shared/lib/api/simpleLogin'; import { SIMPLE_LOGIN_TAGS } from '@proton/shared/lib/constants'; import { isEdge, isFirefox, isSafari } from '@proton/shared/lib/helpers/browser'; const { EXTENSION_INSTALLED_QUERY, EXTENSION_INSTALLED_RESPONSE } = SIMPLE_LOGIN_TAGS; export const SimpleLoginExtensionContext = createContext<{ canUseExtension?: boolean; hasSLExtension?: boolean; hasAccountLinked?: boolean; hasSimpleLogin?: boolean; isFetchingAccountLinked?: boolean; }>({}); export const useSimpleLoginExtension = () => { const { canUseExtension, hasSLExtension, hasAccountLinked, hasSimpleLogin, isFetchingAccountLinked } = useContext( SimpleLoginExtensionContext ) || { canUseExtension: undefined, hasSLExtension: undefined, hasAccountLinked: undefined, hasSimpleLogin: undefined, isFetchingAccountLinked: undefined, }; return { canUseExtension, hasSLExtension, hasAccountLinked, hasSimpleLogin, isFetchingAccountLinked }; }; export const SimpleLoginExtensionProvider = ({ children }: { children: ReactNode }) => { const api = useApi(); const [hasSLExtension, setHasSLExtension] = useState(false); const [hasAccountLinked, setHasAccountLinked] = useState(false); const [isFetchingAccountLinked, setIsFetchingAccountLinked] = useState(false); const [maxRetriesReached, setMaxRetriesReached] = useState(false); const [numberOfTries, setNumberOfTries] = useState(1); const maxNumberOfTries = 5; const canUseExtension = isEdge() || 'chrome' in window || isFirefox(); // We don't need to present SL feature to users // Having the extension on Firefox or Chromium browsers // Having a Proton account linked to SL on Safari const hasSimpleLogin = canUseExtension ? hasSLExtension : hasAccountLinked; const handleSLExtensionEvents = (event: any) => { if (event.source !== window) { return; } if (event?.data?.tag === EXTENSION_INSTALLED_RESPONSE) { setHasSLExtension(true); } }; useEffect(() => { // Event listener responsible for catching the extension response window.addEventListener('message', handleSLExtensionEvents); return () => { window.removeEventListener('message', handleSLExtensionEvents); }; }, []); // Send 5 events with 200ms interval to check whether the extension is installed // the extension might miss it, so we send it multiple times to be sure useEffect(() => { if (!canUseExtension || hasSLExtension || maxRetriesReached) { return; } const sendEvent = setInterval(() => { if (numberOfTries < maxNumberOfTries) { // post a message to the extension to know whether it's installed window.postMessage({ tag: EXTENSION_INSTALLED_QUERY }, '/'); setNumberOfTries(numberOfTries + 1); } else { setTimeout(() => { setMaxRetriesReached(true); }, 200); clearInterval(sendEvent); } }, 200); return () => clearInterval(sendEvent); }, [numberOfTries, hasSLExtension, maxRetriesReached]); // If using Safari, the user cannot have an extension. However, he might have activated its SL account useEffect(() => { const handleGetSLAccountLinked = async () => { setIsFetchingAccountLinked(true); const { User } = await api(getSLAccountLinked()); setIsFetchingAccountLinked(false); if (!!User) { setHasAccountLinked(true); } }; if (isSafari()) { void handleGetSLAccountLinked(); } }, []); return ( <SimpleLoginExtensionContext.Provider value={{ canUseExtension, hasSLExtension, hasAccountLinked, hasSimpleLogin, isFetchingAccountLinked }} > {children} </SimpleLoginExtensionContext.Provider> ); };
4,050
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/simpleLogin/useSimpleLoginTelemetry.ts
import { useApi, useSubscription } from '@proton/components/hooks'; import { TelemetryMeasurementGroups, TelemetrySimpleLoginEvents } from '@proton/shared/lib/api/telemetry'; import { APPS, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { isSafari } from '@proton/shared/lib/helpers/browser'; import { sendTelemetryReport } from '@proton/shared/lib/helpers/metrics'; import { getPrimaryPlan } from '@proton/shared/lib/helpers/subscription'; import { SimpleMap } from '@proton/shared/lib/interfaces'; import { FREE_PLAN } from '@proton/shared/lib/subscription/freePlans'; export const useSimpleLoginTelemetry = () => { const api = useApi(); const [subscription] = useSubscription(); const primaryPlan = getPrimaryPlan(subscription, APPS.PROTONMAIL); const planTitle = primaryPlan?.Title || PLAN_NAMES[FREE_PLAN.Name as PLANS]; // However, we need to bin the number of message we send to Telemetry // '0' => User has 0 messages in spam // '1' => User has 1 message in spam // '10' => User has 2-10 messages in spam // '10+' => User has more than 10 messages in spam const getBinnedMessagesInSpam = (totalMessages: number) => { if (totalMessages === 0) { return '0'; } else if (totalMessages === 1) { return '1'; } else if (totalMessages < 11) { return '10'; } else { return '10+'; } }; const handleSendTelemetryData = ( event: TelemetrySimpleLoginEvents, values?: SimpleMap<number>, needsModalType = false, messagesInSpam?: number ) => { const dimensions = { Plan: planTitle, } as SimpleMap<string>; if (needsModalType) { dimensions.ModalType = isSafari() ? 'website' : 'extension'; } if (messagesInSpam !== undefined) { dimensions.MessagesInSpam = getBinnedMessagesInSpam(messagesInSpam); } void sendTelemetryReport({ api, measurementGroup: TelemetryMeasurementGroups.mailSimpleLogin, event, values, dimensions, }); }; return { handleSendTelemetryData }; };
4,051
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/actions.ts
import { createAction } from '@reduxjs/toolkit'; export const globalReset = createAction<void>('reset');
4,052
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/snoozehelpers.test.ts
import { format, getUnixTime, nextMonday, nextSaturday, set } from 'date-fns'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { Element } from '../models/element'; import { getSnoozeDate, getSnoozeNotificationText, getSnoozeTimeFromElement, getSnoozeUnixTime } from './snoozehelpers'; describe('snooze helpers - getSnoozeUnixTime', () => { it('Should return tomorrow 9 when snooze duration is tomorrow', () => { const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(9, 0, 0, 0); expect(getSnoozeUnixTime('tomorrow')).toEqual(tomorrow.getTime() / 1000); }); it('Should return two days from now 9 when snooze duration is later', () => { const twoDaysFromNow = new Date(); twoDaysFromNow.setDate(twoDaysFromNow.getDate() + 2); twoDaysFromNow.setHours(9, 0, 0, 0); expect(getSnoozeUnixTime('later')).toEqual(twoDaysFromNow.getTime() / 1000); }); it('Should return next Saturday 9 when snooze duration is weekend', () => { const nextSat = nextSaturday(new Date()); nextSat.setHours(9, 0, 0, 0); expect(getSnoozeUnixTime('weekend')).toEqual(nextSat.getTime() / 1000); }); it('Should return next Monday 9 when snooze duration is nextweek', () => { const nextMon = nextMonday(new Date()); nextMon.setHours(9, 0, 0, 0); expect(getSnoozeUnixTime('nextweek')).toEqual(nextMon.getTime() / 1000); }); it('Should throw an error when no snooze time for custom duration', () => { expect(() => getSnoozeUnixTime('custom')).toThrowError('Snooze time is required for custom snooze'); }); it('Should return unix time of custom time', () => { const futureDate = set(new Date(), { year: 2030, month: 10, date: 10, minutes: 0, seconds: 0, milliseconds: 0, hours: 9, }); expect(getSnoozeUnixTime('custom', futureDate)).toEqual(futureDate.getTime() / 1000); }); }); describe('snooze helpers - getSnoozeNotificationText', () => { it('Should return snooze notification text when snooze is true', () => { expect(getSnoozeNotificationText(true, 1)).toEqual('1 conversation snoozed'); expect(getSnoozeNotificationText(true, 2)).toEqual('2 conversations snoozed'); }); it('Should return unsnooze notification text when snooze is false', () => { expect(getSnoozeNotificationText(false, 1)).toEqual('1 conversation unsnoozed'); expect(getSnoozeNotificationText(false, 2)).toEqual('2 conversations unsnoozed'); }); }); describe('snooze helpers - getSnoozeTimeFromElement', () => { it('Should return undefined when no element', () => { expect(getSnoozeTimeFromElement()).toEqual(undefined); }); it('Should return undefined when element is not a conversation', () => { expect(getSnoozeTimeFromElement({} as Element)).toEqual(undefined); }); it('Should return snooze time when element is a conversation and has a snooze label', () => { const snoozeTime = new Date().getTime(); expect( getSnoozeTimeFromElement({ Labels: [{ ID: MAILBOX_LABEL_IDS.SNOOZED, ContextSnoozeTime: snoozeTime }], } as Element) ).toEqual(snoozeTime); }); it('Should return snooze time when element is a conversation and has a inbox label', () => { const snoozeTime = new Date().getTime(); expect( getSnoozeTimeFromElement({ Labels: [{ ID: MAILBOX_LABEL_IDS.INBOX, ContextSnoozeTime: snoozeTime }], } as Element) ).toEqual(snoozeTime); }); it('Should return undefined when element is a conversation and has no snooze label', () => { expect( getSnoozeTimeFromElement({ Labels: [{ ID: MAILBOX_LABEL_IDS.DRAFTS }], } as Element) ).toEqual(undefined); }); it('Should return snooze time when element is a message', () => { const snoozeTime = new Date().getTime(); expect( getSnoozeTimeFromElement({ ConversationID: 'conversationID', SnoozeTime: snoozeTime, } as Element) ).toEqual(snoozeTime); }); it('Should return undefined when element is a message and has no snooze time', () => { expect( getSnoozeTimeFromElement({ ConversationID: 'conversationID', } as Element) ).toEqual(undefined); }); }); describe('snooze helpers - getSnoozeDate', () => { const isSameTime = (date1: Date, date2: Date) => { const formatter = 'yyyy-MM-dd HH:mm:ss'; return format(date1, formatter) === format(date2, formatter); }; it('Should return current date when no element', () => { expect(isSameTime(getSnoozeDate(undefined, '1'), new Date())); }); it('Should return current date when element is not a conversation', () => { expect(isSameTime(getSnoozeDate({} as Element, '1'), new Date())); }); it('Should return snooze date when element is a conversation and has a snooze label', () => { const now = new Date(); const date = getSnoozeDate( { Labels: [{ ID: MAILBOX_LABEL_IDS.SNOOZED, ContextSnoozeTime: getUnixTime(now) }], } as Element, '1' ); expect(isSameTime(date, now)); }); });
4,053
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/snoozehelpers.ts
import { addDays, getUnixTime, nextMonday, nextSaturday, set } from 'date-fns'; import { c, msgid } from 'ttag'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { getDate, isConversation, isMessage } from '../helpers/elements'; import { SNOOZE_DURATION } from '../hooks/actions/useSnooze'; import { Conversation } from '../models/conversation'; import { Element } from '../models/element'; export const getSnoozeUnixTime = (duration: SNOOZE_DURATION, snoozeTime?: Date) => { const today = new Date(); switch (duration) { case 'tomorrow': const tomorrow = addDays(today, 1); return getUnixTime(set(tomorrow, { minutes: 0, seconds: 0, milliseconds: 0, hours: 9 })); case 'later': const twoDaysFromNow = addDays(today, 2); return getUnixTime(set(twoDaysFromNow, { minutes: 0, seconds: 0, milliseconds: 0, hours: 9 })); case 'weekend': const nextSat = nextSaturday(today); return getUnixTime(set(nextSat, { minutes: 0, seconds: 0, milliseconds: 0, hours: 9 })); case 'nextweek': const nextMon = nextMonday(today); return getUnixTime(set(nextMon, { minutes: 0, seconds: 0, milliseconds: 0, hours: 9 })); case 'custom': if (!snoozeTime) { throw new Error('Snooze time is required for custom snooze'); } return getUnixTime(snoozeTime); } }; export const getSnoozeNotificationText = (isSnoozing: boolean, elementsCount: number) => { if (isSnoozing) { return c('Success').ngettext( msgid`${elementsCount} conversation snoozed`, `${elementsCount} conversations snoozed`, elementsCount ); } return c('Success').ngettext( msgid`${elementsCount} conversation unsnoozed`, `${elementsCount} conversations unsnoozed`, elementsCount ); }; export const getSnoozeTimeFromElement = (element?: Element) => { if (!element) { return undefined; } if (isMessage(element)) { return (element as Message).SnoozeTime; } const contextSnoozeTime = (element as Conversation).Labels?.find(({ ID }) => { return ID === MAILBOX_LABEL_IDS.INBOX || ID === MAILBOX_LABEL_IDS.SNOOZED; })?.ContextSnoozeTime; return contextSnoozeTime; }; export const getSnoozeDate = (element: Element | undefined, labelID: string) => { const time = getSnoozeTimeFromElement(element); if (time) { return new Date(time * 1000); } // If the item don't have a snooze time we get the time of the element return getDate(element, labelID); }; export const isConversationElementSnoozed = (element: Element | undefined, conversationMode: boolean) => { if (!conversationMode) { return false; } return (element as Conversation)?.Labels?.some(({ ID }) => ID === MAILBOX_LABEL_IDS.SNOOZED); }; export const isMessageElementSnoozed = (element: Element | undefined, conversationMode: boolean) => { if (conversationMode) { return false; } const message = element as Message; return message.SnoozeTime && message?.LabelIDs.includes(MAILBOX_LABEL_IDS.SNOOZED); }; export const isElementSnoozed = (element: Element | undefined, conversationMode: boolean) => { return ( isConversationElementSnoozed(element, conversationMode) || isMessageElementSnoozed(element, conversationMode) ); }; export const isElementReminded = (element: Element | undefined) => { const isElementOrConversation = isMessage(element) || isConversation(element); return element && isElementOrConversation ? (element as Message | Conversation).DisplaySnoozedReminder ?? false : false; };
4,054
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/store.ts
import { useRef } from 'react'; import { TypedUseSelectorHook, useDispatch, useSelector, useStore } from 'react-redux'; import { configureStore } from '@reduxjs/toolkit'; import { useApi, useEventManager, useNotifications } from '@proton/components/hooks'; import { Api } from '@proton/shared/lib/interfaces'; import attachments from './attachments/attachmentsSlice'; import composers from './composers/composersSlice'; import contacts from './contacts/contactsSlice'; import conversations from './conversations/conversationsSlice'; import elements from './elements/elementsSlice'; import incomingDefaults from './incomingDefaults/incomingDefaultsSlice'; import layout from './layout/layoutSlice'; import messages from './messages/messagesSlice'; import snooze from './snooze/snoozeSlice'; const thunkExtraArgs = {} as unknown as AppThunkExtra['extra']; /** * Set thunk extra args needed at the `MainContainer` app level. * @warning use this method at the top of the app before store context is initialized. * @warning dont dispatch async thunks usind those extra args before this hook is runned */ export const useSetReduxThunkExtraArgs = () => { const api = useApi(); const notifications = useNotifications(); const eventManager = useEventManager(); /** * https://beta.reactjs.org/reference/react/useRef#avoiding-recreating-the-ref-contents */ const thunkExtraArgsDefined = useRef(false); if (!thunkExtraArgsDefined.current) { thunkExtraArgsDefined.current = true; Object.assign(thunkExtraArgs, { api, notifications, eventManager }); } }; /** * Typing has to be tweaked here. Store is generated inside a hook * to add utils inside thunk middleware. * Those utils depends on other react contexts. */ export const store = configureStore({ reducer: { elements, conversations, attachments, messages, contacts, incomingDefaults, composers, layout, snooze, }, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ thunk: { extraArgument: thunkExtraArgs }, // Serialization checks have to be restored // But we need some kind of regex ignore capacities serializableCheck: { // Ignore these field paths in state // ignoredPaths: [], // TODO ignoreState: true, // Ignore these field paths in all actions ignoredActionPaths: [ 'meta.arg', 'payload.abortController', 'payload.preparation', 'payload.decryption', 'payload', 'payload.attachment', 'payload.contacts', 'payload.contactGroups', ], warnAfter: 100, }, }), }); type Store = typeof store; export type RootState = ReturnType<Store['getState']>; export type AppDispatch = Store['dispatch']; export type AppThunkExtra = { state: RootState; dispatch: AppDispatch; extra: { api: Api; notifications: ReturnType<typeof useNotifications>; eventManager: ReturnType<typeof useEventManager>; }; }; export const useAppStore: () => Store = useStore; export const useAppDispatch: () => AppDispatch = useDispatch; export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
4,055
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/attachments/attachmentsActions.ts
import { createAction } from '@reduxjs/toolkit'; import { WorkerDecryptionResult } from '@proton/crypto'; export const addAttachment = createAction<{ ID: string; attachment: WorkerDecryptionResult<Uint8Array> }>( 'attachments/add' ); export const updateAttachment = createAction<{ ID: string; attachment: WorkerDecryptionResult<Uint8Array> }>( 'attachments/update' );
4,056
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/attachments/attachmentsReducers.ts
import { PayloadAction } from '@reduxjs/toolkit'; import { Draft } from 'immer'; import { WorkerDecryptionResult } from '@proton/crypto'; import { AttachmentsState } from './attachmentsTypes'; export const globalReset = (state: Draft<AttachmentsState>) => { Object.keys(state).forEach((key) => delete state[key]); }; export const setAttachment = ( state: Draft<AttachmentsState>, { payload: { ID, attachment } }: PayloadAction<{ ID: string; attachment: WorkerDecryptionResult<Uint8Array> }> ) => { state[ID] = attachment; };
4,057
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/attachments/attachmentsSelectors.ts
import { createSelector } from 'reselect'; import { RootState } from '../store'; const attachments = (state: RootState) => state.attachments; const currentID = (_: RootState, { ID }: { ID: string }) => ID; export const attachmentByID = createSelector( [attachments, currentID], (attachments, currentID) => attachments[currentID] );
4,058
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/attachments/attachmentsSlice.ts
import { createSlice } from '@reduxjs/toolkit'; import { globalReset } from '../actions'; import { addAttachment, updateAttachment } from './attachmentsActions'; import { globalReset as globalResetReducer, setAttachment as setAttachmentReducer } from './attachmentsReducers'; import { AttachmentsState } from './attachmentsTypes'; const attachmentsSlice = createSlice({ name: 'attachments', initialState: {} as AttachmentsState, reducers: {}, extraReducers: (builder) => { builder.addCase(globalReset, globalResetReducer); builder.addCase(addAttachment, setAttachmentReducer); builder.addCase(updateAttachment, setAttachmentReducer); }, }); export default attachmentsSlice.reducer;
4,059
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/attachments/attachmentsTypes.ts
import { WorkerDecryptionResult } from '@proton/crypto'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; export type AttachmentsState = SimpleMap<WorkerDecryptionResult<Uint8Array>>;
4,060
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/composers/composerSelectors.ts
import { createSelector } from 'reselect'; import { RootState } from '../store'; import { ComposerID } from './composerTypes'; const composers = (state: RootState) => state.composers.composers; const composerID = (_: RootState, ID: ComposerID) => ID; export const selectComposersCount = createSelector([composers], (composers) => Object.values(composers).length); export const selectOpenedComposersIds = createSelector([composers], (composers) => { const values = Object.values(composers); return values.map(({ ID }) => ID); }); export const selectComposer = createSelector([composers, composerID], (composers, id) => composers[id]);
4,061
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/composers/composerTypes.ts
import { Optional, Recipient } from '@proton/shared/lib/interfaces'; import { EditorTypes } from '../../hooks/composer/useComposerContent'; import { RecipientType } from '../../models/address'; type ComposerFields = { ID: string; messageID: string; senderEmailAddress: string; recipients: Record<RecipientType, Recipient[]>; /** TODO: Remove later. Used to trigger changes from a hook while moving to Redux */ changesCount: number; type: EditorTypes; }; /** * "loading" occurs when you open an existing message which is not yet loaded (for ex a draft) * "idle" occurs when Composer is ready */ type ComposerStatus = 'loading' | 'idle'; export type Composer = | ({ status: Extract<ComposerStatus, 'loading'>; } & Optional<ComposerFields, 'senderEmailAddress'>) | ({ status: Extract<ComposerStatus, 'idle'>; } & ComposerFields); export type ComposerID = string; export interface ComposersState { composers: Record<ComposerID, Composer>; }
4,062
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/composers/composersSlice.ts
import { PayloadAction, createSlice } from '@reduxjs/toolkit'; import { Optional, Recipient } from '@proton/shared/lib/interfaces'; import { RecipientType } from '../../models/address'; import { globalReset } from '../actions'; import { MessageState } from '../messages/messagesTypes'; import { Composer, ComposerID, ComposersState } from './composerTypes'; const initialState: ComposersState = { composers: {}, }; const getComposerUID = (() => { let current = 0; return () => `composer-${current++}`; })(); const composersSlice = createSlice({ name: 'composers', initialState, reducers: { addComposer( state, action: PayloadAction< Optional< Pick<Composer, 'messageID' | 'type' | 'senderEmailAddress' | 'recipients' | 'status'>, 'recipients' > > ) { const composerID = getComposerUID(); const { messageID, type, senderEmailAddress, recipients, status } = action.payload; const composer = { ID: composerID, messageID, type, senderEmailAddress, changesCount: 0, recipients: { ToList: recipients?.ToList || [], CCList: recipients?.CCList || [], BCCList: recipients?.BCCList || [], }, status, } as Composer; state.composers[composerID] = composer; }, setInitialized(state, action: PayloadAction<{ ID: ComposerID; message: MessageState }>) { state.composers[action.payload.ID].senderEmailAddress = action.payload.message?.data?.Sender.Address; state.composers[action.payload.ID].recipients = { ToList: action.payload.message.data?.ToList || [], CCList: action.payload.message.data?.CCList || [], BCCList: action.payload.message.data?.BCCList || [], }; }, removeComposer(state, action: PayloadAction<{ ID: ComposerID }>) { delete state.composers[action.payload.ID]; }, setSender(state, action: PayloadAction<{ ID: ComposerID; emailAddress: string }>) { const { ID, emailAddress } = action.payload; state.composers[ID].senderEmailAddress = emailAddress; state.composers[ID].changesCount += 1; }, setRecipients(state, action: PayloadAction<{ ID: ComposerID; type: RecipientType; recipients: Recipient[] }>) { const { ID, type, recipients } = action.payload; state.composers[ID].recipients[type] = recipients; state.composers[ID].changesCount += 1; }, }, extraReducers: (builder) => { builder.addCase(globalReset, (state) => { Object.keys(state.composers).forEach((key) => delete state.composers[key]); }); }, }); export const composerActions = composersSlice.actions; export default composersSlice.reducer;
4,063
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/contacts/contactsActions.ts
import { createAction } from '@reduxjs/toolkit'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; export const refresh = createAction<{ contacts: ContactEmail[]; contactGroups: ContactGroup[] }>('contacts/refresh');
4,064
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/contacts/contactsReducers.ts
import { PayloadAction } from '@reduxjs/toolkit'; import { Draft } from 'immer'; import { canonicalizeEmail } from '@proton/shared/lib/helpers/email'; import { toMap } from '@proton/shared/lib/helpers/object'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { initialState } from './contactsSlice'; import { ContactsMap, ContactsMapWithDuplicates, ContactsState, GroupsWithContactsMap } from './contactsTypes'; const toMapWithDuplicates = (contacts: ContactEmail[]) => { const contactsMapWithDuplicates = contacts.reduce<ContactsMapWithDuplicates>((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 contactsMap = Object.keys(contactsMapWithDuplicates).reduce<ContactsMap>((acc, key) => { acc[key] = contactsMapWithDuplicates[key]?.[0]; return acc; }, {}); return { contactsMap, contactsMapWithDuplicates }; }; 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 reset = (state: Draft<ContactsState>) => { Object.assign(state, initialState); }; export const refresh = ( state: Draft<ContactsState>, { payload: { contacts, contactGroups } }: PayloadAction<{ contacts: ContactEmail[]; contactGroups: ContactGroup[] }> ) => { const { contactsMap, contactsMapWithDuplicates } = toMapWithDuplicates(contacts); state.contactsMap = contactsMap; state.contactsMapWithDuplicates = contactsMapWithDuplicates; state.contactGroupsMap = toMap(contactGroups, 'Path'); state.groupsWithContactsMap = computeGroupsMap(contacts, contactGroups); state.recipientsLabelCache = {}; state.groupsLabelCache = {}; };
4,065
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/contacts/contactsSelectors.ts
import { RootState } from '../store'; export const contactsMap = (state: RootState) => state.contacts.contactsMap; export const contactGroupsMap = (state: RootState) => state.contacts.contactGroupsMap; export const groupsWithContactsMap = (state: RootState) => state.contacts.groupsWithContactsMap; export const recipientsLabelCache = (state: RootState) => state.contacts.recipientsLabelCache; export const groupsLabelCache = (state: RootState) => state.contacts.groupsLabelCache;
4,066
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/contacts/contactsSlice.ts
import { createSlice } from '@reduxjs/toolkit'; import { globalReset } from '../actions'; import { refresh } from './contactsActions'; import { refresh as refreshReducer, reset } from './contactsReducers'; import { ContactsState } from './contactsTypes'; export const initialState: ContactsState = { contactsMap: {}, contactsMapWithDuplicates: {}, contactGroupsMap: {}, groupsWithContactsMap: {}, recipientsLabelCache: {}, groupsLabelCache: {}, }; const elementsSlice = createSlice({ name: 'contacts', initialState, reducers: {}, extraReducers: (builder) => { builder.addCase(globalReset, reset); builder.addCase(refresh, refreshReducer); }, }); // Export the reducer, either as a default or named export export default elementsSlice.reducer;
4,067
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/contacts/contactsTypes.ts
import { SimpleMap } from '@proton/shared/lib/interfaces'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; export type ContactsMap = SimpleMap<ContactEmail>; export type ContactsMapWithDuplicates = SimpleMap<ContactEmail[]>; export type ContactGroupsMap = SimpleMap<ContactGroup>; export type GroupWithContacts = { group: ContactGroup; contacts: ContactEmail[] }; export type GroupsWithContactsMap = SimpleMap<GroupWithContacts>; export type ContactsState = { contactsMap: ContactsMap; contactsMapWithDuplicates: ContactsMapWithDuplicates; contactGroupsMap: ContactGroupsMap; groupsWithContactsMap: GroupsWithContactsMap; recipientsLabelCache: SimpleMap<string>; groupsLabelCache: SimpleMap<string>; };
4,068
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/conversations/conversationsActions.ts
import { createAction, createAsyncThunk } from '@reduxjs/toolkit'; import { getConversation } from '@proton/shared/lib/api/conversations'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { LabelChanges, UnreadStatus } from '../../helpers/labels'; import { MarkAsChanges } from '../../hooks/optimistic/useOptimisticMarkAs'; import { Conversation } from '../../models/conversation'; import { AppThunkExtra } from '../store'; import { ConversationEvent, ConversationParams, ConversationResult, ConversationState } from './conversationsTypes'; export const initialize = createAction<ConversationState>('conversations/initialize'); export const load = createAsyncThunk<ConversationResult, ConversationParams, AppThunkExtra>( 'conversations/load', async ({ silentFetch = false, conversationID, messageID }, thunkApi) => { try { return await thunkApi.extra.api({ ...getConversation(conversationID, messageID), silent: silentFetch }); } catch (error: any | undefined) { console.error(error); throw error; } } ); export const retryLoading = createAction<{ ID: string }>('conversations/retryLoading'); export const applyLabelsOnConversationMessages = createAction<{ ID: string; messageID: string; changes: LabelChanges; unreadStatuses: UnreadStatus[] | undefined; updatedConversation: Conversation; conversationResult: ConversationState; }>('conversations/optimistic/applyLabels/messages'); export const applyLabelsOnConversation = createAction<{ ID: string; changes: LabelChanges; unreadStatuses: UnreadStatus[] | undefined; }>('conversations/optimistic/applyLabels/conversation'); export const optimisticDelete = createAction<string>('conversations/optimistic/delete/conversation'); export const optimisticDeleteConversationMessages = createAction<{ ID: string; messages: Message[] }>( 'conversations/optimistic/delete/messages' ); export const optimisticRestore = createAction<ConversationState[]>('conversations/optimistic/restore'); export const optimisticMarkAsConversationMessages = createAction<{ ID: string; messageID: string; updatedConversation: Conversation; changes: MarkAsChanges; }>('conversations/optimistic/markAs/messages'); export const optimisticMarkAsConversation = createAction<{ ID: string; labelID: string; changes: MarkAsChanges }>( 'conversations/optimistic/markAs/conversation' ); export const deleteConversation = createAction<string>('conversations/delete'); export const updateConversation = createAction<{ ID: string; updates: Partial<ConversationState> }>( 'conversations/update' ); export const eventMessageUpdate = createAction<ConversationEvent>('conversations/event/messages'); export const eventDelete = createAction<string>('conversations/event/delete'); export const eventConversationUpdate = createAction<{ ID: string; updatedConversation: Conversation }>( 'conversations/event/update' );
4,069
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/conversations/conversationsReducers.ts
import { PayloadAction } from '@reduxjs/toolkit'; import { Draft } from 'immer'; import { isNotExistError } from '@proton/shared/lib/api/helpers/apiErrorHelper'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import isTruthy from '@proton/utils/isTruthy'; import { mergeConversations } from '../../helpers/conversation'; import { isConversation, parseLabelIDsInEvent } from '../../helpers/elements'; import { isNetworkError } from '../../helpers/errors'; import { LabelChanges, UnreadStatus, applyLabelChangesOnConversation, applyLabelChangesOnMessage, } from '../../helpers/labels'; import { applyMarkAsChangesOnMessage } from '../../helpers/message/messages'; import { MarkAsChanges, applyMarkAsChangesOnConversation } from '../../hooks/optimistic/useOptimisticMarkAs'; import { Conversation } from '../../models/conversation'; import { Element } from '../../models/element'; import { EventUpdates, QueryParams, QueryResults, TaskRunningInfo } from '../elements/elementsTypes'; import { RootState } from '../store'; import { allConversations, conversationByID } from './conversationsSelectors'; import { ConversationErrors, ConversationEvent, ConversationParams, ConversationResult, ConversationState, ConversationsState, } from './conversationsTypes'; export const globalReset = (state: Draft<ConversationsState>) => { Object.keys(state).forEach((key) => delete state[key]); }; const getConversation = (state: Draft<ConversationsState>, ID: string) => conversationByID({ conversations: state } as RootState, { ID }); const getAllConversation = (state: Draft<ConversationsState>) => allConversations({ conversations: state } as RootState); export const initialize = (state: Draft<ConversationsState>, action: PayloadAction<ConversationState>) => { state[action.payload.Conversation.ID] = action.payload as any; }; export const loadFulfilled = ( state: Draft<ConversationsState>, action: PayloadAction<ConversationResult, string, { arg: ConversationParams }> ) => { const { Conversation, Messages } = action.payload; const { conversationID } = action.meta.arg; const conversationState = getConversation(state, conversationID); if (conversationState) { conversationState.Conversation = Conversation; conversationState.Messages = Messages; conversationState.loadRetry = conversationState.loadRetry ? conversationState.loadRetry + 1 : 1; conversationState.errors = { network: [], unknown: [] }; } else { state[Conversation.ID] = { Conversation, Messages, loadRetry: 1, errors: { network: [], unknown: [] }, }; } }; export const loadRejected = ( state: Draft<ConversationsState>, action: PayloadAction<any, string, { arg: ConversationParams }, any | undefined> ) => { const { error } = action; const errors: ConversationErrors = {}; if (isNetworkError(error)) { errors.network = [error]; } else if (isNotExistError(error)) { errors.notExist = [error]; } else { errors.unknown = [error]; } const { conversationID } = action.meta.arg; const conversationState = getConversation(state, conversationID); if (conversationState) { conversationState.errors = errors; conversationState.loadRetry = conversationState.loadRetry ? conversationState.loadRetry + 1 : 1; } }; export const retryLoading = (state: Draft<ConversationsState>, { payload: { ID } }: PayloadAction<{ ID: string }>) => { const conversationState = getConversation(state, ID); if (conversationState) { conversationState.loadRetry = 0; conversationState.errors = {}; } }; export const applyLabelsOnConversationMessages = ( state: Draft<ConversationsState>, { payload: { ID, messageID, changes, unreadStatuses, updatedConversation, conversationResult }, }: PayloadAction<{ ID: string; messageID: string; changes: LabelChanges; unreadStatuses: UnreadStatus[] | undefined; updatedConversation: Conversation; conversationResult: ConversationState; }> ) => { const conversationState = getConversation(state, ID); if (conversationState) { conversationState.Conversation = updatedConversation; conversationState.Messages = conversationResult.Messages?.map((messageFromConversation: Message) => { if (messageFromConversation.ID === messageID) { return applyLabelChangesOnMessage(messageFromConversation, changes, unreadStatuses); } return messageFromConversation; }); } }; export const applyLabelsOnConversation = ( state: Draft<ConversationsState>, { payload: { ID, changes, unreadStatuses }, }: PayloadAction<{ ID: string; changes: LabelChanges; unreadStatuses: UnreadStatus[] | undefined }> ) => { const conversationState = getConversation(state, ID); if (conversationState) { conversationState.Conversation = applyLabelChangesOnConversation( conversationState.Conversation, changes, unreadStatuses ); } }; export const optimisticDelete = (state: Draft<ConversationsState>, { payload: ID }: PayloadAction<string>) => { delete state[ID]; }; export const optimisticDeleteConversationMessages = ( state: Draft<ConversationsState>, { payload: { ID, messages } }: PayloadAction<{ ID: string; messages: Message[] }> ) => { const conversationState = getConversation(state, ID); if (conversationState) { conversationState.Messages = messages; } }; export const optimisticRestore = ( state: Draft<ConversationsState>, { payload: conversations }: PayloadAction<ConversationState[]> ) => { conversations.forEach((conversation) => { state[conversation.Conversation.ID] = conversation; }); }; export const optimisticMarkAsConversationMessages = ( state: Draft<ConversationsState>, { payload: { ID, messageID, updatedConversation, changes }, }: PayloadAction<{ ID: string; messageID: string; updatedConversation: Conversation; changes: MarkAsChanges }> ) => { const conversationState = getConversation(state, ID); if (conversationState) { conversationState.Conversation = updatedConversation; conversationState.Messages = conversationState.Messages?.map((conversationMessage) => { if (conversationMessage.ID === messageID) { return applyMarkAsChangesOnMessage(conversationMessage, changes); } return conversationMessage; }); } }; export const optimisticMarkAsConversation = ( state: Draft<ConversationsState>, { payload: { ID, labelID, changes } }: PayloadAction<{ ID: string; labelID: string; changes: MarkAsChanges }> ) => { const conversationState = getConversation(state, ID); if (conversationState) { conversationState.Conversation = applyMarkAsChangesOnConversation( conversationState.Conversation, labelID, changes ); } }; export const deleteConversation = (state: Draft<ConversationsState>, { payload: ID }: PayloadAction<string>) => { delete state[ID]; }; export const updateConversation = ( state: Draft<ConversationsState>, { payload: { ID, updates } }: PayloadAction<{ ID: string; updates: Partial<ConversationState> }> ) => { const currentConversation = getConversation(state, ID); const updatedConversation = mergeConversations(currentConversation, updates); state[ID] = updatedConversation; }; export const eventMessagesUpdates = (state: Draft<ConversationsState>, action: PayloadAction<ConversationEvent>) => { const { toCreate, toUpdate, toDelete } = action.payload; if (toCreate.length === 0 && toUpdate.length === 0 && Object.keys(toDelete).length === 0) { return; } // Create and update conversation messages [...toCreate, ...toUpdate].forEach((messageEvent) => { const conversationState = getConversation(state, messageEvent.ConversationID); if (conversationState) { conversationState.loadRetry = 0; conversationState.errors = {}; const isUpdate = conversationState.Messages?.some((message: Message) => message.ID === messageEvent.ID); let updatedMessages: Message[]; if (isUpdate && conversationState.Messages) { updatedMessages = conversationState.Messages.map((message: Message) => { if (message.ID === messageEvent.ID) { return parseLabelIDsInEvent(message, messageEvent); } return message; }); } else { updatedMessages = [...(conversationState.Messages || []), messageEvent]; } conversationState.Messages = updatedMessages; } }); // Delete conversation messages if (Object.keys(toDelete).length > 0) { const allConversations = getAllConversation(state); allConversations.forEach((conversationState) => { if (conversationState?.Conversation.ID && conversationState.Messages) { const updatedMessages = conversationState.Messages.filter(({ ID }) => !toDelete[ID]); if (conversationState.Messages.length !== updatedMessages.length) { conversationState.Messages = updatedMessages; } } }); } }; export const eventConversationUpdate = ( state: Draft<ConversationsState>, { payload: { ID, updatedConversation } }: PayloadAction<{ ID: string; updatedConversation: Conversation }> ) => { const conversationState = getConversation(state, ID); if (conversationState) { conversationState.Conversation = updatedConversation; } }; // Update conversations from fetch elements export const updateFromElements = ( state: Draft<ConversationsState>, action: PayloadAction< { result: QueryResults; taskRunning: TaskRunningInfo; }, string, { arg: QueryParams; requestId: string; requestStatus: 'fulfilled'; }, never > ) => { const { Elements } = action.payload.result; if (Elements && Elements.length) { Elements.forEach((element) => { if (isConversation(element)) { const conversationState = getConversation(state, element.ID); if (conversationState) { conversationState.Conversation = { ...conversationState.Conversation, ...element }; } } }); } }; // Update conversations from individual element load export const updateFromLoadElements = ( state: Draft<ConversationsState>, action: PayloadAction<(Element | undefined)[], string, { arg: EventUpdates }> ) => { action.payload.filter(isTruthy).forEach((element) => { if (isConversation(element)) { const conversationState = getConversation(state, element.ID); if (conversationState) { conversationState.Conversation = element; } } }); }; export const updateMessageOnSend = (state: Draft<ConversationsState>, { payload: Sent }: PayloadAction<Message>) => { const conversationState = getConversation(state, Sent.ConversationID); if (conversationState?.Messages?.length) { const messageIndex = conversationState.Messages.findIndex((message) => message.ID === Sent.ID); if (messageIndex !== -1) { conversationState.Messages[messageIndex] = Sent; } } };
4,070
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/conversations/conversationsSelectors.ts
import { createSelector } from 'reselect'; import { RootState } from '../store'; const conversations = (state: RootState) => state.conversations; const currentID = (_: RootState, { ID }: { ID: string }) => ID; export const conversationByID = createSelector( [conversations, currentID], (conversations, currentID) => conversations[currentID] ); export const allConversations = createSelector([conversations], (conversations) => { return Object.values(conversations); });
4,071
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/conversations/conversationsSlice.ts
import { createSlice } from '@reduxjs/toolkit'; import { globalReset } from '../actions'; import { eventUpdates, load as loadElements } from '../elements/elementsActions'; import * as messageDraftAction from '../messages/draft/messagesDraftActions'; import { applyLabelsOnConversation, applyLabelsOnConversationMessages, deleteConversation, eventConversationUpdate, eventDelete, eventMessageUpdate, initialize, load, optimisticDelete, optimisticDeleteConversationMessages, optimisticMarkAsConversation, optimisticMarkAsConversationMessages, optimisticRestore, retryLoading, updateConversation, } from './conversationsActions'; import { applyLabelsOnConversationMessages as applyLabelsOnConversationMessagesReducer, applyLabelsOnConversation as applyLabelsOnConversationReducer, deleteConversation as deleteConversationReducer, eventConversationUpdate as eventConversationUpdateReducer, eventMessagesUpdates as eventMessageUpdateReducer, globalReset as globalResetReducer, initialize as initializeReducer, loadFulfilled, loadRejected, optimisticDeleteConversationMessages as optimisticDeleteConversationMessagesReducer, optimisticDelete as optimisticDeleteReducer, optimisticMarkAsConversationMessages as optimisticMarkAsConversationMessagesReducer, optimisticMarkAsConversation as optimisticMarkAsConversationReducer, optimisticRestore as optimisticRestoreReducer, retryLoading as retryLoadingReducer, updateConversation as updateConversationReducer, updateFromElements, updateFromLoadElements, updateMessageOnSend, } from './conversationsReducers'; import { ConversationsState } from './conversationsTypes'; const conversationSlice = createSlice({ name: 'conversations', initialState: {} as ConversationsState, reducers: {}, extraReducers: (builder) => { builder.addCase(globalReset, globalResetReducer); builder.addCase(initialize, initializeReducer); builder.addCase(load.fulfilled, loadFulfilled); builder.addCase(load.rejected, loadRejected); builder.addCase(retryLoading, retryLoadingReducer); builder.addCase(applyLabelsOnConversationMessages, applyLabelsOnConversationMessagesReducer); builder.addCase(applyLabelsOnConversation, applyLabelsOnConversationReducer); builder.addCase(deleteConversation, deleteConversationReducer); builder.addCase(optimisticDelete, optimisticDeleteReducer); builder.addCase(optimisticRestore, optimisticRestoreReducer); builder.addCase(optimisticDeleteConversationMessages, optimisticDeleteConversationMessagesReducer); builder.addCase(optimisticMarkAsConversationMessages, optimisticMarkAsConversationMessagesReducer); builder.addCase(optimisticMarkAsConversation, optimisticMarkAsConversationReducer); builder.addCase(updateConversation, updateConversationReducer); builder.addCase(eventMessageUpdate, eventMessageUpdateReducer); builder.addCase(eventDelete, deleteConversationReducer); builder.addCase(eventConversationUpdate, eventConversationUpdateReducer); builder.addCase(loadElements.fulfilled, updateFromElements); builder.addCase(eventUpdates.fulfilled, updateFromLoadElements); builder.addCase(messageDraftAction.sent, updateMessageOnSend); }, }); export default conversationSlice.reducer;
4,072
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/conversations/conversationsTypes.ts
import { SimpleMap } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { Conversation } from '../../models/conversation'; export interface ConversationResult { Conversation: Conversation; Messages?: Message[]; } export interface ConversationParams { silentFetch?: boolean; conversationID: string; messageID: string | undefined; } export interface ConversationErrors { network?: Error[]; notExist?: Error[]; unknown?: Error[]; } export interface ConversationEvent { toCreate: Message[]; toUpdate: Message[]; toDelete: { [ID: string]: boolean }; } export interface ConversationState { Conversation: Conversation; Messages?: Message[]; loadRetry: number; errors: ConversationErrors; } export type ConversationsState = SimpleMap<ConversationState>;
4,073
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/elementsActions.ts
import { createAction, createAsyncThunk } from '@reduxjs/toolkit'; import { moveAll as moveAllRequest, queryMessageMetadata } from '@proton/shared/lib/api/messages'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import diff from '@proton/utils/diff'; import unique from '@proton/utils/unique'; import { Element } from '../../models/element'; import { AppThunkExtra, RootState } from '../store'; import { ESResults, EventUpdates, NewStateParams, OptimisticDelete, OptimisticUpdates, QueryParams, QueryResults, TaskRunningInfo, } from './elementsTypes'; import { getQueryElementsParameters, queryElement, queryElements, refreshTaskRunningTimeout, } from './helpers/elementQuery'; const REFRESHES = [5, 10, 20]; export const reset = createAction<NewStateParams>('elements/reset'); export const updatePage = createAction<number>('elements/updatePage'); export const retry = createAction<{ queryParameters: any; error: Error | undefined }>('elements/retry'); export const load = createAsyncThunk< { result: QueryResults; taskRunning: TaskRunningInfo }, QueryParams, AppThunkExtra >( 'elements/load', async ( { page, params, abortController, conversationMode, count = 1 }: QueryParams, { dispatch, getState, extra } ) => { const queryParameters = getQueryElementsParameters({ page, params }); let result; try { result = await queryElements(extra.api, abortController, conversationMode, queryParameters); } catch (error: any | undefined) { // Wait a couple of seconds before retrying setTimeout(() => { dispatch(retry({ queryParameters, error })); }, 2000); throw error; } if (result.Stale === 1 && REFRESHES?.[count]) { const ms = 1000 * REFRESHES[count]; // Wait few seconds before retrying setTimeout(() => { if (isDeepEqual((getState() as RootState).elements.params, params)) { void dispatch(load({ page, params, abortController, conversationMode, count: count + 1 })); } }, ms); } const taskLabels = Object.keys(result.TasksRunning || {}); const taskRunning = { ...(getState() as RootState).elements.taskRunning }; if (taskLabels.length) { taskRunning.labelIDs = unique([...taskRunning.labelIDs, ...taskLabels]); taskRunning.timeoutID = refreshTaskRunningTimeout(taskRunning.labelIDs, { getState, dispatch, }); } return { result, taskRunning }; } ); export const removeExpired = createAction<Element>('elements/removeExpired'); export const invalidate = createAction<void>('elements/invalidate'); export const eventUpdates = createAsyncThunk<(Element | undefined)[], EventUpdates, AppThunkExtra>( 'elements/eventUpdates', async ({ conversationMode, toLoad }, thunkApi) => { return Promise.all( toLoad.map(async (element) => queryElement(thunkApi.extra.api, conversationMode, element.ID).catch(() => element) ) ); } ); export const manualPending = createAction<void>('elements/manualPending'); export const manualFulfilled = createAction<void>('elements/manualFulfilled'); export const addESResults = createAction<ESResults>('elements/addESResults'); export const optimisticApplyLabels = createAction<OptimisticUpdates>('elements/optimistic/applyLabels'); export const optimisticDelete = createAction<OptimisticDelete>('elements/optimistic/delete'); export const optimisticRestoreDelete = createAction<OptimisticUpdates>('elements/optimistic/restoreDelete'); export const optimisticEmptyLabel = createAction<void>('elements/optimistic/emptyLabel'); export const optimisticRestoreEmptyLabel = createAction<OptimisticUpdates>('elements/optimistic/restoreEmptyLabel'); export const optimisticMarkAs = createAction<OptimisticUpdates>('elements/optimistic/markAs'); export const backendActionStarted = createAction<void>('elements/action/started'); export const backendActionFinished = createAction<void>('elements/action/finished'); export const pollTaskRunning = createAsyncThunk<TaskRunningInfo, undefined, AppThunkExtra>( 'elements/pollTaskRunning', async (_, { dispatch, getState, extra }) => { await extra.eventManager.call(); const currentLabels = (getState() as RootState).elements.taskRunning.labelIDs; const finishedLabels = []; for (let label of currentLabels) { const result = await extra.api<QueryResults>(queryMessageMetadata({ LabelID: label })); const isLabelStillRunning = result?.TasksRunning && !Array.isArray(result.TasksRunning) && result.TasksRunning[label]; if (!isLabelStillRunning) { finishedLabels.push(label); } } const labelIDs = diff(currentLabels, finishedLabels); const timeoutID = refreshTaskRunningTimeout(labelIDs, { getState, dispatch, }); return { labelIDs, timeoutID }; } ); export const moveAll = createAsyncThunk< { LabelID: string; timeoutID: NodeJS.Timeout }, { SourceLabelID: string; DestinationLabelID: string }, AppThunkExtra >('elements/moveAll', async ({ SourceLabelID, DestinationLabelID }, { dispatch, getState, extra }) => { // If we move all to trash, we don't want to keep labels attached to the elements const isMoveToTrash = SourceLabelID === MAILBOX_LABEL_IDS.TRASH; await extra.api(moveAllRequest({ SourceLabelID, DestinationLabelID, KeepSourceLabel: isMoveToTrash ? 0 : 1 })); const timeoutID = refreshTaskRunningTimeout([SourceLabelID], { getState, dispatch, }); return { LabelID: SourceLabelID, timeoutID: timeoutID as NodeJS.Timeout }; });
4,074
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/elementsReducers.ts
import { PayloadAction } from '@reduxjs/toolkit'; import { Draft } from 'immer'; import { toMap } from '@proton/shared/lib/helpers/object'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import diff from '@proton/utils/diff'; import isTruthy from '@proton/utils/isTruthy'; import range from '@proton/utils/range'; import { MAX_ELEMENT_LIST_LOAD_RETRIES, PAGE_SIZE } from '../../constants'; import { parseLabelIDsInEvent, isMessage as testIsMessage } from '../../helpers/elements'; import { Conversation } from '../../models/conversation'; import { Element } from '../../models/element'; import { newState } from './elementsSlice'; import { ESResults, ElementsState, EventUpdates, NewStateParams, OptimisticDelete, OptimisticUpdates, QueryParams, QueryResults, TaskRunningInfo, } from './elementsTypes'; import { getElementsToBypassFilter } from './helpers/elementBypassFilters'; import { newRetry } from './helpers/elementQuery'; export const globalReset = (state: Draft<ElementsState>) => { Object.assign(state, newState()); }; export const reset = (state: Draft<ElementsState>, action: PayloadAction<NewStateParams>) => { Object.assign( state, newState({ ...action.payload, taskRunning: { labelIDs: state.taskRunning.labelIDs, timeoutID: state.taskRunning.timeoutID }, }) ); }; export const updatePage = (state: Draft<ElementsState>, action: PayloadAction<number>) => { state.page = action.payload; }; export const retry = ( state: Draft<ElementsState>, action: PayloadAction<{ queryParameters: any; error: Error | undefined }> ) => { state.beforeFirstLoad = false; state.invalidated = false; state.pendingRequest = false; state.retry = newRetry(state.retry, action.payload.queryParameters, action.payload.error); }; const hasSameMode = (state: Draft<ElementsState>, arg: QueryParams) => { return state.params.conversationMode === arg.params.conversationMode; }; export const loadPending = ( state: Draft<ElementsState>, action: PayloadAction<undefined, string, { arg: QueryParams }> ) => { if (hasSameMode(state, action.meta.arg)) { state.pendingRequest = true; state.page = action.meta.arg.page; } }; export const loadFulfilled = ( state: Draft<ElementsState>, action: PayloadAction<{ result: QueryResults; taskRunning: TaskRunningInfo }, string, { arg: QueryParams }> ) => { const { page, params } = action.meta.arg; const { result: { Total, Elements }, taskRunning, } = action.payload; if (hasSameMode(state, action.meta.arg)) { Object.assign(state, { beforeFirstLoad: false, invalidated: false, pendingRequest: false, page, total: Total, retry: newRetry(state.retry, params, undefined), }); state.pages.push(page); Object.assign(state.elements, toMap(Elements, 'ID')); state.taskRunning = taskRunning; } }; export const manualPending = (state: Draft<ElementsState>) => { state.pendingRequest = true; }; export const manualFulfilled = (state: Draft<ElementsState>) => { state.pendingRequest = false; }; export const removeExpired = (state: Draft<ElementsState>, action: PayloadAction<Element>) => { delete state.elements[action.payload.ID || '']; }; export const invalidate = (state: Draft<ElementsState>) => { state.invalidated = true; }; export const eventUpdatesPending = ( state: Draft<ElementsState>, action: PayloadAction<undefined, string, { arg: EventUpdates }> ) => { const { toCreate, toUpdate, toDelete } = action.meta.arg; toCreate.forEach((element) => { state.elements[element.ID || ''] = element; }); toUpdate.forEach((element) => { const existingElement = state.elements[element.ID || '']; if (existingElement) { state.elements[element.ID || ''] = parseLabelIDsInEvent(existingElement, element); } }); toDelete.forEach((elementID) => { delete state.elements[elementID]; }); }; export const eventUpdatesFulfilled = ( state: Draft<ElementsState>, action: PayloadAction<(Element | undefined)[], string, { arg: EventUpdates }> ) => { action.payload.filter(isTruthy).forEach((element) => { state.elements[element.ID || ''] = element; }); }; export const addESResults = (state: Draft<ElementsState>, action: PayloadAction<ESResults>) => { const total = action.payload.elements.length; const pages = range(0, Math.ceil(total / PAGE_SIZE)); // Retry is disabled for encrypted search results, to avoid re-triggering the search several times // when there are no results Object.assign(state, { bypassFilter: [], beforeFirstLoad: false, invalidated: false, pendingRequest: false, page: action.payload.page, total, pages, elements: toMap(action.payload.elements, 'ID'), retry: { payload: undefined, count: MAX_ELEMENT_LIST_LOAD_RETRIES, error: undefined }, }); }; export const optimisticUpdates = (state: Draft<ElementsState>, action: PayloadAction<OptimisticUpdates>) => { action.payload.elements.forEach((element) => { if (element.ID) { state.elements[element.ID] = element; } }); if (action.payload.isMove) { const elementIDs = action.payload.elements.map(({ ID }) => ID || ''); state.bypassFilter = diff(state.bypassFilter, elementIDs); } // If there is a filter applied when marking elements as read or unread, elements might need to bypass filters // e.g. filter is unread and marking elements as read, then we want to keep those items in the view if (action.payload.bypass && action.payload.markAsStatus) { const { conversationMode } = action.payload; const unreadFilter = state.params.filter.Unread as number | undefined; const { elementsToBypass, elementsToRemove } = getElementsToBypassFilter( action.payload.elements, action.payload.markAsStatus, unreadFilter ); // Add elements in the bypass array if they are not already present elementsToBypass.forEach((element) => { const isMessage = testIsMessage(element); const id = (isMessage && conversationMode ? (element as Message).ConversationID : element.ID) || ''; if (!state.bypassFilter.includes(id)) { state.bypassFilter.push(id); } }); // If we are not in a case where we need to bypass filter, // we need to remove elements if they are already in the array const toRemoveIDs = elementsToRemove.map((element) => { const isMessage = testIsMessage(element); return (isMessage && conversationMode ? (element as Message).ConversationID : element.ID) || ''; }); state.bypassFilter = state.bypassFilter.filter((elementID) => { return !toRemoveIDs.includes(elementID); }); } }; export const optimisticDelete = (state: Draft<ElementsState>, action: PayloadAction<OptimisticDelete>) => { action.payload.elementIDs.forEach((elementID) => { delete state.elements[elementID]; }); }; export const optimisticEmptyLabel = (state: Draft<ElementsState>) => { state.elements = {}; state.page = 0; }; export const backendActionStarted = (state: Draft<ElementsState>) => { state.pendingActions++; }; export const backendActionFinished = (state: Draft<ElementsState>) => { state.pendingActions--; }; export const moveAllFulfilled = ( state: Draft<ElementsState>, { payload: { LabelID, timeoutID } }: PayloadAction<{ LabelID: string; timeoutID: NodeJS.Timeout }> ) => { if (!state.taskRunning.labelIDs.includes(LabelID)) { state.taskRunning.labelIDs.push(LabelID); } state.taskRunning.timeoutID = timeoutID; }; export const pollTaskRunningFulfilled = (state: Draft<ElementsState>, { payload }: PayloadAction<TaskRunningInfo>) => { state.taskRunning = payload; }; export const deleteDraft = (state: Draft<ElementsState>, { payload: ID }: PayloadAction<string>) => { delete state.elements[ID]; }; const previousExpiration: Record<string, number | undefined> = {}; export const expireElementsPending = ( state: Draft<ElementsState>, action: PayloadAction< void, string, { arg: { IDs: string[]; expirationTime: number | null; conversationID?: string } } > ) => { const { IDs, expirationTime, conversationID } = action.meta.arg; const copyIDs = [...IDs]; // Copy the array to avoid mutating the original one // Look to update the Conversation.ExpirationTime that contains the only message if (conversationID) { const conversation = state.elements[conversationID] as Conversation; if (conversation && conversation.NumMessages === 1) { copyIDs.push(conversationID); } } copyIDs.forEach((ID) => { const element = state.elements[ID]; if (element) { previousExpiration[ID] = element.ExpirationTime; element.ExpirationTime = expirationTime ? expirationTime : undefined; } }); }; export const expireElementsFulfilled = ( state: Draft<ElementsState>, action: PayloadAction<Promise<void>, string, { arg: { IDs: string[]; conversationID?: string } }> ) => { const { IDs, conversationID } = action.meta.arg; const copyIDs = [...IDs]; // Copy the array to avoid mutating the original one // Look to update the Conversation.ExpirationTime that contains the only message if (conversationID) { const conversation = state.elements[conversationID] as Conversation; if (conversation && conversation.NumMessages === 1) { copyIDs.push(conversationID); } } copyIDs.forEach((ID) => { delete previousExpiration[ID]; }); }; export const expireElementsRejected = ( state: Draft<ElementsState>, action: PayloadAction<unknown, string, { arg: { IDs: string[]; conversationID?: string } }> ) => { const { IDs, conversationID } = action.meta.arg; const copyIDs = [...IDs]; // Copy the array to avoid mutating the original one // Look to update the Conversation.ExpirationTime that contains the only message if (conversationID) { const conversation = state.elements[conversationID] as Conversation; if (conversation && conversation.NumMessages === 1) { copyIDs.push(conversationID); } } copyIDs.forEach((ID) => { const element = state.elements[ID]; if (element) { element.ExpirationTime = previousExpiration[ID]; delete previousExpiration[ID]; } }); };
4,075
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/elementsSelectors.ts
import { createSelector } from 'reselect'; import { ESStatus, ES_EXTRA_RESULTS_LIMIT } from '@proton/encrypted-search'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { LabelCount } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { DEFAULT_PLACEHOLDERS_COUNT, ELEMENTS_CACHE_REQUEST_SIZE, MAX_ELEMENT_LIST_LOAD_RETRIES, PAGE_SIZE, } from '../../constants'; import { hasAttachments, hasAttachmentsFilter, hasLabel, isFilter, isSearch, isUnread, sort as sortElements, } from '../../helpers/elements'; import { expectedPageLength } from '../../helpers/paging'; import { ESBaseMessage, ESMessageContent, NormalizedSearchParams } from '../../models/encryptedSearch'; import { SearchParameters } from '../../models/tools'; import { RootState } from '../store'; import { ElementsStateParams } from './elementsTypes'; import { getTotal } from './helpers/elementTotal'; const beforeFirstLoad = (state: RootState) => state.elements.beforeFirstLoad; export const elementsMap = (state: RootState) => state.elements.elements; export const params = (state: RootState) => state.elements.params; const page = (state: RootState) => state.elements.page; const pages = (state: RootState) => state.elements.pages; const bypassFilter = (state: RootState) => state.elements.bypassFilter; const pendingRequest = (state: RootState) => state.elements.pendingRequest; export const pendingActions = (state: RootState) => state.elements.pendingActions; const retry = (state: RootState) => state.elements.retry; const invalidated = (state: RootState) => state.elements.invalidated; export const total = (state: RootState) => state.elements.total; export const taskRunning = (state: RootState) => state.elements.taskRunning; const currentPage = (_: RootState, { page }: { page: number }) => page; const currentSearch = (_: RootState, { search }: { search: SearchParameters }) => search; const currentParams = (_: RootState, { params }: { params: ElementsStateParams }) => params; const currentESDBStatus = ( _: RootState, { esStatus }: { esStatus: ESStatus<ESBaseMessage, ESMessageContent, NormalizedSearchParams> } ) => esStatus; const currentCounts = (_: RootState, { counts }: { counts: { counts: LabelCount[]; loading: boolean } }) => counts; export const elements = createSelector( [elementsMap, params, page, pages, bypassFilter], (elements, params, page, pages, bypassFilter) => { // Getting all params from the cache and not from scoped params // To prevent any desynchronization between cache and the output of the memo const { labelID, sort, filter } = params; let finalSort = sort; // The default sorting needs to be override when in inbox or snooze to display snoozed emails on top const isInSnoozeOrInbox = labelID === MAILBOX_LABEL_IDS.INBOX || labelID === MAILBOX_LABEL_IDS.SNOOZED; if (isInSnoozeOrInbox && sort.sort === 'Time') { finalSort = { sort: 'SnoozeTime', desc: labelID === MAILBOX_LABEL_IDS.SNOOZED ? !sort.desc : sort.desc, }; } const minPage = pages.reduce((acc, page) => (page < acc ? page : acc), pages[0]); const startIndex = (page - minPage) * PAGE_SIZE; const endIndex = startIndex + PAGE_SIZE; const elementsArray = Object.values(elements); const filtered = elementsArray .filter((element) => hasLabel(element, labelID)) .filter((element) => { if (!isFilter(filter)) { return true; } if (filter.Attachments) { return hasAttachments(element); } if (bypassFilter.includes(element.ID || '')) { return true; } const elementUnread = isUnread(element, labelID); return filter.Unread ? elementUnread : !elementUnread; }); const sorted = sortElements(filtered, finalSort, labelID); return sorted.slice(startIndex, endIndex); } ); export const elementIDs = createSelector(elements, (elements): string[] => elements.map((element) => element.ID).filter(isTruthy) ); export const elementsLength = createSelector(elements, (elements) => elements.length); export const elementsAreUnread = createSelector([params, elements], (params, elements) => { return elements.reduce<{ [elementID: string]: boolean }>((acc, element) => { acc[element.ID] = isUnread(element, params.labelID); return acc; }, {}); }); export const expiringElements = createSelector([params, elements], (params, elements) => { return elements.reduce<{ [elementID: string]: boolean }>((acc, element) => { acc[element.ID] = !!element.ExpirationTime && element.ExpirationTime > 0; return acc; }, {}); }); /** * Define when we need to request the API to get more elements * Dynamic computations (dynamicTotal and dynamicPageLength) have been proved not to be reliable enough * So the logic here is a lot more basic * It only checks when there is not a full page to show if the label has more than a cache size of elements * It doesn't rely at all on the optimistic counter logic */ export const needsMoreElements = createSelector([total, page, elementsLength], (total, page, elementsLength) => { if (total === undefined) { return false; } const howManyElementsAhead = total - page * PAGE_SIZE; return elementsLength < PAGE_SIZE && howManyElementsAhead > ELEMENTS_CACHE_REQUEST_SIZE; }); export const paramsChanged = createSelector([params, currentParams], (params, currentParams) => { const paramsChanged = currentParams.labelID !== params.labelID || currentParams.conversationMode !== params.conversationMode || currentParams.sort !== params.sort || currentParams.filter !== params.filter || currentParams.search !== params.search || (currentParams.esEnabled !== params.esEnabled && isSearch(currentParams.search)); return paramsChanged; }); export const pageCached = createSelector([pages, currentPage], (pages, currentPage) => pages.includes(currentPage)); export const pageChanged = createSelector([page, currentPage], (page, currentPage) => page !== currentPage); export const pageIsConsecutive = createSelector( [pages, currentPage], (pages, currentPage) => pages.length === 0 || pages.some((p) => p === currentPage || p === currentPage - 1 || p === currentPage + 1) ); export const shouldResetCache = createSelector( [paramsChanged, pageIsConsecutive], (paramsChanged, pageIsConsecutive) => { return paramsChanged || !pageIsConsecutive; } ); export const shouldSendRequest = createSelector( [shouldResetCache, pendingRequest, retry, needsMoreElements, invalidated, pageCached], (shouldResetCache, pendingRequest, retry, needsMoreElements, invalidated, pageCached) => { return ( shouldResetCache || (!pendingRequest && retry.count < MAX_ELEMENT_LIST_LOAD_RETRIES && (needsMoreElements || invalidated || !pageCached)) ); } ); export const isLive = createSelector( [params, pages], (params, pages) => !isSearch(params.search) && !hasAttachmentsFilter(params.filter) && pages.includes(0) ); export const shouldUpdatePage = createSelector( [pageChanged, pageCached], (pageChanged, pageCached) => pageChanged && pageCached ); export const isES = createSelector( [currentESDBStatus, currentSearch], ({ dbExists, esEnabled, getCacheStatus }, search) => { const { isCacheLimited } = getCacheStatus(); return dbExists && esEnabled && isSearch(search) && (!!search.keyword || !isCacheLimited); } ); /** * Loading more search results using ES should be done only under the * following circumstances: * - ES is being used for the search; * - the cache is limited, i.e. the local index is too large to safely fit * in memory and there are messages which are only stored on disk; * - the search is partial, meaning that the whole index on disk hasn't been * fully searched yet; * - a new page of results has been queried by the user's navigation; * - the total number of messages in the results list is not enough to fill * at least the current and the subsequent pages */ export const messagesToLoadMoreES = createSelector( [currentESDBStatus, isES, pageChanged, total, currentPage], ({ getCacheStatus, isSearchPartial }, useES, pageChanged, total, currentPage) => { const { isCacheLimited } = getCacheStatus(); if ( useES && isCacheLimited && isSearchPartial && pageChanged && (total ?? 0) < (currentPage + 2) * ES_EXTRA_RESULTS_LIMIT ) { return (currentPage + 2) * ES_EXTRA_RESULTS_LIMIT - (total ?? 0); } return 0; } ); /** * Computed up to date total of elements for the current parameters * Warning: this value has been proved not to be 100% consistent * Has to be used only for non sensitive behaviors */ export const dynamicTotal = createSelector( [params, currentCounts, bypassFilter], (params, { counts, loading }, bypassFilter) => { if (isSearch(params.search) || hasAttachmentsFilter(params.filter) || loading) { return undefined; } return getTotal(counts, params.labelID, params.filter, bypassFilter.length); } ); /** * Computed up to date number of elements on the current page * Warning: this value has been proved not to be 100% consistent * Has to be used only for non sensitive behaviors */ export const dynamicPageLength = createSelector( [page, dynamicTotal, params, bypassFilter], (page, dynamicTotal, params, bypassFilter) => { if (dynamicTotal === undefined) { return undefined; } return expectedPageLength(page, dynamicTotal, isFilter(params.filter) ? bypassFilter.length : 0); } ); export const placeholderCount = createSelector( [page, total, params, dynamicPageLength], (page, total, params, dynamicPageLength) => { if (dynamicPageLength !== undefined) { return dynamicPageLength; } if (total !== undefined) { return expectedPageLength(page, total, isFilter(params.filter) ? bypassFilter.length : 0); } return DEFAULT_PLACEHOLDERS_COUNT; } ); export const loading = createSelector( [beforeFirstLoad, pendingRequest, shouldSendRequest, invalidated], (beforeFirstLoad, pendingRequest, shouldSendRequest, invalidated) => (beforeFirstLoad || pendingRequest || shouldSendRequest) && !invalidated ); export const totalReturned = createSelector([dynamicTotal, total], (dynamicTotal, total) => dynamicTotal || total); export const expectingEmpty = createSelector([dynamicPageLength], (dynamicPageLength) => dynamicPageLength === 0); export const loadedEmpty = createSelector( [beforeFirstLoad, pendingRequest, total], (beforeFirstLoad, pendingRequest, total) => !beforeFirstLoad && pendingRequest === false && total === 0 ); export const partialESSearch = createSelector([isES, currentESDBStatus], (useES, currentESDBStatus) => { const { isCacheLimited } = currentESDBStatus.getCacheStatus(); return useES && isCacheLimited && currentESDBStatus.isSearchPartial; }); export const stateInconsistency = createSelector( [beforeFirstLoad, pendingRequest, retry, isES], (beforeFirstLoad, pendingRequest, retry, useES) => !beforeFirstLoad && !pendingRequest && retry.error === undefined && retry.count === 3 && !useES ); export const showLabelTaskRunningBanner = createSelector([taskRunning], (taskRunning) => { return taskRunning.labelIDs.length > 0; });
4,076
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/elementsSlice.ts
import { PayloadAction, createSlice } from '@reduxjs/toolkit'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { globalReset } from '../actions'; import { deleteDraft } from '../messages/draft/messagesDraftActions'; import { expireMessages } from '../messages/expire/messagesExpireActions'; import { addESResults, backendActionFinished, backendActionStarted, eventUpdates, invalidate, load, manualFulfilled, manualPending, moveAll, optimisticApplyLabels, optimisticDelete, optimisticEmptyLabel, optimisticMarkAs, optimisticRestoreDelete, optimisticRestoreEmptyLabel, pollTaskRunning, removeExpired, reset, retry, updatePage, } from './elementsActions'; import { addESResults as addESResultsReducer, backendActionFinished as backendActionFinishedReducer, backendActionStarted as backendActionStartedReducer, deleteDraft as deleteDraftReducer, eventUpdatesFulfilled, eventUpdatesPending, expireElementsFulfilled, expireElementsPending, expireElementsRejected, globalReset as globalResetReducer, invalidate as invalidateReducer, loadFulfilled, loadPending, manualFulfilled as manualFulfilledReducer, manualPending as manualPendingReducer, moveAllFulfilled, optimisticDelete as optimisticDeleteReducer, optimisticEmptyLabel as optimisticEmptyLabelReducer, optimisticUpdates, pollTaskRunningFulfilled, removeExpired as removeExpiredReducer, reset as resetReducer, retry as retryReducer, updatePage as updatePageReducer, } from './elementsReducers'; import { ElementsState, ElementsStateParams, NewStateParams, TaskRunningInfo } from './elementsTypes'; export const newState = ({ page = 0, params = {}, retry = { payload: null, count: 0, error: undefined }, beforeFirstLoad = true, taskRunning = { labelIDs: [], timeoutID: undefined }, }: NewStateParams & { taskRunning?: TaskRunningInfo } = {}): ElementsState => { const defaultParams: ElementsStateParams = { labelID: MAILBOX_LABEL_IDS.INBOX, conversationMode: true, filter: {}, sort: { sort: 'Time', desc: true }, search: {}, esEnabled: false, }; return { beforeFirstLoad, invalidated: false, pendingRequest: false, pendingActions: 0, params: { ...defaultParams, ...params }, page, total: undefined, elements: {}, pages: [], bypassFilter: [], retry, taskRunning, }; }; const elementsSlice = createSlice({ name: 'elements', initialState: newState(), reducers: { updateTasksRunning: (state, action: PayloadAction<{ taskRunning: TaskRunningInfo }>) => { state.taskRunning = action.payload.taskRunning; }, }, extraReducers: (builder) => { builder.addCase(globalReset, globalResetReducer); builder.addCase(reset, resetReducer); builder.addCase(updatePage, updatePageReducer); builder.addCase(load.pending, loadPending); builder.addCase(load.fulfilled, loadFulfilled); builder.addCase(retry, retryReducer); builder.addCase(removeExpired, removeExpiredReducer); builder.addCase(invalidate, invalidateReducer); builder.addCase(eventUpdates.pending, eventUpdatesPending); builder.addCase(eventUpdates.fulfilled, eventUpdatesFulfilled); builder.addCase(manualPending, manualPendingReducer); builder.addCase(manualFulfilled, manualFulfilledReducer); builder.addCase(addESResults, addESResultsReducer); builder.addCase(optimisticApplyLabels, optimisticUpdates); builder.addCase(optimisticDelete, optimisticDeleteReducer); builder.addCase(optimisticRestoreDelete, optimisticUpdates); builder.addCase(optimisticEmptyLabel, optimisticEmptyLabelReducer); builder.addCase(optimisticRestoreEmptyLabel, optimisticUpdates); builder.addCase(optimisticMarkAs, optimisticUpdates); builder.addCase(backendActionStarted, backendActionStartedReducer); builder.addCase(backendActionFinished, backendActionFinishedReducer); builder.addCase(moveAll.fulfilled, moveAllFulfilled); builder.addCase(pollTaskRunning.fulfilled, pollTaskRunningFulfilled); builder.addCase(deleteDraft, deleteDraftReducer); builder.addCase(expireMessages.pending, expireElementsPending); builder.addCase(expireMessages.fulfilled, expireElementsFulfilled); builder.addCase(expireMessages.rejected, expireElementsRejected); }, }); export const elementsSliceActions = elementsSlice.actions; // Export the reducer, either as a default or named export export default elementsSlice.reducer;
4,077
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/elementsTypes.ts
import { MARK_AS_STATUS } from '../../hooks/actions/useMarkAs'; import { Element } from '../../models/element'; import { LabelIDsChanges } from '../../models/event'; import { Filter, SearchParameters, Sort } from '../../models/tools'; export interface ElementsStateParams { labelID: string; conversationMode: boolean; sort: Sort; filter: Filter; search: SearchParameters; esEnabled: boolean; } export interface RetryData { payload: any; count: number; error: Error | undefined; } export interface TaskRunningInfo { labelIDs: string[]; timeoutID: NodeJS.Timeout | undefined; } export interface ElementsState { /** * True when the first request has not been sent * Allow to show a loading state even before the first request is sent */ beforeFirstLoad: boolean; /** * The cache is invalidated and the request should be re-sent */ invalidated: boolean; /** * A request is currently pending */ pendingRequest: boolean; /** * An action is pending backend side on the element list and it shouldnt be refreshed yet */ pendingActions: number; /** * Current parameters of the list (label, filter, sort, search) */ params: ElementsStateParams; /** * Current page number */ page: number; /** * List of page number currently in the cache */ pages: number[]; /** * Total of elements returned by the current request * Undefined before the request return * Warning, if the user perform move actions, this value can be hugely outdated */ total: number | undefined; /** * Actual cache of elements indexed by there ids * Contains all elements loaded since last cache reset */ elements: { [ID: string]: Element }; /** * List of element's id which are allowed to bypass the current filter */ bypassFilter: string[]; /** * Retry data about the last request * Keeps track of the last request to count the number of attemps */ retry: RetryData; /** * Labels on which on task is currently running */ taskRunning: TaskRunningInfo; } export interface QueryParams { abortController: AbortController | undefined; conversationMode: boolean; page: number; params: ElementsStateParams; count?: number; } export interface QueryResults { abortController: AbortController; Total: number; Elements: Element[]; Stale: number; /** * About TasksRunning: * - Returns an empty array when no results * - Returns a object when results * - TasksRunning key does not exist when LabelID is not present in query params. */ TasksRunning?: { [labelID: string]: any } | string[]; } export interface NewStateParams { page?: number; params?: Partial<ElementsStateParams>; retry?: RetryData; beforeFirstLoad?: boolean; } export interface EventUpdates { conversationMode: boolean; toCreate: (Element & LabelIDsChanges)[]; toUpdate: (Element & LabelIDsChanges)[]; toLoad: (Element & LabelIDsChanges)[]; toDelete: string[]; } export interface ESResults { page: number; elements: Element[]; } export interface OptimisticUpdates { elements: Element[]; isMove?: boolean; bypass?: boolean; conversationMode?: boolean; markAsStatus?: MARK_AS_STATUS; } export interface OptimisticDelete { elementIDs: string[]; }
4,078
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/helpers/elementBypassFilters.test.ts
import { MARK_AS_STATUS } from '../../../hooks/actions/useMarkAs'; import { Element } from '../../../models/element'; import { getElementsToBypassFilter } from './elementBypassFilters'; describe('getElementsToBypassFilter', () => { const elements = [{ ID: 'message1' } as Element, { ID: 'message2' } as Element] as Element[]; it.each` unreadFilter | markAsAction | elementsToBypass | elementsToRemove ${0} | ${MARK_AS_STATUS.READ} | ${[]} | ${elements} ${1} | ${MARK_AS_STATUS.UNREAD} | ${[]} | ${elements} ${0} | ${MARK_AS_STATUS.UNREAD} | ${elements} | ${[]} ${1} | ${MARK_AS_STATUS.READ} | ${elements} | ${[]} ${undefined} | ${MARK_AS_STATUS.READ} | ${[]} | ${[]} ${undefined} | ${MARK_AS_STATUS.UNREAD} | ${[]} | ${[]} `( 'it should return the expected elementsToBypass when unreadFilter is [$unreadFilter] and marking elements as [$markAsAction]', ({ unreadFilter, markAsAction, elementsToBypass, elementsToRemove }) => { const expected = { elementsToBypass, elementsToRemove }; expect(getElementsToBypassFilter(elements, markAsAction, unreadFilter)).toEqual(expected); } ); });
4,079
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/helpers/elementBypassFilters.ts
import { MARK_AS_STATUS } from '../../../hooks/actions/useMarkAs'; import { Element } from '../../../models/element'; export const getElementsToBypassFilter = (elements: Element[], action: MARK_AS_STATUS, unreadFilter?: number) => { let elementsToBypass: Element[] = []; let elementsToRemove: Element[] = elements; // If no unreadFilter, there is no filter applied, so no need to bypass filters if (unreadFilter === undefined) { return { elementsToBypass: [], elementsToRemove: [] }; } else { /** * IF * - The filter UNREAD is currently applied and elements are marked as UNREAD * - The filter READ is currently applied and elements are marked as READ * * Then we don't need to add elements in the bypass array. * However, it's possible that they are in the bypass array already. In that case we want to remove them from the array * * => We will return {elementsToByPass: [], elementsToRemove: elements} */ const dontNeedBypass = (unreadFilter > 0 && action === MARK_AS_STATUS.UNREAD) || (unreadFilter === 0 && action === MARK_AS_STATUS.READ); /** * Otherwise, we need to push the items in the bypass array * * => We will return {elementsToByPass: elements, elementsToRemove: []} */ if (!dontNeedBypass) { elementsToBypass = elements; elementsToRemove = []; } } return { elementsToBypass, elementsToRemove }; };
4,080
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/helpers/elementQuery.ts
import { getConversation, queryConversations } from '@proton/shared/lib/api/conversations'; import { getMessage, queryMessageMetadata } from '@proton/shared/lib/api/messages'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import { Api } from '@proton/shared/lib/interfaces'; import { ELEMENTS_CACHE_REQUEST_SIZE, PAGE_SIZE } from '../../../constants'; import { Element } from '../../../models/element'; import { RootState } from '../../store'; import { pollTaskRunning } from '../elementsActions'; import { QueryParams, QueryResults, RetryData } from '../elementsTypes'; export const TASK_RUNNING_POLLING_INTERVAL = 2000; export const getQueryElementsParameters = ({ page, params: { labelID, sort, search, filter }, }: Pick<QueryParams, 'page' | 'params'>): any => ({ Page: page, PageSize: PAGE_SIZE, Limit: ELEMENTS_CACHE_REQUEST_SIZE, LabelID: labelID, Sort: sort.sort, Desc: sort.desc ? 1 : 0, Begin: search.begin, End: search.end, // BeginID, // EndID, Keyword: search.keyword, To: search.to, From: search.from, // Subject, Attachments: filter.Attachments, Unread: filter.Unread, AddressID: search.address, // ID, AutoWildcard: search.wildcard, }); export const queryElements = async ( api: Api, abortController: AbortController | undefined, conversationMode: boolean, payload: QueryParams ): Promise<QueryResults> => { abortController?.abort(); const newAbortController = new AbortController(); const query = conversationMode ? queryConversations : queryMessageMetadata; const result: any = await api({ ...query(payload as any), signal: newAbortController.signal }); return { abortController: newAbortController, Total: result.Total, Elements: conversationMode ? result.Conversations : result.Messages, Stale: result.Stale, TasksRunning: result.TasksRunning, }; }; /** * A retry is the same request as before expecting a different result * @param payload: request params + expected total * @param error: optional error from last request */ export const newRetry = (retry: RetryData, payload: any, error: Error | undefined) => { const count = error && isDeepEqual(payload, retry.payload) ? retry.count + 1 : 1; return { payload, count, error }; }; export const queryElement = async (api: Api, conversationMode: boolean, elementID: string): Promise<Element> => { const query = conversationMode ? getConversation : getMessage; const result: any = await api({ ...query(elementID), silence: true }); return conversationMode ? result.Conversation : result.Message; }; export const refreshTaskRunningTimeout = ( newLabelIDs: string[], { getState, dispatch }: { getState: () => unknown; dispatch: (action: any) => void } ): NodeJS.Timeout | undefined => { let timeoutID: NodeJS.Timeout | undefined = (getState() as RootState).elements.taskRunning.timeoutID; if (timeoutID) { clearTimeout(timeoutID); timeoutID = undefined; } if (newLabelIDs.length > 0) { timeoutID = setTimeout(() => { void dispatch(pollTaskRunning()); }, TASK_RUNNING_POLLING_INTERVAL); } return timeoutID; };
4,081
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/helpers/elementTotal.test.ts
import { LabelCount } from '@proton/shared/lib/interfaces'; import { getTotal } from './elementTotal'; describe('getTotal', () => { it('should return the correct count with no filter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 45, Unread: 45, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, {}, 0)).toEqual(45); }); it('should return the correct count with unread filter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 45, Unread: 40, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, { Unread: 1 }, 0)).toEqual(40); }); it('should return the correct count with read filter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 45, Unread: 40, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, { Unread: 0 }, 0)).toEqual(5); }); it('should return the correct count with unread filter and bypassFilter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 55, Unread: 50, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, { Unread: 1 }, 5)).toEqual(55); }); it('should return the correct count with unread filter and bypassFilter', () => { const labelID = '1'; const labelCounts = [ { LabelID: labelID, Total: 55, Unread: 5, }, ] as LabelCount[]; expect(getTotal(labelCounts, labelID, { Unread: 0 }, 5)).toEqual(55); }); });
4,082
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/elements/helpers/elementTotal.ts
import { LabelCount } from '@proton/shared/lib/interfaces'; import { Filter } from '../../../models/tools'; export const getTotal = (counts: LabelCount[], labelID: string, filter: Filter, bypassFilterCount: number) => { const count = counts.find((count) => count.LabelID === labelID); if (!count) { return 0; } const unreadFilter = filter.Unread as number | undefined; if (unreadFilter === undefined) { return count.Total || 0; } if (unreadFilter > 0) { return (count.Unread || 0) + bypassFilterCount; } return (count.Total || 0) - (count.Unread || 0) + bypassFilterCount; };
4,083
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/eo/eoActions.ts
import { createAction, createAsyncThunk } from '@reduxjs/toolkit'; import { CryptoProxy } from '@proton/crypto'; import { decodeUtf8Base64, encodeUtf8Base64 } from '@proton/crypto/lib/utils'; import { getEOMessage, getEOToken } from '@proton/shared/lib/api/eo'; import { EO_DECRYPTED_TOKEN_KEY, EO_PASSWORD_KEY, EO_TOKEN_KEY } from '../../constants'; import { get } from '../../helpers/attachment/attachmentLoader'; import { convertEOtoMessageState, eoDecrypt } from '../../helpers/eo/message'; import { createBlob } from '../../helpers/message/messageEmbeddeds'; import { MessageState, OutsideKey } from '../messages/messagesTypes'; import { EODocumentInitializeParams, EOInitParams, EOInitResult, EOLoadEmbeddedParams, EOLoadEmbeddedResults, EOLoadRemoteParams, EOMessage, EOMessageParams, EOMessageReply, EOTokenParams, } from './eoType'; export const init = createAsyncThunk<EOInitResult, EOInitParams>('eo/init', async ({ get }) => { try { const token = get(EO_TOKEN_KEY); const decryptedToken = get(EO_DECRYPTED_TOKEN_KEY); const password = get(EO_PASSWORD_KEY); return { token, decryptedToken: decryptedToken ? decodeUtf8Base64(decryptedToken) : undefined, password: password ? decodeUtf8Base64(password) : undefined, }; } catch (error: any | undefined) { console.log(error); throw error; } }); export const loadEOToken = createAsyncThunk<string, EOTokenParams>('eo/token/load', async ({ api, id, set }) => { try { const { Token } = await api(getEOToken(id)); set(EO_TOKEN_KEY, Token); return Token; } catch (error: any | undefined) { console.log(error); throw error; } }); export const loadEOMessage = createAsyncThunk<{ eoMessage: EOMessage; messageState: MessageState }, EOMessageParams>( 'eo/message/load', async ({ api, token, id, password, set }) => { try { const { Message, PublicKey } = await api(getEOMessage(token, id)); Message.PublicKey = [await CryptoProxy.importPublicKey({ armoredKey: PublicKey })]; // Decrypt replies bodies (Useless for now, but might be needed if we want to display replies) await eoDecrypt(Message?.Body, password).then((body) => { Message.DecryptedBody = body; }); const messageState = convertEOtoMessageState(Message, token) as any; set(EO_DECRYPTED_TOKEN_KEY, encodeUtf8Base64(token)); set(EO_PASSWORD_KEY, encodeUtf8Base64(password)); return { eoMessage: Message, messageState }; } catch (error: any | undefined) { console.log(error); throw error; } } ); export const EODocumentInitializePending = createAction<void>('eo/message/document/initialize/pending'); export const EODocumentInitializeFulfilled = createAction<EODocumentInitializeParams>( 'eo/message/document/initialize/fulfilled' ); export const EOLoadEmbedded = createAsyncThunk<EOLoadEmbeddedResults, EOLoadEmbeddedParams>( 'eo/message/embedded/load', async ({ attachments, api, messageVerification, password, id, decryptedToken }) => { return Promise.all( attachments.map(async (attachment) => { const buffer = await get( attachment, messageVerification, { type: 'outside', id, password, decryptedToken, } as OutsideKey, api ); return { attachment, blob: createBlob(attachment, buffer.data as Uint8Array), }; }) ); } ); export const EOLoadRemote = createAction<EOLoadRemoteParams>('eo/message/remote/load/url'); export const EOAddReply = createAction<EOMessageReply>('eo/message/reply');
4,084
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/eo/eoReducers.ts
import { PayloadAction } from '@reduxjs/toolkit'; import { Draft } from 'immer'; import { markEmbeddedImagesAsLoaded } from '../../helpers/message/messageEmbeddeds'; import { getEmbeddedImages, getRemoteImages, updateImages } from '../../helpers/message/messageImages'; import { loadBackgroundImages, loadImages } from '../../helpers/message/messageRemotes'; import { MessageRemoteImage, MessageState } from '../messages/messagesTypes'; import { eoMessageSelector, eoMessageStateSelector } from './eoSelectors'; import { initialState } from './eoSlice'; import { RootState } from './eoStore'; import { EODocumentInitializeParams, EOInitParams, EOInitResult, EOLoadEmbeddedParams, EOLoadEmbeddedResults, EOLoadRemoteParams, EOMessage, EOMessageParams, EOMessageReply, EOState, EOTokenParams, } from './eoType'; export const getMessageState = (state: Draft<EOState>) => eoMessageStateSelector({ eo: state } as RootState); export const getEOMessage = (state: Draft<EOState>) => eoMessageSelector({ eo: state } as RootState); const getStateImage = <T extends { image: MessageRemoteImage }>(data: T, messageState: MessageState) => { const remoteImages = getRemoteImages(messageState); const { image: inputImage, ...rest } = data; const image = remoteImages.find((image) => image.id === inputImage.id) as MessageRemoteImage; return { image, inputImage, ...rest }; }; export const reset = (state: Draft<EOState>) => { Object.assign(state, initialState); }; export const initFulfilled = ( state: Draft<EOState>, action: PayloadAction<EOInitResult, string, { arg: EOInitParams }> ) => { const { token, decryptedToken, password } = action.payload; if (token) { state.encryptedToken = token; } if (decryptedToken) { state.decryptedToken = decryptedToken; } if (password) { state.password = password; } state.isStoreInitialized = true; }; export const loadEOTokenFulfilled = ( state: Draft<EOState>, action: PayloadAction<string, string, { arg: EOTokenParams }> ) => { state.encryptedToken = action.payload; }; export const loadEOMessageFulfilled = ( state: Draft<EOState>, action: PayloadAction<{ eoMessage: EOMessage; messageState: MessageState }, string, { arg: EOMessageParams }> ) => { state.password = action.meta.arg.password; state.decryptedToken = action.meta.arg.token; state.message = action.payload.eoMessage as any; state.messageState = action.payload.messageState as any; }; export const EODocumentInitializePending = (state: Draft<EOState>) => { state.messageState.messageDocument = { initialized: false }; }; export const EODocumentInitializeFulfilled = ( state: Draft<EOState>, { payload: { dataChanges, initialized, preparation, decryption, errors, messageImages }, }: PayloadAction<EODocumentInitializeParams> ) => { const messageState = getMessageState(state); if (messageState) { Object.assign(messageState.data!, dataChanges); if (messageState.messageDocument) { messageState.messageDocument.initialized = initialized; messageState.messageDocument.document = preparation?.document; messageState.messageDocument.plainText = preparation?.plainText; } messageState.decryption = decryption; messageState.errors = errors; messageState.loadRetry = messageState.loadRetry ? messageState.loadRetry + 1 : 1; messageState.messageImages = messageImages; } }; export const EOLoadEmbeddedFulfilled = ( state: Draft<EOState>, { payload }: PayloadAction<EOLoadEmbeddedResults, string, { arg: EOLoadEmbeddedParams }> ) => { const messageState = getMessageState(state); if (messageState) { const embeddedImages = getEmbeddedImages(messageState); const updatedEmbeddedImages = markEmbeddedImagesAsLoaded(embeddedImages, payload); messageState.messageImages = updateImages( messageState.messageImages, { showEmbeddedImages: true }, undefined, updatedEmbeddedImages ); } }; export const EOLoadRemote = ( state: Draft<EOState>, // action: PayloadAction<LoadRemoteFromURLParams> action: PayloadAction<EOLoadRemoteParams> ) => { const { imagesToLoad } = action.payload; const messageState = getMessageState(state); if (messageState && messageState.messageImages) { imagesToLoad.forEach((imageToLoad) => { if (messageState.messageImages) { const imageToLoadState = getStateImage({ image: imageToLoad }, messageState); const { image, inputImage } = imageToLoadState; let newImage: MessageRemoteImage = { ...inputImage }; if (imageToLoad.url || imageToLoad.originalURL) { // Image is already in state, we only need to put it as loaded if (image) { image.status = 'loaded'; image.error = undefined; if (image.url) { image.originalURL = image.url; } else { // When using load direct, imageToLoad.url might have been removed image.url = imageToLoad.originalURL; image.originalURL = imageToLoad.url; } } else if (Array.isArray(messageState.messageImages.images)) { // Image not found in the state, we need to add it newImage = { ...newImage, status: 'loaded', originalURL: inputImage.url, url: inputImage.url, }; messageState.messageImages.images.push(newImage); } messageState.messageImages.showRemoteImages = true; loadImages([image ? image : newImage], messageState.messageDocument?.document); loadBackgroundImages({ document: messageState.messageDocument?.document, images: [image ? image : newImage], }); } else { if (image) { image.error = 'No URL'; } else if (Array.isArray(messageState.messageImages.images)) { messageState.messageImages.images.push({ ...inputImage, error: 'No URL', status: 'loaded', }); } } } }); } }; export const EOAddReply = (state: Draft<EOState>, { payload: reply }: PayloadAction<EOMessageReply>) => { const message = getEOMessage(state); if (message) { message.Replies.push(reply); } };
4,085
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/eo/eoSelectors.ts
import { createSelector } from 'reselect'; import { RootState } from './eoStore'; const eoState = (state: RootState) => state.eo; export const eoTokenSelector = createSelector(eoState, (state) => state.encryptedToken); export const eoDecryptedTokenSelector = createSelector(eoState, (state) => state.decryptedToken); export const eoMessageSelector = createSelector(eoState, (state) => state.message); export const isStoreInitializedSelector = createSelector(eoState, (state) => state.isStoreInitialized); export const passwordSelector = createSelector(eoState, (state) => state.password); export const eoMessageStateSelector = createSelector(eoState, (state) => state.messageState);
4,086
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/eo/eoSlice.ts
import { createSlice } from '@reduxjs/toolkit'; import { globalReset } from '../actions'; import { EOAddReply, EODocumentInitializeFulfilled, EODocumentInitializePending, EOLoadEmbedded, EOLoadRemote, init, loadEOMessage, loadEOToken, } from './eoActions'; import { EOAddReply as EOAddReplyReducer, EODocumentInitializeFulfilled as EODocumentInitializeFulfilledReducer, EODocumentInitializePending as EODocumentInitializePendingReducer, EOLoadEmbeddedFulfilled, EOLoadRemote as EOLoadRemoteReducer, reset as globalResetReducer, initFulfilled, loadEOMessageFulfilled, loadEOTokenFulfilled, } from './eoReducers'; import { EOState } from './eoType'; export const initialState = { encryptedToken: '', decryptedToken: '', isStoreInitialized: false, password: '', } as EOState; export const eoSlice = createSlice({ name: 'eo', initialState, reducers: {}, extraReducers: (builder) => { builder.addCase(globalReset, globalResetReducer); builder.addCase(init.fulfilled, initFulfilled); builder.addCase(loadEOToken.fulfilled, loadEOTokenFulfilled); builder.addCase(loadEOMessage.fulfilled, loadEOMessageFulfilled); builder.addCase(EODocumentInitializePending, EODocumentInitializePendingReducer); builder.addCase(EODocumentInitializeFulfilled, EODocumentInitializeFulfilledReducer); builder.addCase(EOLoadEmbedded.fulfilled, EOLoadEmbeddedFulfilled); builder.addCase(EOLoadRemote, EOLoadRemoteReducer); builder.addCase(EOAddReply, EOAddReplyReducer); }, }); export default eoSlice.reducer;
4,087
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/eo/eoStore.ts
import { configureStore } from '@reduxjs/toolkit'; import elements from '../elements/elementsSlice'; import eo from './eoSlice'; export const store = configureStore({ reducer: { eo, elements, }, middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: { ignoreState: true, // Ignore these field paths in all actions ignoredActionPaths: ['payload', 'meta'], }, }), }); // Infer the `RootState` and `AppDispatch` types from the store itself export type RootState = ReturnType<typeof store.getState>;
4,088
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/eo/eoType.ts
import { PublicKeyReference } from '@proton/crypto'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Api, Recipient } from '@proton/shared/lib/interfaces'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { DecryptMessageResult } from '../../helpers/message/messageDecrypt'; import { Preparation } from '../../helpers/transforms/transforms'; import { MessageErrors, MessageImages, MessageRemoteImage, MessageState, MessageVerification, } from '../messages/messagesTypes'; export interface EOInitResult { token: string | undefined; decryptedToken: string | undefined; password: string | undefined; } export interface EOInitParams { get: (key: string) => any; } export interface EOMessageParams { api: Api; token: string; id: string; password: string; set: (key: string, data: any) => void; } export interface EOTokenParams { api: Api; id: string; set: (key: string, data: any) => void; } export interface EOMessageReply { Attachments: Attachment[]; Body: any; DecryptedBody?: any; Time: number; } export interface EOLoadEmbeddedParams { attachments: Attachment[]; api: Api; messageVerification?: MessageVerification; password: string; id: string; decryptedToken: string; } export type EOLoadEmbeddedResults = { attachment: Attachment; blob: string }[]; export interface EOLoadRemoteParams { imagesToLoad: MessageRemoteImage[]; } export interface EOLoadRemoteResults { image: MessageRemoteImage; blob?: Blob; tracker?: string; error?: unknown; } export interface EODocumentInitializeParams { dataChanges: Partial<Message>; initialized?: boolean; preparation?: Preparation; decryption?: DecryptMessageResult; errors?: MessageErrors; messageImages?: MessageImages; } export type EOMessage = { Attachments: Attachment[]; Body: any; ToList: Recipient[]; CCList: Recipient[]; ExpirationTime: number; Subject: string; Sender: Recipient; Recipient: string; Time: number; NumAttachments: number; Replies: EOMessageReply[]; SenderName: string; SenderAddress: string; MIMEType: MIME_TYPES; PublicKey?: PublicKeyReference[]; }; export type EOState = { message: EOMessage; encryptedToken: string; decryptedToken: string; isStoreInitialized: boolean; password: string; messageState: MessageState; };
4,089
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/incomingDefaults/incomingDefaultsActions.ts
import { createAction, createAsyncThunk } from '@reduxjs/toolkit'; import { addIncomingDefault, deleteIncomingDefaults, getIncomingDefaults, } from '@proton/shared/lib/api/incomingDefaults'; import { INCOMING_DEFAULTS_LOCATION } from '@proton/shared/lib/constants'; import { IncomingDefault } from '@proton/shared/lib/interfaces'; import { IncomingDefaultEvent } from '../../models/event'; import { AppThunkExtra } from '../store'; import { IncomingDefaultsState } from './incomingDefaultsTypes'; type LoadResults = Pick<IncomingDefaultsState, 'list'>; interface ApiResult { IncomingDefaults: IncomingDefault[]; Total: number; GlobalTotal: number; } const LOAD_BY_CHUNKS_SIZE = 100; export const load = createAsyncThunk<LoadResults, undefined, AppThunkExtra>( 'incomingDefaults/load', async (_, thunkApi) => { const list: IncomingDefault[] = []; let count = 0; let page = 0; const api = thunkApi.extra.api; do { try { const result = await api<ApiResult>( getIncomingDefaults({ Page: page, PageSize: LOAD_BY_CHUNKS_SIZE, // Load only the blocked ones for perf reasons Location: INCOMING_DEFAULTS_LOCATION.BLOCKED, }) ); list.push(...result.IncomingDefaults); count = result.Total; page += 1; } catch (error: any | undefined) { console.error(error); throw error; } } while (count > list.length); return { list, count, }; } ); export const event = createAction<IncomingDefaultEvent>('incomingDefaults/event'); interface AddBlockAddressesParams { addresses: string[]; overwrite?: boolean; } export const addBlockAddresses = createAsyncThunk<IncomingDefault[], AddBlockAddressesParams, AppThunkExtra>( 'incomingDefaults/addBlockAddresses', async ({ addresses, overwrite }, thunkApi) => { const promises = addresses.map((address) => { return thunkApi.extra.api<{ IncomingDefault: IncomingDefault }>( addIncomingDefault({ Email: address, Location: INCOMING_DEFAULTS_LOCATION.BLOCKED, Overwrite: overwrite, }) ); }); let incomingDefaults: IncomingDefault[] = []; const results = await Promise.all(promises); incomingDefaults = results.map((result) => result.IncomingDefault); return incomingDefaults; } ); export const remove = createAsyncThunk< { ID: string }[], { ID: string; }, AppThunkExtra >('incomingDefaults/remove', async ({ ID }, thunkApi) => { const result = await thunkApi.extra.api<{ Responses: { ID: string }[] }>(deleteIncomingDefaults([ID])); return result.Responses; });
4,090
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/incomingDefaults/incomingDefaultsReducer.ts
import { PayloadAction } from '@reduxjs/toolkit'; import { Draft } from 'immer/dist/internal'; import { EVENT_ACTIONS } from '@proton/shared/lib/constants'; import { IncomingDefault } from '@proton/shared/lib/interfaces'; import { IncomingDefaultEvent } from '../../models/event'; import { IncomingDefaultsState } from './incomingDefaultsTypes'; export const loadFulfilled = ( state: Draft<IncomingDefaultsState>, action: PayloadAction<Pick<IncomingDefaultsState, 'list'>> ) => { state.list = action.payload.list; state.status = 'loaded'; }; export const loadRejected = (state: Draft<IncomingDefaultsState>) => { state.list = []; state.status = 'rejected'; }; export const loadPending = (state: Draft<IncomingDefaultsState>) => { state.list = []; state.status = 'pending'; }; export const event = (state: Draft<IncomingDefaultsState>, action: PayloadAction<IncomingDefaultEvent>) => { const { Action, IncomingDefault } = action.payload; if (!IncomingDefault?.ID) { return state; } if (Action === EVENT_ACTIONS.DELETE) { state.list = state.list.filter((item) => item.ID !== IncomingDefault.ID); } if (Action === EVENT_ACTIONS.UPDATE) { const itemIndex = state.list.findIndex((item) => item.ID === IncomingDefault.ID); if (itemIndex !== -1) { const createdAt = state.list[itemIndex].Time; const updatedAt = IncomingDefault.Time; if (updatedAt > createdAt) { state.list[itemIndex] = { ...IncomingDefault }; } } } if (Action === EVENT_ACTIONS.CREATE) { const itemIndex = state.list.findIndex((item) => item.ID === IncomingDefault.ID); if (itemIndex === -1) { state.list.push({ ...IncomingDefault }); return; } const createdAt = state.list[itemIndex].Time; const updatedAt = IncomingDefault.Time; if (updatedAt > createdAt) { state.list[itemIndex] = { ...IncomingDefault }; } } }; export const blockAddressesFullfilled = ( state: Draft<IncomingDefaultsState>, action: PayloadAction<IncomingDefault[]> ) => { action.payload.forEach((incomingDefault) => { const itemIndex = state.list.findIndex((item) => item.ID === incomingDefault.ID); if (itemIndex !== -1) { state.list[itemIndex] = incomingDefault; } else { state.list.push(incomingDefault); } }); }; export const removeFullfilled = (state: Draft<IncomingDefaultsState>, action: PayloadAction<{ ID: string }[]>) => { const removedIDs = action.payload.map(({ ID }) => ID); state.list = state.list.filter((item) => !removedIDs.includes(item.ID)); };
4,091
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/incomingDefaults/incomingDefaultsSelectors.ts
import { createSelector } from 'reselect'; import { INCOMING_DEFAULTS_LOCATION } from '@proton/shared/lib/constants'; import { RootState } from '../store'; const incomingDefaults = (state: RootState) => state.incomingDefaults; const incomingDefaultLocation = (_: RootState, location: INCOMING_DEFAULTS_LOCATION) => location; export const getIncomingDefaultsList = createSelector([incomingDefaults], (incomingDefaults) => incomingDefaults.list); export const getIncomingDefaultsAddresses = createSelector([getIncomingDefaultsList], (incomingDefaultsList) => incomingDefaultsList.filter((item) => !!item.Email) ); export const getIncomingDefaultStatus = createSelector( [incomingDefaults], (incomingDefaults) => incomingDefaults.status ); export const getIncomingDefaultsByLocation = createSelector( [incomingDefaults, incomingDefaultLocation], (incomingDefaults, location) => incomingDefaults.list.filter((item) => item.Location === location) );
4,092
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/incomingDefaults/incomingDefaultsSlice.ts
import { createSlice } from '@reduxjs/toolkit'; import * as actions from './incomingDefaultsActions'; import * as reducer from './incomingDefaultsReducer'; import { IncomingDefaultsState } from './incomingDefaultsTypes'; const incomingDefaultsSlice = createSlice({ name: 'incomingDefaults', initialState: { list: [], status: 'not-loaded', } as IncomingDefaultsState, reducers: {}, extraReducers: (builder) => { builder.addCase(actions.load.pending, reducer.loadPending); builder.addCase(actions.load.fulfilled, reducer.loadFulfilled); builder.addCase(actions.load.rejected, reducer.loadRejected); builder.addCase(actions.event, reducer.event); builder.addCase(actions.addBlockAddresses.fulfilled, reducer.blockAddressesFullfilled); builder.addCase(actions.remove.fulfilled, reducer.removeFullfilled); }, }); export default incomingDefaultsSlice.reducer;
4,093
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/incomingDefaults/incomingDefaultsTypes.ts
import { IncomingDefault, IncomingDefaultStatus } from '@proton/shared/lib/interfaces'; export interface IncomingDefaultsState { list: IncomingDefault[]; status: IncomingDefaultStatus; }
4,094
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/layout/layoutSlice.ts
import { PayloadAction, createSlice } from '@reduxjs/toolkit'; interface LayoutState { sidebarExpanded: boolean; } const initialState: LayoutState = { /** * Used on narrow devices when burger menu allows to toggle sidebar */ sidebarExpanded: false, }; const layoutSlice = createSlice({ name: 'layout', initialState, reducers: { setSidebarExpanded: (state, action: PayloadAction<boolean>) => { state.sidebarExpanded = action.payload; }, toggleSidebarExpand: (state) => { state.sidebarExpanded = !state.sidebarExpanded; }, }, }); export const layoutActions = layoutSlice.actions; export default layoutSlice.reducer;
4,095
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/layout/layoutSliceSelectors.ts
import { createSelector } from 'reselect'; import { RootState } from '../store'; const layout = (state: RootState) => state.layout; export const selectLayoutIsExpanded = createSelector([layout], (layout) => layout.sidebarExpanded);
4,096
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/messages/messagesSelectors.ts
import { createSelector } from 'reselect'; import { DRAFT_ID_PREFIX } from '@proton/shared/lib/mail/messages'; import { RootState } from '../store'; const messages = (state: RootState) => state.messages; const currentID = (_: RootState, { ID }: { ID: string }) => ID; export const localID = createSelector([messages, currentID], (messages, currentID) => { const localID = [...Object.keys(messages)] .filter((key) => key?.startsWith(DRAFT_ID_PREFIX)) .find((key) => messages[key]?.data?.ID === currentID); return localID || currentID; }); export const messageByID = createSelector([messages, localID], (messages, localID) => messages[localID]); export const allMessages = createSelector([messages], (messages) => { return Object.values(messages); });
4,097
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/messages/messagesSlice.ts
import { createSlice } from '@reduxjs/toolkit'; import { globalReset } from '../actions'; import { load as loadElements } from '../elements/elementsActions'; import * as draftAction from './draft/messagesDraftActions'; import * as draftReducer from './draft/messagesDraftReducers'; import * as expireAction from './expire/messagesExpireActions'; import * as expireReducer from './expire/messagesExpireReducers'; import { updateFromElements } from './helpers/messagesReducer'; import * as msgImageAction from './images/messagesImagesActions'; import * as msgImageReducer from './images/messagesImagesReducers'; import { MessagesState } from './messagesTypes'; import * as msgOptimisticAction from './optimistic/messagesOptimisticActions'; import * as msgOptimisticReducer from './optimistic/messagesOptimisticReducers'; import * as msgReadAction from './read/messagesReadActions'; import * as msgReadReducer from './read/messagesReadReducers'; import * as scheduledAction from './scheduled/scheduledActions'; import * as scheduledReducer from './scheduled/scheduledReducers'; const messagesSlice = createSlice({ name: 'messages', initialState: {} as MessagesState, reducers: {}, extraReducers: (builder) => { builder.addCase(globalReset, msgReadReducer.reset); builder.addCase(msgReadAction.initialize, msgReadReducer.initialize); builder.addCase(msgReadAction.reload, msgReadReducer.reload); builder.addCase(msgReadAction.errors, msgReadReducer.errors); builder.addCase(msgReadAction.event, msgReadReducer.event); builder.addCase(msgReadAction.load.fulfilled, msgReadReducer.loadFulfilled); builder.addCase(msgReadAction.load.rejected, msgReadReducer.loadRejected); builder.addCase(msgReadAction.verificationComplete, msgReadReducer.verificationComplete); builder.addCase(msgReadAction.resign, msgReadReducer.resign); builder.addCase(msgReadAction.resetVerification, msgReadReducer.resetVerification); builder.addCase(msgReadAction.applyDarkStyle, msgReadReducer.applyDarkStyle); builder.addCase(msgReadAction.removeDarkStyle, msgReadReducer.removeDarkStyle); builder.addCase(msgReadAction.documentInitializePending, msgReadReducer.documentInitializePending); builder.addCase(msgReadAction.documentInitializeFulfilled, msgReadReducer.documentInitializeFulfilled); builder.addCase(msgReadAction.cleanUTMTrackers, msgReadReducer.cleanUTMTrackers); builder.addCase(msgImageAction.loadEmbedded.fulfilled, msgImageReducer.loadEmbeddedFulfilled); builder.addCase(msgImageAction.loadRemoteProxy.pending, msgImageReducer.loadRemotePending); builder.addCase(msgImageAction.loadRemoteProxy.fulfilled, msgImageReducer.loadRemoteProxyFulFilled); builder.addCase(msgImageAction.loadFakeProxy.pending, msgImageReducer.loadFakeProxyPending); builder.addCase(msgImageAction.loadFakeProxy.fulfilled, msgImageReducer.loadFakeProxyFulFilled); builder.addCase(msgImageAction.loadRemoteProxyFromURL, msgImageReducer.loadRemoteProxyFromURL); builder.addCase(msgImageAction.loadRemoteDirectFromURL, msgImageReducer.loadRemoteDirectFromURL); builder.addCase(msgImageAction.failedRemoteDirectLoading, msgImageReducer.failedRemoteDirectLoading); builder.addCase(msgImageAction.loadFakeTrackers, msgImageReducer.loadFakeTrackers); builder.addCase(msgOptimisticAction.optimisticApplyLabels, msgOptimisticReducer.optimisticApplyLabels); builder.addCase(msgOptimisticAction.optimisticMarkAs, msgOptimisticReducer.optimisticMarkAs); builder.addCase(msgOptimisticAction.optimisticDelete, msgOptimisticReducer.optimisticDelete); builder.addCase(msgOptimisticAction.optimisticEmptyLabel, msgOptimisticReducer.optimisticEmptyLabel); builder.addCase(msgOptimisticAction.optimisticRestore, msgOptimisticReducer.optimisticRestore); builder.addCase(draftAction.createDraft, draftReducer.createDraft); builder.addCase(draftAction.openDraft, draftReducer.openDraft); builder.addCase(draftAction.removeInitialAttachments, draftReducer.removeInitialAttachments); builder.addCase(draftAction.removeQuickReplyFlag, draftReducer.removeQuickReplyFlag); builder.addCase(draftAction.removeAllQuickReplyFlags, draftReducer.removeAllQuickReplyFlags); builder.addCase(draftAction.updateIsSavingFlag, draftReducer.updateIsSavingFlag); builder.addCase(draftAction.updateDraftContent, draftReducer.updateDraftContent); builder.addCase(draftAction.draftSaved, draftReducer.draftSaved); builder.addCase(draftAction.updateExpires, draftReducer.updateExpires); builder.addCase(draftAction.startSending, draftReducer.startSending); builder.addCase(draftAction.sendModifications, draftReducer.sendModifications); builder.addCase(draftAction.endUndo, draftReducer.endUndo); builder.addCase(draftAction.sent, draftReducer.sent); builder.addCase(draftAction.endSending, draftReducer.endSending); builder.addCase(draftAction.deleteDraft, draftReducer.deleteDraft); builder.addCase(draftAction.cancelSendMessage.fulfilled, draftReducer.cancelSendSuccess); builder.addCase(expireAction.expireMessages.pending, expireReducer.expirePending); builder.addCase(expireAction.expireMessages.fulfilled, expireReducer.expireFullfilled); builder.addCase(expireAction.expireMessages.rejected, expireReducer.expireRejected); builder.addCase(scheduledAction.updateScheduled, scheduledReducer.updateScheduled); builder.addCase(scheduledAction.cancelScheduled, scheduledReducer.cancelScheduled); builder.addCase(loadElements.fulfilled, updateFromElements); }, }); // Export the reducer, either as a default or named export export default messagesSlice.reducer;
4,098
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/logic/messages/messagesTypes.ts
import type { PrivateKeyReference, PublicKeyReference, WorkerDecryptionResult } from '@proton/crypto'; import { Api, KeyTransparencyVerificationResult, RequireSome, SimpleMap } from '@proton/shared/lib/interfaces'; import { VerificationPreferences } from '@proton/shared/lib/interfaces/VerificationPreferences'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers'; import { MESSAGE_ACTIONS } from '../../constants'; import { DecryptMessageResult } from '../../helpers/message/messageDecrypt'; import { Preparation } from '../../helpers/transforms/transforms'; export interface OutsideKey { type: 'outside'; password: string; id: string; decryptedToken: string; } export interface PublicPrivateKey { type: 'publicPrivate'; publicKeys: PublicKeyReference[]; privateKeys: PrivateKeyReference[]; } export type MessageKeys = PublicPrivateKey | OutsideKey; export interface MessageErrors { network?: Error[]; decryption?: Error[]; processing?: Error[]; signature?: Error[]; unknown?: Error[]; } export interface MessageWithOptionalBody extends Omit<Message, 'Body'> { Body?: string; } /** * Data structure containing all the needed informations about the signature verification of a message */ export interface MessageVerification { /** * Signatures verification status flag */ verificationStatus: VERIFICATION_STATUS | undefined; /** * Signature verification errors, if any */ verificationErrors: Error[] | undefined; /** * Pinned public keys of the sender which can verify, if any */ senderPinnedKeys: PublicKeyReference[] | undefined; /** * Sender public keys retrieved from API which can are not pinned */ senderPinnableKeys: PublicKeyReference[] | undefined; /** * If the sender is in the list of contacts, whether its contact signature has been verified */ pinnedKeysVerified: boolean | undefined; /** * If the message is signed, the public key that verifies the signature */ signingPublicKey: PublicKeyReference | undefined; /** * Attached public key, if the message contains any */ attachedPublicKeys: PublicKeyReference[] | undefined; /** * Whether the signingPublicKey is part of the pinned key keys list */ signingPublicKeyIsPinned: boolean | undefined; /** * Whether the signingPublicKey is marked as compromised by the sender */ signingPublicKeyIsCompromised: boolean | undefined; /** * Key transparency verification status */ ktVerificationResult: KeyTransparencyVerificationResult | undefined; /** * Errors occuring while retrieving public keys */ apiKeysErrors: string[] | undefined; /** * Verifying keys, if any */ verifyingKeys: PublicKeyReference[] | undefined; } export interface AbstractMessageImage { type: 'remote' | 'embedded'; original?: HTMLElement; url?: string; id: string; status: 'not-loaded' | 'loading' | 'loaded'; tracker: string | undefined; error?: any; } export interface MessageRemoteImage extends AbstractMessageImage { type: 'remote'; originalURL?: string; } export interface MessageEmbeddedImage extends AbstractMessageImage { type: 'embedded'; cid: string; cloc: string; attachment: Attachment; } export type MessageImage = MessageRemoteImage | MessageEmbeddedImage; export interface MessageImages { hasRemoteImages: boolean; hasEmbeddedImages: boolean; showRemoteImages: boolean; showEmbeddedImages: boolean; trackersStatus: 'not-loaded' | 'loading' | 'loaded'; images: MessageImage[]; } export interface MessageDecryption { /** * Decrypted message body content */ decryptedBody?: string; /** * Decrypted raw content * Often the same as decryptedBody except for pgp-mime format, used for signature verification */ decryptedRawContent?: Uint8Array; /** * Message signature obtained after decryption, if any * Warning, there could also be a signature in the mime content which is different */ signature?: Uint8Array; /** * Decrypted subject * Only used in rare situations where the message is sent by an external system which encrypt even the subject */ decryptedSubject?: string; } export interface MessageDocument { /** * Document representing the message body * Processed to be rendered to the user */ document?: Element; /** * Mail content when in plaintext mode */ plainText?: string; /** * Initialization status of the message * undefined: not started * false: in progress * true: done */ initialized?: boolean; /** * True if dark style injected in message content */ hasDarkStyle?: boolean; /** * User choice to not apply dark style */ noDarkStyle?: boolean; } export interface MessageDraftFlags { /** * Date of expiration of the message */ expiresIn?: Date; /** * Original "To" address of the referring message. Only added for drafts. */ originalTo?: string; /** * Original "From" address of the referring message. It is used to reply with an alias address. Only added for drafts. */ originalFrom?: string; /** * Original "AddressID" of the address of the referring message. Only added for drafts. * Used on rare situation when replying with a different address than the one you received the message. */ originalAddressID?: string; /** * Original "Flags" of the referring message. * Needed to know e.g. whether the draft was created (when repling/forwarding) from an autoforwarded message. * This is relevant for attachment decryption as part of initial draft creation, since with E2EE forwardings * the attachments key packets need to be decrypted using the forwardee key. And using such a key for decryption * is generally disallowed. */ originalMessageFlags?: number; /** * Action flags for draft messages */ action?: MESSAGE_ACTIONS; /** * Action flags for draft messages */ ParentID?: string; /** * Override auto save contacts preference */ autoSaveContacts?: number; /** * true when sending message */ sending?: boolean; /** * Attachments prepared during the creation of a draft to upload * when the draft will be created */ initialAttachments?: File[]; /** * Desired time for schedule send (timestamp) */ scheduledAt?: number; /** * Flag meaning we are reopening the draft from an undo action */ openDraftFromUndo?: boolean; /** * Flag for draft that has already been sent */ isSentDraft?: boolean; /** * Flag to know whether the draft has been created in a quick reply */ isQuickReply?: boolean; /** * Flag to know whether the quick reply draft is being saved or not */ isSaving?: boolean; } export interface MessageState { /** * ID used only on the frontend * Needed to keep a unique id on a message even if it's created in session without a server ID */ localID: string; /** * Message object from the server */ data?: MessageWithOptionalBody; /** * All decryption data */ decryption?: MessageDecryption; /** * Message document either html or plaintext */ messageDocument?: MessageDocument; /** * Signature verifications results */ verification?: MessageVerification; /** * All data relative to remote and embedded images present in the message */ messageImages?: MessageImages; /** * All data relative to links containing UTM trackers in the message */ messageUTMTrackers?: MessageUTMTracker[]; /** * Drafts specifics flags */ draftFlags?: MessageDraftFlags; /** * Counter of load retry */ loadRetry?: number; /** * All kind of errors that appears during message processing */ errors?: MessageErrors; } export interface MessageStateWithFullMessage extends Omit<MessageState, 'data'> { data?: Message; } export type MessagesState = SimpleMap<MessageState>; /** * Common helper to have a MessageExtended with the data props required */ export type MessageStateWithData = RequireSome<MessageState, 'data'>; export type MessageStateWithDataFull = RequireSome<MessageStateWithFullMessage, 'data'>; /** * Common helper to have a partial MessageExtended including a Partial Message */ export type PartialMessageState = Partial<Omit<MessageState, 'data'> & { data: Partial<MessageWithOptionalBody> }>; export interface LoadParams { ID: string; } export interface DocumentInitializeParams { ID: string; dataChanges: Partial<MessageWithOptionalBody>; initialized?: boolean; preparation?: Preparation; decryption?: DecryptMessageResult; errors?: MessageErrors; messageImages?: MessageImages; } export interface VerificationParams { ID: string; verificationPreferences?: VerificationPreferences; verification?: { verified: VERIFICATION_STATUS; signature?: Uint8Array; verificationErrors?: Error[]; }; signingPublicKey?: PublicKeyReference; attachedPublicKeys?: PublicKeyReference[]; errors?: MessageErrors; } export interface LoadEmbeddedParams { ID: string; attachments: Attachment[]; api: Api; messageVerification?: MessageVerification; messageKeys: MessageKeys; getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined; onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void; messageFlags: number; } export type LoadEmbeddedResults = { attachment: Attachment; blob: string }[]; export interface LoadRemoteParams { ID: string; imageToLoad: MessageRemoteImage; api: Api; } export interface LoadRemoteFromURLParams { ID: string; imagesToLoad: MessageRemoteImage[]; uid?: string; } export interface LoadRemoteResults { image: MessageRemoteImage; blob?: Blob; tracker?: string; error?: unknown; } export interface LoadFakeRemoteParams { ID: string; imagesToLoad: MessageRemoteImage[]; api: Api; /** * Used when fake loading images for the first time */ firstLoad?: boolean; }
4,099