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/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/send/sendEncrypt.ts
import { CryptoProxy, PublicKeyReference, SessionKey } from '@proton/crypto'; import { AES256, MIME_TYPES } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { Package, Packages } from '@proton/shared/lib/interfaces/mail/crypto'; import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import { getAttachments } from '@proton/shared/lib/mail/messages'; import { getSessionKey } from '@proton/shared/lib/mail/send/attachments'; import isTruthy from '@proton/utils/isTruthy'; import { MessageState, PublicPrivateKey } from '../../logic/messages/messagesTypes'; import { arrayToBase64 } from '../base64'; const MEGABYTE = 1024 * 1024; // Reference: Angular/src/app/composer/services/encryptPackages.js interface AttachmentKeys { Attachment: Attachment; SessionKey: SessionKey; } const { SEND_CLEAR, SEND_EO, SEND_CLEAR_MIME } = PACKAGE_TYPE; const packToBase64 = ({ data, algorithm: Algorithm = AES256 }: SessionKey) => { return { Key: arrayToBase64(data), Algorithm }; }; const encryptKeyPacket = async ({ sessionKeys = [], publicKeys = [], passwords = [], }: { sessionKeys?: SessionKey[]; publicKeys?: PublicKeyReference[]; passwords?: string[]; }) => Promise.all( sessionKeys.map(async (sessionKey) => { const encryptedSessionKey = await CryptoProxy.encryptSessionKey({ data: sessionKey.data, algorithm: sessionKey.algorithm, encryptionKeys: publicKeys, passwords, format: 'binary', }); return arrayToBase64(encryptedSessionKey); }) ); /** * Encrypt the attachment session keys and add them to the package */ const encryptAttachmentKeys = async (pack: Package, message: MessageState, attachmentKeys: AttachmentKeys[]) => { // multipart/mixed bodies already include the attachments so we don't add them here if (pack.MIMEType === MIME_TYPES.MIME) { return; } const promises = Object.values(pack.Addresses || {}).map(async (address) => { const isEo = hasBit(address.Type, PACKAGE_TYPE.SEND_EO); if (!(isEo || address.PublicKey)) { return; } const keys = await encryptKeyPacket({ sessionKeys: attachmentKeys.map(({ SessionKey }) => SessionKey), passwords: isEo ? [message.data?.Password || ''] : undefined, publicKeys: isEo ? undefined : [address.PublicKey as PublicKeyReference], }); const AttachmentKeyPackets: { [AttachmentID: string]: string } = {}; attachmentKeys.forEach(({ Attachment }, i) => { AttachmentKeyPackets[Attachment.ID || ''] = keys[i]; }); address.AttachmentKeyPackets = AttachmentKeyPackets; }); if (hasBit(pack.Type, PACKAGE_TYPE.SEND_CLEAR)) { const AttachmentKeys: { [AttachmentID: string]: { Key: string; Algorithm: string } } = {}; attachmentKeys.forEach(({ Attachment, SessionKey }) => { AttachmentKeys[Attachment.ID || ''] = packToBase64(SessionKey); }); pack.AttachmentKeys = AttachmentKeys; } return Promise.all(promises); }; /** * Generate random session key in the format openpgp creates them */ const generateSessionKeyHelper = async (): Promise<SessionKey> => ({ algorithm: AES256, data: await CryptoProxy.generateSessionKeyForAlgorithm(AES256), }); /** * Encrypt the body in the given package. Should only be used if the package body differs from message body * (i.e. the draft body) */ const encryptBodyPackage = async ( pack: Package, messageKeys: PublicPrivateKey, publicKeys: (PublicKeyReference | undefined)[], message: MessageState, scheduledTime?: number ) => { const cleanPublicKeys = publicKeys.filter(isTruthy); // Always encrypt with a single private key const privateKeys = messageKeys.privateKeys.slice(0, 1); const containsEmbeddedAttachments = pack.MIMEType === MIME_TYPES.MIME && getAttachments(message.data).length > 0; // NB: `Message.NumAttachments` is a server-controlled value, so we cannot rely on it here // We enable compression for MIME messages that include attachments to reduce the size of the inlined base64 attachment data, // when the body is larger than 1MB. This is also to avoid enabling compression when the attached data is just the sender's public key, // since its value is constant and known to the server, hence compressing it won't necessarily limit compression-based information leakage. const shouldCompress = containsEmbeddedAttachments && pack.Body!.length > MEGABYTE; const sessionKey = cleanPublicKeys.length ? await CryptoProxy.generateSessionKey({ recipientKeys: cleanPublicKeys }) : await generateSessionKeyHelper(); const data = pack.Body || ''; const dataType = data instanceof Uint8Array ? 'binaryData' : 'textData'; // we encrypt using `sessionKey` directly instead of `encryptionKeys` so that returned message only includes // symmetrically encrypted data const { message: encryptedData } = await CryptoProxy.encryptMessage({ [dataType]: data, sessionKey, signingKeys: privateKeys, date: scheduledTime ? new Date(scheduledTime) : undefined, format: 'binary', compress: shouldCompress, }); // encrypt to each public key separetely to get separate serialized session keys const encryptedSessionKeys = await Promise.all( cleanPublicKeys.map((publicKey) => CryptoProxy.encryptSessionKey({ ...sessionKey, encryptionKeys: publicKey, format: 'binary', }) ) ); return { keys: encryptedSessionKeys, encrypted: encryptedData, sessionKey }; }; /** * Encrypts the draft body. This is done separately from the other bodies so we can make sure that the send body * (the encrypted body in the message object) is the same as the other emails so we can use 1 blob for them in the api * (i.e. deduplication) */ const encryptDraftBodyPackage = async ( pack: Package, messageKeys: PublicPrivateKey, publicKeys: (PublicKeyReference | undefined)[], scheduledTime?: number ) => { const cleanPublicAndMessageKeys = [...messageKeys.publicKeys, ...publicKeys].filter(isTruthy); const cleanPublicKeys = publicKeys.filter(isTruthy); // Always encrypt with a single private key const privateKeys = messageKeys.privateKeys.slice(0, 1); // pass both messageKeys and publicKeys to make sure the generated session key is compatible with them all const sessionKey = await CryptoProxy.generateSessionKey({ recipientKeys: cleanPublicAndMessageKeys }); const data = pack.Body || ''; const dataType = data instanceof Uint8Array ? 'binaryData' : 'textData'; // we encrypt using `sessionKey` directly instead of `encryptionKeys` so that returned message only includes // symmetrically encrypted data const { message: encryptedData } = await CryptoProxy.encryptMessage({ [dataType]: data, sessionKey, signingKeys: privateKeys, date: scheduledTime ? new Date(scheduledTime) : undefined, format: 'binary', }); // Encrypt to each recipient's public key separetely to get separate serialized session keys. const encryptedSessionKeys = await Promise.all( cleanPublicKeys.map((publicKey) => CryptoProxy.encryptSessionKey({ ...sessionKey, encryptionKeys: publicKey, format: 'binary', }) ) ); return { keys: encryptedSessionKeys, encrypted: encryptedData, sessionKey }; }; /** * Encrypts the body of the package and then overwrites the body in the package and adds the encrypted session keys * to the subpackages. If we send clear message the unencrypted session key is added to the (top-level) package too. */ const encryptBody = async (pack: Package, messageKeys: PublicPrivateKey, message: MessageState): Promise<void> => { const addressKeys = Object.keys(pack.Addresses || {}); const addresses = Object.values(pack.Addresses || {}); const publicKeysList = addresses.map(({ PublicKey }) => PublicKey); const scheduledTime = message.draftFlags?.scheduledAt ? message.draftFlags?.scheduledAt * 1000 : undefined; /* * Special case: reuse the encryption packet from the draft, this allows us to do deduplication on the back-end. * In fact, this will be the most common case. */ const { keys, encrypted, sessionKey } = message.data?.MIMEType === pack.MIMEType ? await encryptDraftBodyPackage(pack, messageKeys, publicKeysList, scheduledTime) : await encryptBodyPackage(pack, messageKeys, publicKeysList, message, scheduledTime); let counter = 0; publicKeysList.forEach((publicKey, index) => { if (!publicKey) { return; } const key = keys[counter++]; (pack.Addresses || {})[addressKeys[index]].BodyKeyPacket = arrayToBase64(key); }); await Promise.all( addresses.map(async (subPack) => { if (subPack.Type !== SEND_EO) { return; } const [BodyKeyPacket] = await encryptKeyPacket({ sessionKeys: [sessionKey], passwords: [message.data?.Password || ''], }); // eslint-disable-next-line require-atomic-updates subPack.BodyKeyPacket = BodyKeyPacket; }) ); if ((pack.Type || 0) & (SEND_CLEAR | SEND_CLEAR_MIME)) { // eslint-disable-next-line require-atomic-updates pack.BodyKey = packToBase64(sessionKey); } pack.Body = encrypted; }; const encryptPackage = async ( pack: Package, message: MessageState, messageKeys: PublicPrivateKey, attachmentKeys: AttachmentKeys[] ): Promise<Package> => { await Promise.all([encryptBody(pack, messageKeys, message), encryptAttachmentKeys(pack, message, attachmentKeys)]); Object.values(pack.Addresses || {}).forEach((address: any) => delete address.PublicKey); return pack; }; const getAttachmentKeys = async (message: MessageState, messageKeys: PublicPrivateKey): Promise<AttachmentKeys[]> => Promise.all( getAttachments(message.data).map(async (attachment) => ({ Attachment: attachment, SessionKey: await getSessionKey(attachment, messageKeys.privateKeys), })) ); /** * Encrypts the packages and removes all temporary values that should not be send to the API */ export const encryptPackages = async ( message: MessageState, messageKeys: PublicPrivateKey, packages: Packages ): Promise<Packages> => { const attachmentKeys = await getAttachmentKeys(message, messageKeys); const packageList = Object.values(packages) as Package[]; await Promise.all(packageList.map((pack) => encryptPackage(pack, message, messageKeys, attachmentKeys))); return packages; };
3,900
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/send/sendFormatter.ts
import { differenceInSeconds } from 'date-fns'; import { sendMessageForm } from '@proton/shared/lib/api/messages'; import { Packages } from '@proton/shared/lib/interfaces/mail/crypto'; const serializeJsonToFormData = (payload: any, context: string, data: any) => { if (!data || typeof data === 'boolean' || typeof data === 'number' || typeof data === 'string') { payload[context] = data; } else if (data instanceof Uint8Array) { payload[context] = new Blob([data]); } else { Object.entries(data).forEach(([key, value]) => { serializeJsonToFormData(payload, `${context}[${key}]`, value); }); } }; interface Args { ID: string; packages: Packages; expiresIn?: Date; delaySendSeconds?: number; autoSaveContacts?: number; scheduledAt?: number; sendingFrom?: string; } export const sendFormatter = ({ ID, packages, expiresIn, delaySendSeconds, autoSaveContacts, scheduledAt, sendingFrom, }: Args) => { const payload: any = {}; serializeJsonToFormData(payload, `Packages`, packages); if (expiresIn) { payload.ExpiresIn = differenceInSeconds(expiresIn, new Date()); } if (delaySendSeconds) { payload.DelaySeconds = delaySendSeconds; } if (autoSaveContacts !== undefined) { payload.AutoSaveContacts = autoSaveContacts; } if (scheduledAt) { payload.DeliveryTime = scheduledAt; } return sendMessageForm(ID, payload, sendingFrom); };
3,901
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/send/sendMimeBuilder.ts
import mimemessage from '@protontech/mimemessage'; import { WorkerDecryptionResult } from '@proton/crypto'; import { arrayToBinaryString } from '@proton/crypto/lib/utils'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Api } from '@proton/shared/lib/interfaces'; import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants'; import { getAttachments, isPlainText as testIsPlainText } from '@proton/shared/lib/mail/messages'; import { MessageEmbeddedImage, MessageImages, MessageKeys, MessageState } from '../../logic/messages/messagesTypes'; import { Download, formatDownload } from '../attachment/attachmentDownloader'; import { getPlainText } from '../message/messageContent'; import { readContentIDandLocation } from '../message/messageEmbeddeds'; import { prepareExport } from '../message/messageExport'; // Reference: Angular/src/app/composer/services/mimeMessageBuilder.js /** * Remove '; name=' and '; filename=' values */ const extractContentValue = (value = '') => { const semicolonIndex = value.indexOf(';'); if (semicolonIndex === -1) { return value; } return value.substring(0, semicolonIndex); }; const getAttachmentsByType = (attachments: Download[], messageImages: MessageImages | undefined, inline: boolean) => attachments.filter((attachmentData) => { const { cid, cloc } = readContentIDandLocation(attachmentData.attachment); const image = messageImages?.images.find( (image) => (image as MessageEmbeddedImage).cid === cid || (image as MessageEmbeddedImage).cloc === cloc ); return !!image === inline; }); const getEnbeddedAttachments = (attachments: Download[], messageImages: MessageImages | undefined) => getAttachmentsByType(attachments, messageImages, true); const getNormalAttachments = (attachments: Download[], messageImages: MessageImages | undefined) => getAttachmentsByType(attachments, messageImages, false); const buildAttachments = (attachments: Download[]) => attachments.map(({ attachment, data }) => { const attachmentName = JSON.stringify(attachment.Name); const headers = attachment.Headers || {}; const contentTypeValue = extractContentValue(headers['content-type']) || attachment.MIMEType || 'application/octet-stream'; const contentDispositionValue = extractContentValue(headers['content-disposition']) || ATTACHMENT_DISPOSITION.ATTACHMENT; const entity = mimemessage.factory({ contentType: `${contentTypeValue}; filename=${attachmentName}; name=${attachmentName}`, contentTransferEncoding: 'base64', body: arrayToBinaryString(data), }); entity.header( 'content-disposition', `${contentDispositionValue}; filename=${attachmentName}; name=${attachmentName}` ); if (headers['content-id']) { entity.header('content-id', headers['content-id']); } return entity; }); const buildEmbeddedHtml = ( html: string | undefined, attachments: Download[], messageImages: MessageImages | undefined ) => { const htmlEntity = mimemessage.factory({ contentType: 'text/html;charset=utf-8', contentTransferEncoding: 'base64', body: html, }); // Attachments const inlineAttachments = getEnbeddedAttachments(attachments, messageImages); const attachmentEntities = buildAttachments(inlineAttachments); // add the attachments const relatedBody = [htmlEntity].concat(attachmentEntities); return mimemessage.factory({ contentType: 'multipart/related', body: relatedBody, }); }; /** * Quoted printable for compatibility with old clients * Mimemessagefactory doesn't handle the empty string well. */ const buildPlaintextEntity = (plaintext?: string) => mimemessage.factory({ body: plaintext, contentTransferEncoding: 'quoted-printable', }); /** * Build the multipart/alternate MIME entity containing both the HTML and plain text entities. */ const buildAlternateEntity = ( plaintext: string | undefined, html: string | undefined, attachments: Download[], messageImages: MessageImages | undefined ) => mimemessage.factory({ contentType: 'multipart/alternative', body: [buildPlaintextEntity(plaintext), buildEmbeddedHtml(html, attachments, messageImages)], }); /** * Builds a mime body given the plaintext, html source and a list of attachments to fetch embedded images from */ const buildBodyEntity = ( plaintext: string | undefined, html: string | undefined, attachments: Download[], messageImages: MessageImages | undefined ) => { if (html !== undefined && plaintext !== undefined) { return buildAlternateEntity(plaintext, html, attachments, messageImages); } return html !== undefined ? buildEmbeddedHtml(html, attachments, messageImages) : buildPlaintextEntity(plaintext); }; /** * Builds a multipart message from the given plaintext, html bodies and attachments. * The html body is not necessary to create a valid mime body */ const build = ( plaintext: string | undefined, html: string | undefined, attachments: Download[], messageImages: MessageImages | undefined ): string => { const bodyEntity = buildBodyEntity(plaintext, html, attachments, messageImages); const normalAttachments = getNormalAttachments(attachments, messageImages); const attachmentEntities = buildAttachments(normalAttachments); const body = [bodyEntity].concat(attachmentEntities); const msgentity = mimemessage.factory({ contentType: 'multipart/mixed', body, }); // this trailing line space is important: if it's not there Outlook adds it and breaks pgp/mime signatures. return `${msgentity.toString()}\r\n`; }; const fetchMimeDependencies = async ( message: MessageState, messageKeys: MessageKeys, getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined, onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void, api: Api ): Promise<Download[]> => { return Promise.all( getAttachments(message.data).map(async (attachment) => formatDownload( attachment, message.verification, messageKeys, onUpdateAttachment, api, getAttachment, message.data?.Flags ) ) ); }; export const constructMime = async ( message: MessageState, messageKeys: MessageKeys, getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined, onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void, api: Api, downconvert = true ) => { const plaintext = getPlainText(message, downconvert); const html = message.data?.MIMEType !== MIME_TYPES.PLAINTEXT ? prepareExport(message) : undefined; const attachments = await fetchMimeDependencies(message, messageKeys, getAttachment, onUpdateAttachment, api); return build(plaintext, html, attachments, message.messageImages); }; export const constructMimeFromSource = async ( message: MessageState, messageKeys: MessageKeys, getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined, onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void, api: Api ) => { const isDecryptionError = !!message.errors?.decryption?.length; let plaintext: string | undefined; let html: string | undefined; if (isDecryptionError) { plaintext = message.data?.Body; } else { const isPlainText = testIsPlainText(message.data); plaintext = isPlainText ? message.decryption?.decryptedBody : undefined; html = isPlainText ? undefined : message.decryption?.decryptedBody; } const attachments = await fetchMimeDependencies(message, messageKeys, getAttachment, onUpdateAttachment, api); return build(plaintext, html, attachments, message.messageImages); };
3,902
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/send/sendSubPackages.ts
import { CryptoProxy } from '@proton/crypto'; import { arrayToBinaryString, encodeBase64 } from '@proton/crypto/lib/utils'; import { AES256, MIME_TYPES, PACKAGE_SIGNATURES_MODE } from '@proton/shared/lib/constants'; import { Api } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { Package, Packages, SendPreferences } from '@proton/shared/lib/interfaces/mail/crypto'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import { getAttachments, isEO } from '@proton/shared/lib/mail/messages'; import { srpGetVerify } from '@proton/shared/lib/srp'; const { PLAINTEXT, DEFAULT, MIME } = MIME_TYPES; const { SEND_PM, SEND_CLEAR, SEND_PGP_INLINE, SEND_PGP_MIME, SEND_EO, SEND_CLEAR_MIME } = PACKAGE_TYPE; const { SIGNATURES_NONE, SIGNATURES_ATTACHMENTS } = PACKAGE_SIGNATURES_MODE; const getSignatureFlag = ({ sign }: Pick<SendPreferences, 'sign'>, message: Message) => sign && getAttachments(message).every(({ Signature }) => Signature) ? SIGNATURES_ATTACHMENTS : SIGNATURES_NONE; /** * Package for a Proton Mail user. */ const sendPM = async (sendPrefs: SendPreferences, message: Message) => ({ Type: SEND_PM, PublicKey: (sendPrefs.publicKeys?.length && sendPrefs.publicKeys[0]) || undefined, Signature: getSignatureFlag(sendPrefs, message), }); /** * Package for a outside user using Proton Mail encryption */ const sendPMEncryptedOutside = async (message: Message, api: Api) => { try { const sessionKey = await CryptoProxy.generateSessionKeyForAlgorithm(AES256); const Token = encodeBase64(arrayToBinaryString(sessionKey)); const [{ message: EncToken }, { Auth }] = await Promise.all([ CryptoProxy.encryptMessage({ textData: Token, stripTrailingSpaces: true, passwords: [message.Password || ''], // TODO can password actually be undefined? }), srpGetVerify({ api, credentials: { password: message.Password || '' } }), ]); return { Auth, Type: PACKAGE_TYPE.SEND_EO, PasswordHint: message.PasswordHint, Token, EncToken, Signature: +message.Attachments.every(({ Signature }) => Signature), }; } catch (err: any) { // TODO: mark encryption failed console.error(err); throw err; } }; /** * Package for a PGP/MIME user. */ const sendPGPMime = async ({ encrypt, sign, publicKeys }: SendPreferences) => { if (encrypt) { return { Type: SEND_PGP_MIME, PublicKey: (publicKeys?.length && publicKeys[0]) || undefined, }; } // PGP/MIME signature only return { Type: SEND_CLEAR_MIME, Signature: +sign, }; }; /** * Package for a PGP/Inline user. */ const sendPGPInline = async (sendPrefs: SendPreferences, message: Message) => { if (sendPrefs.encrypt) { return { Type: SEND_PGP_INLINE, PublicKey: (sendPrefs.publicKeys?.length && sendPrefs.publicKeys[0]) || undefined, Signature: getSignatureFlag(sendPrefs, message), }; } // PGP/Inline signature only return { Type: SEND_CLEAR, Signature: getSignatureFlag(sendPrefs, message), }; }; /** * Package for an unencrypted user */ const sendClear = async () => ({ Type: SEND_CLEAR, Signature: 0 }); /** * Attach the subpackages for encryptMessage to the given top level packages. The packages need to be encrypted before * they can be send to the api. See encryptPackages for that. */ export const attachSubPackages = async ( packages: Packages, message: Message, emails: string[], mapSendPrefs: SimpleMap<SendPreferences>, api: Api ): Promise<Packages> => { const bindPackageSet = async (promise: Promise<Package>, email: string, type: MIME_TYPES) => { const pack = await promise; const packageToUpdate = packages[type] as Package; if (!packageToUpdate.Addresses) { packageToUpdate.Addresses = {}; } if (!packageToUpdate.Type) { packageToUpdate.Type = 0; } packageToUpdate.Addresses[email] = pack; packageToUpdate.Type |= pack.Type || 0; }; const promises = emails.map((email: string) => { const sendPrefs = mapSendPrefs[email]; if (!sendPrefs) { throw new Error('Missing send preferences'); } const { encrypt, sign, pgpScheme, mimeType } = sendPrefs; const packageType = mimeType === 'text/html' ? DEFAULT : PLAINTEXT; switch (pgpScheme) { case SEND_PM: return bindPackageSet(sendPM(sendPrefs, message), email, packageType); case SEND_PGP_MIME: if (!sign && !encrypt) { return bindPackageSet(sendClear(), email, DEFAULT); } return bindPackageSet(sendPGPMime(sendPrefs), email, MIME); case SEND_PGP_INLINE: return bindPackageSet(sendPGPInline(sendPrefs, message), email, PLAINTEXT); case SEND_EO: case SEND_CLEAR: default: // Encrypted for outside (EO) if (isEO(message)) { return bindPackageSet(sendPMEncryptedOutside(message, api), email, packageType); } return bindPackageSet(sendClear(), email, packageType); } }); await Promise.all(promises); return packages; };
3,903
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/send/sendTopPackages.ts
import { WorkerDecryptionResult } from '@proton/crypto'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Api } from '@proton/shared/lib/interfaces'; import { Package, PackageStatus, Packages, SendPreferences } from '@proton/shared/lib/interfaces/mail/crypto'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import { addReceived } from '@proton/shared/lib/mail/messages'; import isTruthy from '@proton/utils/isTruthy'; import { MessageKeys, MessageState } from '../../logic/messages/messagesTypes'; import { getPlainText } from '../message/messageContent'; import { prepareExport } from '../message/messageExport'; import { constructMime } from './sendMimeBuilder'; // Reference: Angular/src/app/composer/services/encryptMessage.js // Reference: Angular/src/app/composer/services/generateTopPackages.js const { PLAINTEXT, DEFAULT, MIME } = MIME_TYPES; /** * Generates the mime top-level packages, which include all attachments in the body. * Build the multipart/alternate MIME entity containing both the HTML and plain text entities. */ const generateMimePackage = async ( message: MessageState, messageKeys: MessageKeys, getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined, onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void, api: Api ): Promise<Package> => ({ Flags: addReceived(message.data?.Flags), Addresses: {}, MIMEType: MIME, Body: await constructMime(message, messageKeys, getAttachment, onUpdateAttachment, api), }); const generatePlainTextPackage = async (message: MessageState): Promise<Package> => ({ Flags: addReceived(message.data?.Flags), Addresses: {}, MIMEType: PLAINTEXT, Body: getPlainText(message, true), }); const generateHTMLPackage = async (message: MessageState): Promise<Package> => ({ Flags: addReceived(message.data?.Flags), Addresses: {}, MIMEType: DEFAULT, // We NEVER upconvert, if the user wants html: plaintext is actually fine as well Body: prepareExport(message), }); /** * Generates all top level packages. The top level packages have unencrypted bodies which are encrypted later on * once the sub level packages are attached, so we know with which keys we need to encrypt the bodies with. * Top level packages that are not needed are not generated. */ export const generateTopPackages = async ( message: MessageState, messageKeys: MessageKeys, mapSendPrefs: SimpleMap<SendPreferences>, getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined, onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void, api: Api ): Promise<Packages> => { const packagesStatus: PackageStatus = Object.values(mapSendPrefs) .filter(isTruthy) .reduce( (packages, { encrypt, sign, pgpScheme, mimeType }) => ({ [PLAINTEXT]: packages[PLAINTEXT] || mimeType === MIME_TYPES.PLAINTEXT, [DEFAULT]: packages[DEFAULT] || mimeType === DEFAULT || (pgpScheme === PACKAGE_TYPE.SEND_PGP_MIME && !encrypt && !sign), [MIME]: packages[MIME] || (pgpScheme === PACKAGE_TYPE.SEND_PGP_MIME && (encrypt || sign)), }), { [PLAINTEXT]: false, [DEFAULT]: false, [MIME]: false, } as PackageStatus ); const demandedPackages = Object.values(MIME_TYPES).filter((k) => packagesStatus[k]); const packages: Packages = {}; await Promise.all( demandedPackages.map(async (type) => { switch (type) { case MIME: packages[MIME] = await generateMimePackage( message, messageKeys, getAttachment, onUpdateAttachment, api ); return; case PLAINTEXT: packages[PLAINTEXT] = await generatePlainTextPackage(message); return; case DEFAULT: packages[DEFAULT] = await generateHTMLPackage(message); return; default: throw new Error(); // Should never happen. } }) ); return packages; };
3,904
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/api.ts
import { FeatureCode } from '@proton/components'; import { addApiMock, addApiResolver, apiMock, apiMocksMap, clearApiMocks } from '@proton/testing'; /** * Export for backward compatibility in the tests. It can be gradually migrated to use @proton/testing package directly * in the tests. */ export { addApiMock, addApiResolver, clearApiMocks, apiMock as api, apiMocksMap as apiMocks }; export const featureFlags: { [code: string]: any } = {}; export const defaultFeatureFlagValue = { Code: '', Type: 'boolean', Global: false, DefaultValue: false, Value: false, UpdateTime: 1616511553, Writable: true, }; export const setFeatureFlags = (featureCode: string, value: boolean) => { featureFlags[featureCode] = { ...defaultFeatureFlagValue, Code: featureCode, Value: value, }; }; export const clearFeatureFlags = () => { Object.keys(featureFlags).forEach((key) => delete apiMocksMap[key]); }; export const registerFeatureFlagsApiMock = () => { addApiMock( 'core/v4/features', (args) => { const { Code } = args.params; const features: string[] = Code.split(','); return { Features: features.map((code) => featureFlags[code] ? featureFlags[code] : { ...defaultFeatureFlagValue, Code: code } ), }; }, 'get' ); }; export const registerMinimalFlags = () => { setFeatureFlags(FeatureCode.SpotlightEncryptedSearch, false); }; export const parseFormData = (data: any) => { const result: any = {}; const createStructure = (resultContext: any, name: string, left: string, value: any) => { if (!resultContext[name]) { resultContext[name] = {}; } if (left === '') { resultContext[name] = value; } else { const [, newName, newLeft] = /^\[([^[]+)\](.*)/.exec(left) || []; createStructure(resultContext[name], newName, newLeft, value); } }; Object.entries(data).forEach(([key, value]) => { const [, name, left] = /^([^[]+)(.*)/.exec(key) || []; createStructure(result, name, left, value); }); return result; }; export const mockDomApi = () => { window.HTMLElement.prototype.scrollIntoView = jest.fn(); // https://github.com/nickcolley/jest-axe/issues/147#issuecomment-758804533 const { getComputedStyle } = window; window.getComputedStyle = (elt) => getComputedStyle(elt); window.ResizeObserver = jest.fn(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), })); };
3,905
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/assertion.ts
export const assertIcon = ( iconElement: Element | null | undefined, iconName?: string, iconColor?: string, iconPrefix: string = 'ic' ) => { if (!iconElement) { throw new Error('Icon element is undefined'); } if (iconName) { expect((iconElement.firstChild as Element).getAttribute('xlink:href')).toBe(`#${iconPrefix}-${iconName}`); } if (iconColor) { expect(iconElement.classList.contains(iconColor)).toBe(true); } }; export const assertFocus = (element: Element | null | undefined, isFocused = true) => { const realIsFocused = document.activeElement === element; if (realIsFocused && !isFocused) { throw new Error('Element is focused while it should not'); } if (!realIsFocused && isFocused) { throw new Error('Element is not focused while it should be'); } }; export const assertCheck = (item: HTMLElement, checked = true) => { const checkbox = item.querySelector('input[type="checkbox"]') as HTMLInputElement | null; expect(checkbox?.checked).toBe(checked); };
3,906
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/cache.ts
import { ADDRESS_STATUS } from '@proton/shared/lib/constants'; import createCache from '@proton/shared/lib/helpers/cache'; import { Address, DecryptedKey, Key } from '@proton/shared/lib/interfaces'; import { SHORTCUTS } from '@proton/shared/lib/mail/mailSettings'; import { ResolvedRequest, addToCache, clearCache, mockCache, resolvedRequest } from '@proton/testing'; import { Base64Cache } from '../../hooks/useBase64Cache'; import { addKeysToAddressKeysCache } from './crypto'; /** * Export for backward compatibility in the tests. It can be gradually migrated to use @proton/testing package directly * in the tests. */ export { resolvedRequest, mockCache, addToCache, clearCache, ResolvedRequest }; export const getInstance = () => { const instance = createCache(); ['set', 'get', 'has', 'toObject', 'delete', 'subscribe', 'notify', 'reset'].forEach((methodName) => jest.spyOn(instance, methodName as any) ); return instance; }; export const addressKeysCache = createCache<string, { status: number; value: Partial<DecryptedKey>[] }>(); export const base64Cache = createCache<string, string>() as Base64Cache; export const minimalCache = () => { addToCache('User', { UsedSpace: 10, MaxSpace: 100, Flags: {} }); addToCache('Addresses', []); // Enable hotkeys to trigger composer save easily addToCache('MailSettings', { Shortcuts: SHORTCUTS.ENABLED }); addToCache('UserSettings', { Flags: {} }); addToCache('ContactEmails', []); addToCache('Labels', []); addToCache('MessageCounts', []); addToCache('ConversationCounts', []); addToCache('Filters', []); mockCache.set('ADDRESS_KEYS', addressKeysCache); addKeysToAddressKeysCache('AddressID', undefined); }; export const addAddressToCache = (inputAddress: Partial<Address>) => { const address = { ID: 'AddressID', Keys: [{ ID: 'KeyID' } as Key], Status: ADDRESS_STATUS.STATUS_ENABLED, Send: 1, Receive: 1, ...inputAddress, } as Address; const Addresses = mockCache.get('Addresses') as ResolvedRequest<Address[]>; Addresses.value.push(address); };
3,907
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/calendar.ts
import {getIsAllDay} from '@proton/shared/lib/calendar/veventHelper'; import { getUnixTime } from 'date-fns'; import { PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import { createCalendarEvent } from '@proton/shared/lib/calendar/serialize'; import { getDtendProperty, propertyToUTCDate } from '@proton/shared/lib/calendar/vcalConverter'; import { getPropertyTzid } from '@proton/shared/lib/calendar/vcalHelper'; import { booleanToNumber } from '@proton/shared/lib/helpers/boolean'; import { Attendee, CalendarEvent, CalendarEventData, VcalVeventComponent, } from '@proton/shared/lib/interfaces/calendar'; const withAuthorCard = (card: Omit<CalendarEventData, 'Author'>, author: string): CalendarEventData => { return { ...card, Author: author, }; }; const toApiAttendees = (attende: Omit<Attendee, 'ID' | 'UpdateTime'>[], updateTime = getUnixTime(new Date())) => { return attende.map(({ Token, Status }, index) => ({ ID: `attendee-${index + 1}`, UpdateTime: updateTime, Token, Status, })); }; export const generateApiCalendarEvent = async ({ eventComponent, author, publicKey, privateKey, eventID, sharedEventID, calendarID, isOrganizer = true, isProtonProtonInvite = false, }: { eventComponent: VcalVeventComponent; author: string; publicKey: PublicKeyReference; privateKey: PrivateKeyReference; eventID: string; sharedEventID: string; calendarID: string; isOrganizer?: boolean; isProtonProtonInvite?: boolean; }): Promise<CalendarEvent> => { const { SharedEventContent = [], SharedKeyPacket, CalendarEventContent = [], CalendarKeyPacket, Notifications, AttendeesEventContent = [], Attendees = [], } = await createCalendarEvent({ eventComponent, publicKey, privateKey, isCreateEvent: true, isSwitchCalendar: false, hasDefaultNotifications: true, }); const nowTimestamp = getUnixTime(new Date()); const { dtstart, uid } = eventComponent; const dtend = getDtendProperty(eventComponent); return { ID: eventID, SharedEventID: sharedEventID, CalendarID: calendarID, CreateTime: nowTimestamp, ModifyTime: nowTimestamp, Permissions: 1, IsOrganizer: booleanToNumber(isOrganizer), IsProtonProtonInvite: isProtonProtonInvite ? 1 : 0, Author: author, StartTime: getUnixTime(propertyToUTCDate(dtstart)), StartTimezone: getPropertyTzid(dtstart) || 'UTC', EndTime: getUnixTime(propertyToUTCDate(dtend)), EndTimezone: getPropertyTzid(dtend) || 'UTC', FullDay: +getIsAllDay(eventComponent), RRule: null, UID: uid.value, RecurrenceID: null, Exdates: [], CalendarKeyPacket: CalendarKeyPacket || null, CalendarEvents: CalendarEventContent.map((card) => withAuthorCard(card, author)), SharedKeyPacket: SharedKeyPacket || null, SharedEvents: SharedEventContent.map((card) => withAuthorCard(card, author)), AddressKeyPacket: null, AddressID: null, Notifications, AttendeesEvents: AttendeesEventContent.map((card) => withAuthorCard(card, author)), Attendees: toApiAttendees(Attendees), }; };
3,908
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/contact.ts
import { prepareCardsFromVCard } from '@proton/shared/lib/contacts/encrypt'; import { toKeyProperty } from '@proton/shared/lib/contacts/keyProperties'; import { createContactPropertyUid, fromVCardProperties } from '@proton/shared/lib/contacts/properties'; import { Contact, ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { addApiMock } from './api'; import { GeneratedKey } from './crypto'; export interface ContactMock { contactID: string; email: string; mimeType?: string; pinKey?: GeneratedKey; } export const apiContacts = new Map<string, ContactMock>(); const addApiContactMock = () => { addApiMock('contacts/v4/contacts/emails', (args) => { const email = args.params.Email; if (apiContacts.has(email)) { const contactMock = apiContacts.get(email) as ContactMock; return { ContactEmails: [{ ContactID: contactMock.contactID }] as ContactEmail[] }; } // console.log('api contact email', args, email); return {}; }); }; addApiContactMock(); export const addApiContact = (contact: ContactMock, key: GeneratedKey) => { apiContacts.set(contact.email, contact); addApiMock(`contacts/v4/contacts/${contact.contactID}`, async () => { const group = 'group'; const properties: VCardProperty<string>[] = [ { field: 'email', value: contact.email, group, uid: createContactPropertyUid() }, ]; if (contact.pinKey) { properties.push(await toKeyProperty({ publicKey: contact.pinKey.publicKeys[0], group, index: 0 })); } if (contact.mimeType) { properties.push({ field: 'x-pm-mimetype', value: contact.mimeType, group: 'group', uid: createContactPropertyUid(), }); } const vCardContact = fromVCardProperties(properties); const Cards = await prepareCardsFromVCard(vCardContact, { privateKey: key.privateKeys[0], publicKey: key.publicKeys[0], }); return { Contact: { ContactID: contact.contactID, Cards } as Partial<Contact> }; }); }; export const clearApiContacts = () => { apiContacts.clear(); addApiContactMock(); };
3,909
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/crypto.ts
import { CryptoProxy, PrivateKeyReference, PublicKeyReference, SessionKey } from '@proton/crypto'; import { generatePassphrase } from '@proton/shared/lib/calendar/crypto/keys/calendarKeys'; import { ENCRYPTION_CONFIGS, ENCRYPTION_TYPES, KEY_FLAG } from '@proton/shared/lib/constants'; import { base64ToArray } from '../base64'; import { addApiMock } from './api'; import { addressKeysCache, mockCache, resolvedRequest } from './cache'; export interface GeneratedKey { name: string; email: string; publicKeyArmored: string; privateKeyArmored: string; publicKeys: PublicKeyReference[]; privateKeys: PrivateKeyReference[]; } export interface ApiKey { isInternal: boolean; keys: GeneratedKey[]; } export const apiKeys = new Map<string, ApiKey>(); const addApiKeysMock = () => { addApiMock('core/v4/keys/all', (args) => { const email = args.params.Email; if (apiKeys.has(email)) { const apiKey = apiKeys.get(email) as ApiKey; const publicKeysWithMetadata = apiKey.keys.map((key) => ({ Flags: KEY_FLAG.FLAG_NOT_OBSOLETE | KEY_FLAG.FLAG_NOT_COMPROMISED, PublicKey: key.publicKeyArmored, })); const internalKeys = apiKey.isInternal ? publicKeysWithMetadata : []; const externalKeys = apiKey.isInternal ? [] : publicKeysWithMetadata; return { Address: { Keys: internalKeys, SignedKeyList: null, }, Unverified: { Keys: externalKeys }, ProtonMX: apiKey.isInternal, }; } console.log('api keys', args, email); return { Address: { Keys: [] } }; }); }; addApiKeysMock(); export const addApiKeys = (isInternal: boolean, email: string, keys: GeneratedKey[]) => { apiKeys.set(email, { isInternal, keys }); }; export const clearApiKeys = () => { apiKeys.clear(); addApiKeysMock(); }; export const generateKeys = async (name: string, email: string, passphrase = 'passphrase'): Promise<GeneratedKey> => { const privateKey = await CryptoProxy.generateKey({ userIDs: [{ name, email }], }); const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase }); const publicKeyArmored = await CryptoProxy.exportPublicKey({ key: privateKey }); const publicKeys = [await CryptoProxy.importPublicKey({ armoredKey: publicKeyArmored })]; const privateKeys = [privateKey]; return { name, email, publicKeyArmored, privateKeyArmored, publicKeys, privateKeys, }; }; export const generateCalendarKeysAndPassphrase = async (addressKey: GeneratedKey | Promise<GeneratedKey>) => { const { publicKeys: addressPublicKeys, privateKeys: addressPrivateKeys } = addressKey instanceof Promise ? await addressKey : addressKey; const passphrase = generatePassphrase(); const privateKey = await CryptoProxy.generateKey({ userIDs: [{ name: 'Calendar key' }], ...ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519], }); const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase }); const publicKeyArmored = await CryptoProxy.exportPublicKey({ key: privateKey }); const publicKeys = [await CryptoProxy.importPublicKey({ armoredKey: publicKeyArmored })]; const privateKeys = [privateKey]; const { message: data, signature } = await CryptoProxy.encryptMessage({ textData: passphrase, encryptionKeys: addressPublicKeys, signingKeys: addressPrivateKeys, detached: true, }); return { calendarKey: { publicKeyArmored, privateKeyArmored, publicKeys, privateKeys, }, passphrase: { clearText: passphrase, armored: data, signature, }, }; }; export const addKeysToUserKeysCache = (key: GeneratedKey) => { mockCache.set('USER_KEYS', resolvedRequest([{ publicKey: key.publicKeys[0], privateKey: key.privateKeys[0] }])); }; export const addKeysToAddressKeysCache = (addressID: string, key: GeneratedKey | undefined) => { const currentValue = addressKeysCache.get(addressID)?.value || []; const newValue = key ? [{ publicKey: key.publicKeys[0], privateKey: key.privateKeys[0] }] : []; addressKeysCache.set(addressID, resolvedRequest([...currentValue, ...newValue])); }; export const encryptSessionKey = async ({ data, algorithm }: SessionKey, publicKey: PublicKeyReference) => { const encryptedSessionKey = await CryptoProxy.encryptSessionKey({ data, algorithm, encryptionKeys: [publicKey], format: 'binary', }); return encryptedSessionKey; }; export const generateSessionKey = async (publicKey: PublicKeyReference) => { const sessionKey = await CryptoProxy.generateSessionKey({ recipientKeys: publicKey }); return sessionKey; }; export const decryptSessionKey = async (keyPacket: string, privateKeys: PrivateKeyReference[]) => { const sessionKey = await CryptoProxy.decryptSessionKey({ binaryMessage: base64ToArray(keyPacket), decryptionKeys: privateKeys, }); return sessionKey as SessionKey; }; /** * Load Crypto API outside of web workers, for testing purposes. */ export async function setupCryptoProxyForTesting() { // dynamic import to avoid loading the library unless required const { Api: CryptoApi } = await import('@proton/crypto/lib/worker/api'); CryptoApi.init(); CryptoProxy.setEndpoint(new CryptoApi(), (endpoint) => endpoint.clearKeyStore()); } export function releaseCryptoProxy() { return CryptoProxy.releaseEndpoint(); }
3,910
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/event-manager.ts
import { useEventManager } from '@proton/components'; import { Event } from '../../models/event'; export const eventManagerListeners: ((...args: any[]) => any)[] = []; ((useEventManager as any).subscribe as jest.Mock).mockImplementation((listener) => { eventManagerListeners.push(listener); }); export const triggerEvent = (event: Event) => { eventManagerListeners.forEach((listener) => listener(event)); };
3,911
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/experiments.tsx
import React from 'react'; import ExperimentsContext from '@proton/components/containers/experiments/ExperimentsContext'; interface Props { children: React.ReactNode; } /** * It's a duplicate of the original ExperimentsProvider for testing purpose * We want the experiments to always be "A" and loaded */ const ExperimentsTestProvider = ({ children }: Props) => { return ( <ExperimentsContext.Provider value={{ experiments: {}, loading: false, initialize: jest.fn() }}> {children} </ExperimentsContext.Provider> ); }; export default ExperimentsTestProvider;
3,912
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/helper.ts
import { waitFor } from '@testing-library/react'; import { act } from '@testing-library/react'; import { useEventManager } from '@proton/components'; import { globalReset } from '../../logic/actions'; import { store } from '../../logic/store'; import { api, clearApiMocks } from './api'; import { addressKeysCache, base64Cache, clearCache } from './cache'; import { clearApiContacts } from './contact'; import { clearApiKeys } from './crypto'; import { eventManagerListeners } from './event-manager'; import { resetHistory } from './render'; export * from './cache'; export * from './crypto'; export * from './render'; export * from './api'; export * from './event-manager'; export * from './message'; export * from './assertion'; const savedConsole = { ...console }; export const clearAll = () => { jest.clearAllMocks(); api.mockClear(); store.dispatch(globalReset()); clearApiMocks(); clearCache(); clearApiKeys(); clearApiContacts(); addressKeysCache.clear(); base64Cache.clear(); eventManagerListeners.splice(0, eventManagerListeners.length); resetHistory(); console = { ...savedConsole }; }; export const mockConsole = (level: keyof Console = 'error') => { console[level] = jest.fn(); }; export const waitForSpyCall = async (mock: jest.Mock) => act(async () => waitFor(() => expect(mock).toHaveBeenCalled(), { interval: 100, timeout: 5000, }) ); export const waitForEventManagerCall = async () => { // Hard override of the typing as event manager is mocked const { call } = (useEventManager as any as () => { call: jest.Mock })(); await waitForSpyCall(call); }; export const getModal = () => { const modal = (document.querySelector('dialog[aria-modal="true"]') as HTMLDialogElement | null) || (document.querySelector('div[class="modal"]') as HTMLDialogElement | null); if (!modal) { throw new Error('No modal was on screen'); } const submit = modal.querySelector('button[type="submit"]') as HTMLButtonElement | null; const cancel = modal.querySelector('button[type="reset"]') as HTMLButtonElement | null; const close = modal.querySelector('button.modal-close') as HTMLButtonElement | null; return { modal, submit, cancel, close }; }; export const getDropdown = () => waitFor( () => { const dropdown = document.querySelector('div[role="dialog"].dropdown') as HTMLDialogElement | null; if (!dropdown) { throw new Error('No dropdown was on screen'); } return dropdown; }, { interval: 100, timeout: 5000, } ); export const waitForNotification = (content: string) => waitFor( () => { const notifications = document.querySelectorAll('div[role="alert"].notification'); const matchingNotification = [...notifications].find((notification) => notification.textContent?.includes(content) ); if (matchingNotification) { return matchingNotification; } throw new Error(`Notification not found with "${content}"`); }, { interval: 100, timeout: 5000, } ); export const waitForNoNotification = () => waitFor( () => { const notifications = document.querySelectorAll('div[role="alert"].notification:not(.notification--out)'); if (notifications.length === 0) { return; } const matchingNotification = [...notifications].map((notification) => notification.textContent); throw new Error(`Notification still present with "${matchingNotification.join(', ')}"`); }, { interval: 100, timeout: 5000, } );
3,913
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/message.ts
import { CryptoProxy, PrivateKeyReference, PublicKeyReference, SessionKey, VERIFICATION_STATUS, WorkerDecryptionOptions, } from '@proton/crypto'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { MessageEmbeddedImage, MessageImage, MessageImages } from '../../logic/messages/messagesTypes'; import { arrayToBase64, base64ToArray } from '../base64'; import { readContentIDandLocation } from '../message/messageEmbeddeds'; import { GeneratedKey, encryptSessionKey, generateSessionKey } from './crypto'; // Helper to make testing easier export const removeLineBreaks = (text: string) => { return text.replaceAll(/\n/g, ''); }; export const createDocument = (content: string): Element => { const document = window.document.createElement('div'); document.innerHTML = content; return document; }; export const readSessionKey = (key: any) => { return { data: base64ToArray(key.Key), algorithm: key.Algorithm, }; }; // Blob type in Jest doesn't have the new arrayBuffer function, maybe not yet implemented in JSDom const readBlob = async (blob: Blob) => new Promise<Uint8Array>((resolve, reject) => { const fileReader = new FileReader(); fileReader.onload = (event) => { if (event.target?.result instanceof ArrayBuffer) { resolve(new Uint8Array(event.target.result)); } else { reject(event); } }; fileReader.readAsArrayBuffer(blob); }); /** * Decrypt non-legacy message. */ export const decryptMessage = async (pack: any, privateKeys: PrivateKeyReference[], sessionKey: SessionKey) => { const decryptResult = await CryptoProxy.decryptMessage({ binaryMessage: await readBlob(pack.Body), decryptionKeys: privateKeys, sessionKeys: [sessionKey], }); return { data: decryptResult.data, signatures: decryptResult.signatures }; }; /** * Decrypts the mime message and parses the body and attachments in the right structure. * @param options * @return {Promise<{getBody: (function(): Promise<{body, mimetype}>), getAttachments: (function(): Promise<any>), getEncryptedSubject: (function(): Promise<any>), verify: (function(): Promise<any>), errors: (function(): Promise<any>), stop: stop}>} */ export async function decryptMIMEMessage(options: WorkerDecryptionOptions) { const { data: rawData, verified, signatures } = await CryptoProxy.decryptMessage({ ...options, format: 'utf8' }); const { body, mimeType, verified: pgpMimeVerified, attachments, encryptedSubject, signatures: pgpMimeSignatures, } = await CryptoProxy.processMIME({ ...options, data: rawData }); const combinedVerified = verified === VERIFICATION_STATUS.NOT_SIGNED ? pgpMimeVerified : verified; return { getBody: () => Promise.resolve(body ? { body, mimeType } : undefined), getAttachments: () => Promise.resolve(attachments), getEncryptedSubject: () => Promise.resolve(encryptedSubject), verify: () => Promise.resolve(combinedVerified), stop() {}, signatures: [...signatures, ...pgpMimeSignatures], }; } export const decryptMessageMultipart = async ( pack: any, privateKeys: PrivateKeyReference[], sessionKey: SessionKey ) => { const decryptResult = await decryptMIMEMessage({ binaryMessage: await readBlob(pack.Body), decryptionKeys: privateKeys, sessionKeys: [sessionKey], }); const bodyResult = await decryptResult.getBody(); const attachments = await decryptResult.getAttachments(); return { data: bodyResult?.body, mimeType: bodyResult?.mimeType, attachments }; }; export const createAttachment = async (inputAttachment: Partial<Attachment>, publicKeys: PublicKeyReference[]) => { const attachment = { ...inputAttachment }; const sessionKey = await generateSessionKey(publicKeys[0]); const encryptedSessionKey = await encryptSessionKey(sessionKey, publicKeys[0]); attachment.KeyPackets = arrayToBase64(encryptedSessionKey); return { attachment, sessionKey }; }; export const encryptMessage = async (body: string, fromKeys: GeneratedKey, toKeys: GeneratedKey) => { const { message } = await CryptoProxy.encryptMessage({ textData: body, stripTrailingSpaces: true, encryptionKeys: [toKeys.publicKeys?.[0]], signingKeys: [fromKeys.privateKeys?.[0]], }); return message; }; export const createEmbeddedImage = (attachment: Attachment) => ({ type: 'embedded', attachment, cid: readContentIDandLocation(attachment).cid, url: 'url', id: 'image-id', status: 'loaded', } as MessageEmbeddedImage); export const createMessageImages = (images: MessageImage[] = []) => ({ showEmbeddedImages: true, showRemoteImages: true, hasEmbeddedImages: true, hasRemoteImages: true, trackersStatus: 'not-loaded', images, } as MessageImages);
3,914
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/mockUseEncryptedSearchContext.ts
import { defaultESContextMail } from '../../constants'; import * as encryptedSearchProviderModule from '../../containers/EncryptedSearchProvider'; export const mockUseEncryptedSearchContext = ( value?: Partial<ReturnType<typeof encryptedSearchProviderModule.useEncryptedSearchContext>> ) => { const mockedUseEncryptedSearchContext = jest.spyOn(encryptedSearchProviderModule, 'useEncryptedSearchContext'); mockedUseEncryptedSearchContext.mockReturnValue({ ...defaultESContextMail, ...value, }); return mockedUseEncryptedSearchContext; };
3,915
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/mockUseScheduleSendFeature.ts
import * as useScheduleSendFeature from '../../components/composer/actions/scheduleSend/useScheduleSendFeature'; export const mockUseScheduleSendFeature = (value?: Partial<ReturnType<typeof useScheduleSendFeature.default>>) => { const mockedUseScheduleSendFeature = jest.spyOn(useScheduleSendFeature, 'default'); mockedUseScheduleSendFeature.mockReturnValue({ canScheduleSend: false, canScheduleSendCustom: false, loading: false, ...value, }); return mockedUseScheduleSendFeature; };
3,916
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/notifications.tsx
import React, { useRef } from 'react'; import NotificationsContainer from '@proton/components/containers/notifications/Container'; import { Notification } from '@proton/components/containers/notifications/interfaces'; import createNotificationManager from '@proton/components/containers/notifications/manager'; import NotificationsContext from '@proton/components/containers/notifications/notificationsContext'; import noop from '@proton/utils/noop'; import { useLongLivingState } from '../../hooks/useLongLivingState'; interface Props { children: React.ReactNode; } /** * It's a duplicate of the original NotificationProvider for testing purpose * The main (only?) difference is that it uses a "long living state" for notification * In order to simplify tests no making Jest scream at any notification happening too late * YET it's still relevant to try to prevent any async leak from your tests */ const NotificationsTestProvider = ({ children }: Props) => { const [notifications, setNotifications] = useLongLivingState<Notification[]>([]); const managerRef = useRef<ReturnType<typeof createNotificationManager>>(); if (!managerRef.current) { managerRef.current = createNotificationManager(setNotifications as any, noop); } const manager = managerRef.current; const { hideNotification, removeNotification, removeDuplicate } = manager; return ( <NotificationsContext.Provider value={manager}> {children} <NotificationsContainer notifications={notifications} removeNotification={removeNotification} removeDuplicate={removeDuplicate} hideNotification={hideNotification} /> </NotificationsContext.Provider> ); }; export default NotificationsTestProvider;
3,917
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/pinKeys.tsx
import { CryptoProxy } from '@proton/crypto'; import { arrayToBinaryString, encodeBase64 } from '@proton/crypto/lib/utils'; import { prepareCardsFromVCard } from '@proton/shared/lib/contacts/encrypt'; import { createContactPropertyUid, fromVCardProperties } from '@proton/shared/lib/contacts/properties'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { addApiMock } from './api'; import { GeneratedKey, generateKeys } from './crypto'; export const contactID = 'contactID'; export const receiver = { Name: 'receiver', Address: 'receiver@protonmail.com', } as Recipient; export const sender = { Name: 'sender', Address: 'sender@outside.com', ContactID: contactID, } as Recipient; export const message = { ID: 'messageID', Sender: sender, ToList: [receiver] as Recipient[], } as Message; export const contactEmails = [{ ContactID: contactID, Email: sender.Address } as ContactEmail] as ContactEmail[]; const getProperties = async (senderKeys: GeneratedKey, hasFingerprint = true) => { const keyValue = hasFingerprint ? `data:application/pgp-keys;base64,${encodeBase64( arrayToBinaryString( await CryptoProxy.exportPublicKey({ key: senderKeys.publicKeys[0], format: 'binary' }) ) )}` : 'data:application/pgp-keys;'; return [ { field: 'fn', value: 'Sender', params: { pref: '1' }, uid: createContactPropertyUid() } as VCardProperty, { field: 'email', group: 'item1', value: sender.Address, params: { pref: '1' }, uid: createContactPropertyUid(), } as VCardProperty, { field: 'key', group: 'item1', value: keyValue, params: { pref: '1' }, uid: createContactPropertyUid(), } as VCardProperty, ] as VCardProperty[]; }; export const setupContactsForPinKeys = async (hasFingerprint = true) => { const updateSpy = jest.fn(() => Promise.resolve({})); addApiMock(`contacts/v4/contacts/${contactID}`, updateSpy, 'put'); const receiverKeys = await generateKeys('me', receiver.Address); const senderKeys = await generateKeys('sender', sender.Address); const properties = await getProperties(senderKeys, hasFingerprint); const vCardContact = fromVCardProperties(properties); const contactCards = await prepareCardsFromVCard(vCardContact, { privateKey: receiverKeys.privateKeys[0], publicKey: receiverKeys.publicKeys[0], }); // Add an api mock to use the created contact when the call is done addApiMock( `contacts/v4/contacts/${contactID}`, () => { return { Contact: { Cards: contactCards, ContactEmails: contactEmails } }; }, 'get' ); return { receiverKeys, senderKeys, updateSpy }; };
3,918
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/quick-settings.tsx
import { ReactNode } from 'react'; import { QuickSettingsRemindersContext } from '@proton/components/hooks/drawer/useQuickSettingsReminders'; interface Props { children: ReactNode; } /** * It's a duplicate of the original QuickSettingsReminderProvider for testing purpose * We want the experiments to always be "A" and loaded */ const QuickSettingsTestProvider = ({ children }: Props) => { return ( <QuickSettingsRemindersContext.Provider value={{ reminders: [] }}> {children} </QuickSettingsRemindersContext.Provider> ); }; export default QuickSettingsTestProvider;
3,919
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/render.tsx
import * as React from 'react'; import { ReactElement, ReactNode, useRef } from 'react'; import { Provider as ReduxProvider } from 'react-redux'; import { Route, Router } from 'react-router'; import { RenderResult as OriginalRenderResult, act, render as originalRender } from '@testing-library/react'; import { act as actHook, renderHook as originalRenderHook } from '@testing-library/react-hooks'; import { MemoryHistory, createMemoryHistory } from 'history'; import { CacheProvider, CalendarModelEventManagerProvider, EventModelListener, ModalsChildren, ModalsProvider, PrivateAuthenticationStore, } from '@proton/components'; import SpotlightProvider from '@proton/components/components/spotlight/Provider'; import ApiContext from '@proton/components/containers/api/apiContext'; import AuthenticationProvider from '@proton/components/containers/authentication/Provider'; import ConfigProvider from '@proton/components/containers/config/Provider'; import FeaturesProvider from '@proton/components/containers/features/FeaturesProvider'; import { DrawerProvider } from '@proton/components/hooks/drawer/useDrawer'; import { APPS } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { ProtonConfig } from '@proton/shared/lib/interfaces'; import { ConversationCountsModel, MessageCountsModel } from '@proton/shared/lib/models'; import QuickSettingsTestProvider from 'proton-mail/helpers/test/quick-settings'; import { LabelActionsContextProvider } from '../../components/sidebar/EditLabelContext'; import { MAIN_ROUTE_PATH } from '../../constants'; import { ComposeProvider } from '../../containers/ComposeProvider'; import EncryptedSearchProvider from '../../containers/EncryptedSearchProvider'; import { MailboxContainerContextProvider } from '../../containers/mailbox/MailboxContainerProvider'; import ChecklistsProvider from '../../containers/onboardingChecklist/provider/ChecklistsProvider'; import { MailContentRefProvider } from '../../hooks/useClickMailContent'; import { store, useSetReduxThunkExtraArgs } from '../../logic/store'; import { api, mockDomApi, registerFeatureFlagsApiMock, registerMinimalFlags } from './api'; import { minimalCache, mockCache } from './cache'; import ExperimentsTestProvider from './experiments'; import NotificationsTestProvider from './notifications'; interface RenderResult extends OriginalRenderResult { rerender: (ui: React.ReactElement) => Promise<void>; } export const authentication = { getUID: jest.fn(() => 'uid'), getLocalID: jest.fn(), getPassword: jest.fn(), onLogout: jest.fn(), } as unknown as PrivateAuthenticationStore; let history: MemoryHistory; export const getHistory = () => history; export const resetHistory = () => { history = createMemoryHistory({ initialEntries: ['/inbox'] }); }; resetHistory(); export const config = { APP_NAME: APPS.PROTONMAIL, APP_VERSION: 'test-version', DATE_VERSION: 'test-date-version', } as ProtonConfig; export const onCompose = jest.fn(); interface Props { children: ReactNode; } export const ReduxProviderWrapper = ({ children }: Props) => { useSetReduxThunkExtraArgs(); return <ReduxProvider store={store}>{children}</ReduxProvider>; }; const TestProvider = ({ children }: Props) => { const contentRef = useRef<HTMLDivElement>(null); return ( <ConfigProvider config={config}> <ApiContext.Provider value={api}> <NotificationsTestProvider> <ModalsProvider> <AuthenticationProvider store={authentication}> <CalendarModelEventManagerProvider> <CacheProvider cache={mockCache}> <QuickSettingsTestProvider> <FeaturesProvider> <SpotlightProvider> <DrawerProvider> <ExperimentsTestProvider> <ModalsChildren /> <EventModelListener models={[ConversationCountsModel, MessageCountsModel]} /> <ReduxProviderWrapper> <MailContentRefProvider mailContentRef={contentRef}> <ChecklistsProvider> <MailboxContainerContextProvider isResizing={false} containerRef={contentRef} elementID={undefined} > <ComposeProvider onCompose={onCompose}> <Router history={history}> <Route path={MAIN_ROUTE_PATH}> <EncryptedSearchProvider> <LabelActionsContextProvider> {children} </LabelActionsContextProvider> </EncryptedSearchProvider> </Route> </Router> </ComposeProvider> </MailboxContainerContextProvider> </ChecklistsProvider> </MailContentRefProvider> </ReduxProviderWrapper> </ExperimentsTestProvider> </DrawerProvider> </SpotlightProvider> </FeaturesProvider> </QuickSettingsTestProvider> </CacheProvider> </CalendarModelEventManagerProvider> </AuthenticationProvider> </ModalsProvider> </NotificationsTestProvider> </ApiContext.Provider> </ConfigProvider> ); }; /** * Small helper to wait for asynchronous work to be executed * Should be avoided as much as possible, but often convenient */ export const tick = () => { return act(() => Promise.resolve()); }; export const render = async (ui: ReactElement, useMinimalCache = true): Promise<RenderResult> => { mockDomApi(); registerFeatureFlagsApiMock(); if (useMinimalCache) { minimalCache(); registerMinimalFlags(); } const result = originalRender(<TestProvider>{ui}</TestProvider>); await tick(); // Should not be necessary, would be better not to use it, but fails without const rerender = async (ui: ReactElement) => { result.rerender(<TestProvider>{ui}</TestProvider>); await tick(); // Should not be necessary, would be better not to use it, but fails without }; const unmount = () => { // Unmounting the component not the whole context result.rerender(<TestProvider>{null}</TestProvider>); return true; }; return { ...result, rerender, unmount }; }; export const renderHook = async <TProps, TResult>(callback: (props: TProps) => TResult, useMinimalCache = true) => { registerFeatureFlagsApiMock(); if (useMinimalCache) { minimalCache(); registerMinimalFlags(); } const result = originalRenderHook<TProps, TResult>(callback, { wrapper: TestProvider as any }); await actHook(() => wait(0)); return result; };
3,920
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/eo/EORender.tsx
import { ReactElement, ReactNode } from 'react'; import * as React from 'react'; import { Provider as ReduxProvider } from 'react-redux'; import { Router } from 'react-router'; import { Route } from 'react-router-dom'; import { RenderResult as OriginalRenderResult, render as originalRender } from '@testing-library/react'; import { MemoryHistory, createMemoryHistory } from 'history'; import { CacheProvider, ConfigProvider, ExperimentsProvider, FeaturesProvider, ModalsChildren, ModalsProvider, } from '@proton/components'; import ApiContext from '@proton/components/containers/api/apiContext'; import { EO_REDIRECT_PATH } from '../../../constants'; import { store } from '../../../logic/eo/eoStore'; import { api, mockDomApi, registerFeatureFlagsApiMock } from '../api'; import { mockCache } from '../cache'; import NotificationsTestProvider from '../notifications'; import { config, tick } from '../render'; interface RenderResult extends OriginalRenderResult { rerender: (ui: React.ReactElement) => Promise<void>; } let history: MemoryHistory; export const EOGetHistory = () => history; export const EOResetHistory = (initialEntries: string[] = ['/eo']) => { history = createMemoryHistory({ initialEntries }); }; EOResetHistory(); interface Props { children: ReactNode; routePath?: string; } const EOTestProvider = ({ children, routePath = EO_REDIRECT_PATH }: Props) => { return ( <ConfigProvider config={config}> <ApiContext.Provider value={api}> <NotificationsTestProvider> <ModalsProvider> <CacheProvider cache={mockCache}> <FeaturesProvider> <ExperimentsProvider> <ModalsChildren /> <ReduxProvider store={store}> <Router history={history}> <Route path={routePath}>{children}</Route> </Router> </ReduxProvider> </ExperimentsProvider> </FeaturesProvider> </CacheProvider> </ModalsProvider> </NotificationsTestProvider> </ApiContext.Provider> </ConfigProvider> ); }; export const EORender = async (ui: ReactElement, routePath?: string): Promise<RenderResult> => { mockDomApi(); registerFeatureFlagsApiMock(); const result = originalRender(<EOTestProvider routePath={routePath}>{ui}</EOTestProvider>); await tick(); // Should not be necessary, would be better not to use it, but fails without const rerender = async (ui: ReactElement) => { result.rerender(<EOTestProvider routePath={routePath}>{ui}</EOTestProvider>); await tick(); // Should not be necessary, would be better not to use it, but fails without }; const unmount = () => { // Unmounting the component not the whole context result.rerender(<EOTestProvider routePath={routePath}>{null}</EOTestProvider>); return true; }; return { ...result, rerender, unmount }; };
3,921
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/test/eo/helpers.tsx
import { CryptoProxy } from '@proton/crypto'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Recipient } from '@proton/shared/lib/interfaces'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { globalReset } from '../../../logic/actions'; import { init, loadEOMessage, loadEOToken } from '../../../logic/eo/eoActions'; import { store } from '../../../logic/eo/eoStore'; import { EOMessage, EOMessageReply } from '../../../logic/eo/eoType'; import { convertEOtoMessageState } from '../../eo/message'; import { addApiMock, api, clearApiMocks } from '../api'; import { base64Cache, clearCache } from '../cache'; import { generateKeys } from '../crypto'; import { resetHistory } from '../render'; import { EOResetHistory } from './EORender'; const savedConsole = { ...console }; export const reply = { Body: 'EO reply body', Attachments: [] as Attachment[], } as EOMessageReply; export const EOClearAll = () => { jest.clearAllMocks(); api.mockClear(); store.dispatch(globalReset()); clearApiMocks(); clearCache(); base64Cache.clear(); resetHistory(); console = { ...savedConsole }; }; export const mockConsole = (level: keyof Console = 'error') => { console[level] = jest.fn(); }; export const getEOEncryptedMessage = async (decryptedToken: string, password: string) => { const { message } = await CryptoProxy.encryptMessage({ textData: decryptedToken, passwords: [password], }); return message; }; export interface EOOriginalMessageOptions { body?: string; attachments?: Attachment[]; numAttachments?: number; expirationTime?: number; time?: number; replies?: EOMessageReply[]; } export const validID = 'validID'; export const invalidID = 'invalidID'; export const EODecryptedToken = 'decryptedToken'; export const EOPassword = 'password'; export const EOInvalidPassword = 'invalidPassword'; export const EOLocalID = 'eoLocalID'; export const EOSubject = 'Test EO subject'; export const EOBody = 'Test EO body'; export const EOSender = { Name: 'EO Sender', Address: 'EOsender@protonmail.com' } as Recipient; export const EORecipient = { Name: 'EO Recipient', Address: 'EOrecipient@protonmail.com' } as Recipient; export const getEOOriginalMessage = async (options?: EOOriginalMessageOptions) => { return { Attachments: options?.attachments || ([] as Attachment[]), Body: await getEOEncryptedMessage(options?.body || EOBody, EOPassword), ToList: [EORecipient] as Recipient[], CCList: [] as Recipient[], ExpirationTime: options?.expirationTime || 0, Subject: EOSubject, Sender: EOSender, Time: options?.time || new Date().getTime(), NumAttachments: options?.numAttachments || 0, Replies: options?.replies || ([] as EOMessageReply[]), MIMEType: MIME_TYPES.DEFAULT, } as EOMessage; }; export const getEOMessageState = async () => { const EOOriginalMessage = await getEOOriginalMessage(); return convertEOtoMessageState(EOOriginalMessage, EOLocalID); }; export const EOInitStore = async (initialRoute: string, options?: EOOriginalMessageOptions) => { const publicKey = await generateKeys(EOSender.Name, EOSender.Address); EOResetHistory([`/eo/${initialRoute}/${validID}`]); const EOOriginalMessage = await getEOOriginalMessage(options); const EOEncryptedToken = await getEOEncryptedMessage(EODecryptedToken, EOPassword); addApiMock(`mail/v4/eo/token/${validID}`, () => ({ Token: EOEncryptedToken })); addApiMock('mail/v4/eo/message', () => ({ Message: EOOriginalMessage as EOMessage, PublicKey: publicKey.publicKeyArmored, })); await store.dispatch(init({ get: jest.fn() })); await store.dispatch(loadEOToken({ api, id: validID, set: jest.fn() })); await store.dispatch( loadEOMessage({ api, id: validID, set: jest.fn(), token: EOEncryptedToken, password: EOPassword }) ); };
3,922
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/toolbar/getToolbarResponsiveSizes.ts
export const getToolbarResponsiveSizes = (breakpoint?: string) => { const localIsTiny = breakpoint === 'extratiny' || breakpoint === 'tiny'; const localIsExtraTiny = breakpoint === 'extratiny'; const localIsNarrow = breakpoint === 'extratiny' || breakpoint === 'tiny' || breakpoint === 'small'; return { localIsTiny, localIsExtraTiny, localIsNarrow, }; };
3,923
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/transformBase.ts
import { IMG_SRC_BASE_64_PREFIX } from './transformEscape'; const ELEMENTS = [ { selector: 'a:not([href^="http"]):not([href^="mailto:"])', attribute: 'href', }, { selector: `img:not([src^="http"]):not([proton-src^="cid"]):not([${IMG_SRC_BASE_64_PREFIX}])`, attribute: 'src', }, ]; const getBaseURL = (base: HTMLBaseElement) => { // Make sure base has trailing slash const baseUrl = base.getAttribute('href') || ''; if (baseUrl.substring(baseUrl.length - 1, baseUrl.length) !== '/') { return `${baseUrl}/`; } return baseUrl; }; /** * Append base url to any href/src if we need to * @param html HTML document from DOMPurify * @return Dom based */ export const transformBase = (document: Element) => { const base = document.querySelector('base'); if (!base || !base.getAttribute('href')) { return { document }; } // Make sure base has trailing slash const BASE_URL = getBaseURL(base); const bindAttribute = (node: Element, key: string, value = '') => { if (!value.startsWith('http')) { node.setAttribute(key, BASE_URL + value); } }; ELEMENTS.forEach(({ selector, attribute }) => { [...document.querySelectorAll(selector)].forEach((el) => { const keyproton = `proton-${attribute}`; const value = el.getAttribute(attribute) || ''; const ptValue = el.getAttribute(keyproton) || ''; // Ensure we don't add a useless / if we already have one const url = value.charAt(0) === '/' ? value.slice(1) : value; /* Bind the value only when we need, if there is a proton-src we don't need to add the src else it will generate a request to the domain */ if (ptValue || (attribute === 'src' && !value)) { bindAttribute(el, keyproton, ptValue); } else { bindAttribute(el, attribute, url); } }); }); // Remove base element, even if there are several document.querySelectorAll('base').forEach((base) => { base.parentElement?.removeChild(base); }); };
3,924
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/transformEmbedded.ts
import generateUID from '@proton/shared/lib/helpers/generateUID'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { hasShowEmbedded } from '@proton/shared/lib/mail/images'; import { getAttachments, hasProtonSender, isDraft } from '@proton/shared/lib/mail/messages'; import { LoadEmbeddedResults, MessageEmbeddedImage, MessageState } from '../../logic/messages/messagesTypes'; import { decryptEmbeddedImages, findEmbedded, insertBlobImages, markEmbeddedImagesAsLoaded, matchSameCidOrLoc, readContentIDandLocation, setEmbeddedAttr, } from '../message/messageEmbeddeds'; import { getEmbeddedImages, insertImageAnchor } from '../message/messageImages'; export const transformEmbedded = async ( message: MessageState, mailSettings: MailSettings, onLoadEmbeddedImages: (attachments: Attachment[]) => Promise<LoadEmbeddedResults> ) => { const draft = isDraft(message.data); const showEmbeddedImages = message.messageImages?.showEmbeddedImages === true || hasShowEmbedded(mailSettings) || hasProtonSender(message.data); const existingEmbeddedImage = getEmbeddedImages(message); let newEmbeddedImages: MessageEmbeddedImage[] = []; if (message.messageDocument?.document) { const { document } = message.messageDocument; newEmbeddedImages = getAttachments(message.data) .map((attachment) => { const { cid, cloc } = readContentIDandLocation(attachment); const existing = existingEmbeddedImage.find((embeddedImage) => matchSameCidOrLoc(embeddedImage, cid, cloc) ); if (existing) { return []; } const matches = findEmbedded(cid, cloc, document); return matches.map((match) => { const id = generateUID('embedded'); if (draft) { setEmbeddedAttr(cid, cloc, match); } else { insertImageAnchor(id, 'embedded', match); } return { type: 'embedded' as 'embedded', original: match, id, cid, cloc, tracker: attachment.Headers?.['x-pm-tracker-provider'], attachment, status: 'not-loaded' as 'not-loaded', }; }); }) .flat(); } let embeddedImages = [...existingEmbeddedImage, ...newEmbeddedImages]; const hasEmbeddedImages = !!embeddedImages.length; if (showEmbeddedImages) { const { updatedImages, downloadPromise } = decryptEmbeddedImages(embeddedImages, onLoadEmbeddedImages); embeddedImages = updatedImages; // In draft, we actually want image in the document if (draft) { const downloadResults = await downloadPromise; embeddedImages = markEmbeddedImagesAsLoaded(embeddedImages, downloadResults); if (message.messageDocument?.document) { insertBlobImages(message.messageDocument.document, embeddedImages); } } } return { showEmbeddedImages: hasEmbeddedImages ? showEmbeddedImages : undefined, embeddedImages, hasEmbeddedImages, }; };
3,925
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/transformEscape.ts
import { removeHTMLComments } from '@proton/shared/lib/helpers/string'; import { protonizer as purifyHTML } from '@proton/shared/lib/sanitize'; import { Base64Cache } from '../../hooks/useBase64Cache'; import { uniqID } from '../string'; export const IMG_SRC_BASE_64_PREFIX = 'data-proton-replace-base'; /** * Parsing base64 is expensive and can create a crash. * Here we can reduce input string from many Mb to less than 100kb, which is way easier to escape. * So instead of escaping everything with it too, we remove them from the HTML * and we replace it with an attribute with an uniq hash so we can load them * later for the user via injectMessageMedia component. * Store it inside inside a cache * - lazy load the image post render message * - open the composer we need to lazy load it here too * * Source: regexp https://www.regextester.com/95505 * @param input Raw unescaped HTML */ const removeBase64 = (input: string, cache?: Base64Cache): string => { /* eslint no-useless-escape: "off" */ return input.replace(/src="data:image\/([a-zA-Z]*);base64,([^\"]*)\"/g, (match) => { const hash = uniqID(); if (cache) { cache.set(hash, match); } return `${IMG_SRC_BASE_64_PREFIX}="${hash}"`; }); }; /** * Parse the dom and find all matching base64 custom tags we added * then replace them by the valid SRC for the base64. * @return HTML */ export const attachBase64 = (element: Element, cache: Base64Cache) => { const nodes = [...element.querySelectorAll(`[${IMG_SRC_BASE_64_PREFIX}]`)]; nodes.forEach((node) => { const hash = node.getAttribute(IMG_SRC_BASE_64_PREFIX); // Clean the string and remove \n else it won't load inside the browser const src = (cache.get(hash || '') || '') .replace(/^src="/, '') .replace(/"$/, '') .replace(/\n/, ''); if (src) { node.setAttribute('src', src); } node.removeAttribute(IMG_SRC_BASE_64_PREFIX); }); }; /** * Escape content for a message * Content can be a Document when we open a message, it's useful * in order to bind the base if it exists * @param message Message to escape * @param action Type of action */ export const transformEscape = (content = '', cache?: Base64Cache) => { // We are removing all comments from the HTML string, // so that we can avoid having potential issues when removing Base 64 images wrongly formatted const withoutComment = removeHTMLComments(content); const value = removeBase64(withoutComment, cache); const document = purifyHTML(value, true); return document; };
3,926
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/transformLinks.ts
import { getUTMTrackersFromURL } from '@proton/shared/lib/mail/trackers'; import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers'; import { matches } from '../dom'; const PROTOCOLS = ['ftp://', 'http://', 'https://', 'xmpp:', 'tel:', 'callto:']; const ALL_PROTOCOLS = PROTOCOLS.concat(['mailto:']); const MAP = PROTOCOLS.reduce<{ [key: string]: boolean }>((acc, key) => { acc[key] = true; return acc; }, {}); const EXCLUDE_ANCHORS = ':not([href=""]):not([href^="#"])'; const getNormalizedHref = (link: HTMLLinkElement) => { return (link.getAttribute('href') || '').trim().toLowerCase(); }; const linkUsesProtocols = (link: HTMLLinkElement) => ALL_PROTOCOLS.some((proto) => getNormalizedHref(link).startsWith(proto)); const isEmptyAnchor = (link: HTMLLinkElement) => { const href = getNormalizedHref(link); return href === '' || MAP[href]; }; const noReferrerInfo = (link: HTMLLinkElement) => { link.setAttribute('rel', 'noreferrer nofollow noopener'); }; /** * make links open in a new tab */ const httpInNewTab = (link: HTMLLinkElement) => { if (matches(link, EXCLUDE_ANCHORS)) { const href = link.getAttribute('href') || ''; const hasHTTP = href.indexOf('http') === 0; const isRelative = href.indexOf('/') === 0; // Prevent issue for Edge/IE A security problem cf https://jsfiddle.net/dpaoxoks/7/ if (hasHTTP || isRelative) { link.setAttribute('target', '_blank'); } } }; /** * turn these relative links into absolute links * (example.com/a -> http://example.com) */ const sanitizeRelativeHttpLinks = (link: HTMLLinkElement) => { if (matches(link, EXCLUDE_ANCHORS) && !linkUsesProtocols(link) && link.nodeName === 'A') { // link.href is the absolute value of the link: mail.proton.me is prepended, use getAttribute const url = link.getAttribute('href'); if (url) { link.setAttribute('href', `http://${url}`); } } }; const removeTrackingTokens = (link: HTMLLinkElement) => { if (matches(link, EXCLUDE_ANCHORS) && link.nodeName === 'A') { const href = link.getAttribute('href'); if (href) { const result = getUTMTrackersFromURL(href); if (result) { link.setAttribute('href', result.url); return result?.utmTracker; } } } }; /* * Anchors will work on the whole protonmail page, so we need to disable them * opening them in a new tab will just open a empty page. */ const disableAnchors = (link: HTMLLinkElement) => { if (isEmptyAnchor(link)) { link.style.pointerEvents = 'none'; } }; export const transformLinks = ( document: Element, onCleanUTMTrackers: (utmTrackers: MessageUTMTracker[]) => void, canCleanUTMTrackers: boolean ) => { const links = [...document.querySelectorAll('[href]')] as HTMLLinkElement[]; const utmTrackers: MessageUTMTracker[] = []; links.forEach((link) => { httpInNewTab(link); noReferrerInfo(link); if (canCleanUTMTrackers) { const tracker = removeTrackingTokens(link); if (tracker) { utmTrackers.push(tracker); } } sanitizeRelativeHttpLinks(link); disableAnchors(link); }); if (utmTrackers.length > 0) { onCleanUTMTrackers(utmTrackers); } };
3,927
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/transformRemote.ts
import { hasBit } from '@proton/shared/lib/helpers/bitset'; import generateUID from '@proton/shared/lib/helpers/generateUID'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { hasShowRemote } from '@proton/shared/lib/mail/images'; import { IMAGE_PROXY_FLAGS } from '@proton/shared/lib/mail/mailSettings'; import { isDraft } from '@proton/shared/lib/mail/messages'; import { MessageRemoteImage, MessageState } from '../../logic/messages/messagesTypes'; import { querySelectorAll } from '../message/messageContent'; import { getRemoteImages, insertImageAnchor } from '../message/messageImages'; import { ATTRIBUTES_TO_FIND, ATTRIBUTES_TO_LOAD, hasToSkipProxy, loadFakeImages, loadRemoteImages, loadSkipProxyImages, removeProtonPrefix, } from '../message/messageRemotes'; const SELECTOR = ATTRIBUTES_TO_FIND.map((name) => { if (name === 'src') { return '[proton-src]:not([proton-src^="cid"]):not([proton-src^="data"])'; } // https://stackoverflow.com/questions/23034283/is-it-possible-to-use-htmls-queryselector-to-select-by-xlink-attribute-in-an if (name === 'xlink:href') { return '[*|href]:not([href])'; } return `[proton-${name}]`; }).join(','); export const getRemoteImageMatches = (message: MessageState) => { const imageElements = querySelectorAll(message, SELECTOR); const elementsWithStyleTag = querySelectorAll(message, '[style]').reduce<HTMLElement[]>((acc, elWithStyleTag) => { const styleTagValue = elWithStyleTag.getAttribute('style'); const hasSrcAttribute = elWithStyleTag.hasAttribute('src'); if (styleTagValue && !hasSrcAttribute && styleTagValue.includes('proton-url')) { acc.push(elWithStyleTag); } return acc; }, []); return { matchedElements: [...imageElements, ...elementsWithStyleTag], hasRemoteImages: imageElements.length + elementsWithStyleTag.length > 0, }; }; export const transformRemote = ( message: MessageState, mailSettings: Partial<MailSettings>, onLoadRemoteImagesDirect: (imagesToLoad: MessageRemoteImage[]) => void, onLoadRemoteImagesProxy?: (imagesToLoad: MessageRemoteImage[]) => void, onLoadFakeImagesProxy?: (imagesToLoad: MessageRemoteImage[], firstLoad?: boolean) => void ) => { const showRemoteImages = message.messageImages?.showRemoteImages || hasShowRemote(mailSettings) || !!message.data?.Sender?.IsProton; const draft = isDraft(message.data); const useProxy = hasBit(mailSettings.ImageProxy, IMAGE_PROXY_FLAGS.PROXY); const { matchedElements, hasRemoteImages } = getRemoteImageMatches(message); const remoteImages = getRemoteImages(message); const skipProxy = hasToSkipProxy(remoteImages); matchedElements.forEach((match) => { // Avoid duplicating images if (remoteImages.find(({ original }) => original === match)) { return; } const id = generateUID('remote'); if (match.tagName === 'IMG') { if (!draft) { insertImageAnchor(id, 'remote', match); } } // If the user do not want to use the proxy at all, we can remove all proton prefix in drafts // This will load all images if (draft && showRemoteImages && !useProxy) { removeProtonPrefix(match); } let url = ''; ATTRIBUTES_TO_LOAD.some((attribute) => { url = match.getAttribute(`proton-${attribute}`) || ''; return url && url !== ''; }); if (!url && match.hasAttribute('style') && match.getAttribute('style')?.includes('proton-url')) { const styleContent = match.getAttribute('style'); if (styleContent !== null) { const nextUrl = styleContent.match(/proton-url\((.*?)\)/)?.[1].replace(/('|")/g, ''); if (nextUrl) { url = nextUrl; } } } // Some elements might not have a URL at this point, e.g. img tag with only a srcset attribute // We don't want to display an error placeholder, so we don't add them if (url) { remoteImages.push({ type: 'remote', url, original: match, id, tracker: undefined, status: 'not-loaded', }); } }); if (skipProxy) { void loadSkipProxyImages(remoteImages, onLoadRemoteImagesDirect); } else if (showRemoteImages) { // Beware because we also pass here when loading images in EO // Load images through proxy, by forging the URL and putting it directly into the image src void loadRemoteImages(useProxy, remoteImages, onLoadRemoteImagesDirect, onLoadRemoteImagesProxy); // Make a fake load of images to check if they are trackers if (useProxy && onLoadFakeImagesProxy) { void loadFakeImages(remoteImages, onLoadFakeImagesProxy); } } else if (useProxy && onLoadFakeImagesProxy) { void loadFakeImages(remoteImages, onLoadFakeImagesProxy, true); } // We might found images elements that we do not add to remote images, e.g. img tag with only a srcset attribute const containsRemoteImages = hasRemoteImages && remoteImages.length > 0; return { document, showRemoteImages: containsRemoteImages ? showRemoteImages : undefined, remoteImages, hasRemoteImages: containsRemoteImages, }; };
3,928
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/transformStyleAttributes.ts
const isHTMLElement = (element: Element): element is HTMLElement => 'style' in element; const replaceViewportHeightUnit = (element: HTMLElement) => { const height = element.style.height; if (!height) { return; } if (height.includes('vh')) { element.style.height = 'auto'; } }; export const transformStyleAttributes = (document: Element) => { const nodesWithStyleAttribute = document.querySelectorAll('[style]'); for (const element of nodesWithStyleAttribute) { if (!isHTMLElement(element)) { continue; } replaceViewportHeightUnit(element); } };
3,929
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/transformStylesheet.ts
export const transformStylesheet = (document: Element) => { const firstElement = document.firstElementChild as HTMLElement | null; /** * Some emails from ex: tripit contains a position absolute on the container * => hack to prevent margin on android/ios * @{@link https://twitter.com/HTeuMeuLeu/status/852110032045035520} * Gmail changes the dom too. */ if (firstElement && /absolute/.test(firstElement.style.position)) { firstElement.style.position = 'inherit'; } };
3,930
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/transformWelcome.ts
export const transformWelcome = (document: Element) => { // For the welcome email, we need to change the path to the welcome image lock const images = [...document.querySelectorAll('img[src="/img/app/welcome_lock.gif"]')] as HTMLImageElement[]; if (images.length > 0) { images.forEach((image) => { image.src = '/assets/img/emails/welcome_lock.gif'; }); } };
3,931
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/transforms.ts
import { MailSettings } from '@proton/shared/lib/interfaces'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/mailSettings'; import { transformLinkify } from '@proton/shared/lib/mail/transformLinkify'; import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers'; import { Base64Cache } from '../../hooks/useBase64Cache'; import { LoadEmbeddedResults, MessageImage, MessageRemoteImage, MessageState, } from '../../logic/messages/messagesTypes'; import { transformBase } from './transformBase'; import { transformEmbedded } from './transformEmbedded'; import { attachBase64, transformEscape } from './transformEscape'; import { transformLinks } from './transformLinks'; import { transformRemote } from './transformRemote'; import { transformStyleAttributes } from './transformStyleAttributes'; import { transformStylesheet } from './transformStylesheet'; import { transformWelcome } from './transformWelcome'; export interface Preparation { plainText?: string; document?: Element; showEmbeddedImages?: boolean; showRemoteImages?: boolean; hasRemoteImages?: boolean; hasEmbeddedImages?: boolean; remoteImages?: MessageImage[]; embeddedImages?: MessageImage[]; } export const prepareHtml = async ( message: MessageState, base64Cache: Base64Cache, mailSettings: MailSettings, onLoadEmbeddedImages: (attachments: Attachment[]) => Promise<LoadEmbeddedResults>, onLoadRemoteImagesProxy: (imagesToLoad: MessageRemoteImage[]) => void, onLoadFakeImagesProxy: (imagesToLoad: MessageRemoteImage[], firstLoad?: boolean) => void, onLoadRemoteImagesDirect: (imagesToLoad: MessageRemoteImage[]) => void, onCleanUTMTrackers: (utmTrackers: MessageUTMTracker[]) => void, canCleanUTMTrackersFeature: boolean ): Promise<Preparation> => { const document = transformEscape(message.decryption?.decryptedBody, base64Cache); const canCleanUTMTrackers = canCleanUTMTrackersFeature && (!!mailSettings.ImageProxy || false); transformBase(document); transformLinks(document, onCleanUTMTrackers, canCleanUTMTrackers); const { showEmbeddedImages, hasEmbeddedImages, embeddedImages } = await transformEmbedded( { ...message, messageDocument: { document } }, mailSettings, onLoadEmbeddedImages ); transformWelcome(document); transformStylesheet(document); transformStyleAttributes(document); const { showRemoteImages, hasRemoteImages, remoteImages } = transformRemote( { ...message, messageDocument: { document } }, mailSettings, onLoadRemoteImagesDirect, onLoadRemoteImagesProxy, onLoadFakeImagesProxy ); attachBase64(document, base64Cache); return { document, showRemoteImages, showEmbeddedImages, hasRemoteImages, remoteImages, hasEmbeddedImages, embeddedImages, }; }; export const preparePlainText = async ( body: string, isDraft: boolean, mailSettings: MailSettings = DEFAULT_MAILSETTINGS, canCleanUTMTrackersFeature?: boolean, onCleanUTMTrackers?: (utmTrackers: MessageUTMTracker[]) => void ): Promise<Preparation> => { const canCleanUTMTrackers = canCleanUTMTrackersFeature && (!!mailSettings.ImageProxy || false); const plainText = isDraft ? body : transformLinkify({ content: body, canCleanUTMTrackers, onCleanUTMTrackers }); return { plainText }; };
3,932
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformBase.test.ts
import range from '@proton/utils/range'; import { transformBase } from '../transformBase'; describe('transformBase service', () => { const URL_PROTON = 'https://proton.me'; const URL_PROTON_SLASH = 'https://proton.me/'; const LINKS = { linkRelative: '/monique', linkRelative2: '/robert', linkRelative3: 'roberts', imgRelative: '/monique.jpg', imgRelative2: '/robert.jpg', imgRelative3: 'robert3.jpg', linkAbsolutehttp: 'http://cpp.li/monique', linkAbsolutehttps: 'https://cpp.li/monique2', imgAbsolute: 'http://cpp.li/robert3.jpg', imgAbsolute2: 'https://cpp.li/robert3.jpg', imgCID: 'cid:xxxxx', imghttp: 'https://cpp.li/robert3.jpg', ahttp: 'https://cpp.li/', mailto: 'mailto:someone@domain.com', }; const DOM = ` <section> <a href="${LINKS.linkRelative}" id="linkRelative" class="link-relative">Monique</a> <a href="${LINKS.linkRelative2}" id="linkRelative2" class="link-relative">Robert</a> <a href="${LINKS.linkRelative3}" id="linkRelative3" class="link-relative">Roberts</a> <a href="${LINKS.linkAbsolutehttp}" id="linkAbsolutehttp" class="link-absolute">Monique</a> <a href="${LINKS.linkAbsolutehttps}" id="linkAbsolutehttps" class="link-absolute">Monique</a> <a class="link-empty" id="linkNope">Nope</a> <img src="${LINKS.imgRelative}" id="imgRelative" class="img-relative"> <img src="${LINKS.imgRelative2}" id="imgRelative2" class="img-relative"> <img src="${LINKS.imgRelative3}" id="imgRelative3" class="img-relative"> <img src="${LINKS.imgAbsolute}" id="imgAbsolute" class="img-absolute"> <img src="${LINKS.imgAbsolute2}" id="imgAbsolute2" class="img-absolute"> <img class="img-empty" id="imgNope"> <img proton-src="${LINKS.imgCID}" alt="" id="imgcid" /> <img src="${LINKS.imghttp}" alt="" id="imghttp" /> <a href="${LINKS.ahttp}" id="ahttp">dew</a> <a href="${LINKS.mailto}" id="mailto">Mailto</a> </section `; const DEFAULT_DOMAIN = 'http://lol.com'; const setup = (path = DEFAULT_DOMAIN) => { const doc = document.implementation.createHTMLDocument('test transformBase'); const base = document.createElement('BASE') as HTMLBaseElement; base.href = path; doc.head.appendChild(base); doc.body.innerHTML = DOM; transformBase(doc.documentElement); const querySelector = (selectors: string) => doc.querySelector(selectors); const querySelectorAll = (selectors: string) => [...doc.querySelectorAll(selectors)]; return { document: doc, querySelector, querySelectorAll }; }; describe('Remove base tag', () => { it('should remove base tag from the head', () => { const { querySelectorAll } = setup(); expect(querySelectorAll('base').length).toBe(0); }); it('should remove multiple base tag from the head', () => { const doc = document.implementation.createHTMLDocument('test transformBase'); range(0, 5).forEach((index) => { const base = document.createElement('BASE') as HTMLBaseElement; base.href = `https://something.com/${index}/`; doc.head.appendChild(base); }); doc.body.innerHTML = DOM; transformBase(doc.documentElement); expect(doc.querySelectorAll('base').length).toBe(0); }); }); describe('Escape base relative no slash', () => { describe('For a link', () => { const getLinks = (type = 'relative') => { const { querySelectorAll } = setup(URL_PROTON); return querySelectorAll(`.link-${type}`).map((element) => (element as HTMLLinkElement).href); }; it('should prepend the base into href', () => { const [link1, link2, link3] = getLinks(); expect(link1).toContain(URL_PROTON); expect(link2).toContain(URL_PROTON); expect(link3).toContain(URL_PROTON); }); it('should prepend the base into href without breaking the path', () => { const [link1, link2] = getLinks(); expect(link1).toBe(URL_PROTON + LINKS.linkRelative); expect(link2).toBe(URL_PROTON + LINKS.linkRelative2); }); it('should prepend the base into href with a slash', () => { const [, , link3] = getLinks(); expect(link3).toBe(`${URL_PROTON}/${LINKS.linkRelative3}`); }); it('should bind a href if there is not', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#linkNope') as HTMLLinkElement; expect(nope.href).toBe(`${URL_PROTON}/`); }); it('should not change the HREF for a link with already http', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#ahttp') as HTMLLinkElement; expect(nope.href).toBe(LINKS.ahttp); }); }); describe('For an image', () => { const getImages = (type = 'relative') => { const { querySelectorAll } = setup(URL_PROTON); return querySelectorAll(`.img-${type}`).map((element) => (element as HTMLImageElement).src); }; it('should prepend the base into href', () => { const [img1, img2, img3] = getImages(); expect(img1).toContain(URL_PROTON); expect(img2).toContain(URL_PROTON); expect(img3).toContain(URL_PROTON); }); it('should prepend the base into src without breaking the path', () => { const [img1, img2] = getImages(); expect(img1).toBe(URL_PROTON + LINKS.imgRelative); expect(img2).toBe(URL_PROTON + LINKS.imgRelative2); }); it('should prepend the base into src with a slash', () => { const [, , img3] = getImages(); expect(img3).toBe(`${URL_PROTON}/${LINKS.imgRelative3}`); }); it('should bind proton-src if there is not', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#imgNope') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(`${URL_PROTON}/`); expect(nope.src).toBe(''); }); it('should not change the SRC for a link with already http', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#imghttp') as HTMLImageElement; expect(nope.src).toBe(LINKS.imghttp); }); it('should not change the SRC for a link with cid', () => { const { querySelector } = setup(URL_PROTON); const nope = querySelector('#imgcid') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(LINKS.imgCID); expect(nope.getAttribute('src')).toBe(null); }); }); }); describe('Escape base relative slash', () => { describe('For a link', () => { const getLinks = (type = 'relative') => { const { querySelectorAll } = setup(URL_PROTON_SLASH); return querySelectorAll(`.link-${type}`).map((element) => (element as HTMLLinkElement).href); }; it('should prepend the base into href', () => { const [link1, link2, link3] = getLinks(); expect(link1).toContain(URL_PROTON_SLASH); expect(link2).toContain(URL_PROTON_SLASH); expect(link3).toContain(URL_PROTON_SLASH); }); it('should prepend the base into href without breaking the path', () => { const [link1, link2] = getLinks(); expect(link1).toBe(URL_PROTON + LINKS.linkRelative); expect(link2).toBe(URL_PROTON + LINKS.linkRelative2); }); it('should prepend the base into href with a slash', () => { const [, , link3] = getLinks(); expect(link3).toBe(URL_PROTON_SLASH + LINKS.linkRelative3); }); it('should bind a href if there is not', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#linkNope') as HTMLLinkElement; expect(nope.href).toBe(URL_PROTON_SLASH); }); it('should not change the HREF for a link with already http', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#ahttp') as HTMLLinkElement; expect(nope.href).toBe(LINKS.ahttp); }); }); describe('For an image', () => { const getImages = (type = 'relative') => { const { querySelectorAll } = setup(URL_PROTON_SLASH); return querySelectorAll(`.img-${type}`).map((element) => (element as HTMLImageElement).src); }; it('should prepend the base into href', () => { const [img1, img2, img3] = getImages(); expect(img1).toContain(URL_PROTON_SLASH); expect(img2).toContain(URL_PROTON_SLASH); expect(img3).toContain(URL_PROTON_SLASH); }); it('should prepend the base into src without breaking the path', () => { const [img1, img2] = getImages(); expect(img1).toBe(URL_PROTON + LINKS.imgRelative); expect(img2).toBe(URL_PROTON + LINKS.imgRelative2); }); it('should prepend the base into src with a slash', () => { const [, , img3] = getImages(); expect(img3).toBe(URL_PROTON_SLASH + LINKS.imgRelative3); }); it('should bind proton-src if there is not', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#imgNope') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(URL_PROTON_SLASH); expect(nope.src).toBe(''); }); it('should not change the SRC for a link with already http', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#imghttp') as HTMLImageElement; expect(nope.src).toBe(LINKS.imghttp); }); it('should not change the SRC for a link with cid', () => { const { querySelector } = setup(URL_PROTON_SLASH); const nope = querySelector('#imgcid') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(LINKS.imgCID); expect(nope.getAttribute('src')).toBe(null); }); }); }); describe('Escape with a base', () => { const matchLink = (url: string, domain = DEFAULT_DOMAIN) => `${domain}${url.startsWith('/') ? url : `/${url}`}`; describe('For a link', () => { const getLinks = (type = 'relative') => { const { querySelectorAll } = setup(); return querySelectorAll(`.link-${type}`).map((element) => (element as HTMLLinkElement).href); }; it('should prepend the base into href', () => { const [link1, link2, link3] = getLinks(); expect(link1).not.toContain(URL_PROTON); expect(link2).not.toContain(URL_PROTON); expect(link3).not.toContain(URL_PROTON); }); it('should prepend the base into href without breaking the path', () => { const [link1, link2] = getLinks(); expect(link1).toBe(matchLink(LINKS.linkRelative)); expect(link2).toBe(matchLink(LINKS.linkRelative2)); }); it('should prepend the base into href with a slash', () => { const [, , link3] = getLinks(); expect(link3).toBe(matchLink(LINKS.linkRelative3)); }); it('should bind a href if there is not', () => { const { querySelector } = setup(); const nope = querySelector('#linkNope') as HTMLLinkElement; expect(nope.href).toBe(matchLink('')); }); it('should not change the HREF for a link with already http', () => { const { querySelector } = setup(); const nope = querySelector('#ahttp') as HTMLLinkElement; expect(nope.href).toBe(LINKS.ahttp); }); it('should not change the HREF for a mailto link', () => { const { querySelector } = setup(); const nope = querySelector('#mailto') as HTMLLinkElement; expect(nope.href).toBe(LINKS.mailto); }); }); describe('For an image', () => { const getImages = (type = 'relative') => { const { querySelectorAll } = setup(); return querySelectorAll(`.img-${type}`).map((element) => (element as HTMLImageElement).src); }; it('should prepend the base into href', () => { const [img1, img2, img3] = getImages(); expect(img1).not.toContain(URL_PROTON_SLASH); expect(img2).not.toContain(URL_PROTON_SLASH); expect(img3).not.toContain(URL_PROTON_SLASH); }); it('should prepend the base into src without breaking the path', () => { const [img1, img2] = getImages(); expect(img1).toBe(matchLink(LINKS.imgRelative)); expect(img2).toBe(matchLink(LINKS.imgRelative2)); }); it('should prepend the base into src with a slash', () => { const [, , img3] = getImages(); expect(img3).toBe(matchLink(LINKS.imgRelative3)); }); it('should bind proton-src if there is not', () => { const { querySelector } = setup(); const nope = querySelector('#imgNope') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(matchLink('')); expect(nope.src).toBe(''); }); it('should not change the SRC for a link with already http', () => { const { querySelector } = setup(); const nope = querySelector('#imghttp') as HTMLImageElement; expect(nope.src).toBe(LINKS.imghttp); }); it('should not change the SRC for a link with cid', () => { const { querySelector } = setup(); const nope = querySelector('#imgcid') as HTMLImageElement; expect(nope.getAttribute('proton-src')).toBe(LINKS.imgCID); expect(nope.getAttribute('src')).toBe(null); }); }); }); });
3,933
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformEmbedded.test.ts
import { MailSettings } from '@proton/shared/lib/interfaces'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import { MessageImage, MessageState } from '../../../logic/messages/messagesTypes'; import { createDocument } from '../../test/message'; import { transformEmbedded } from '../transformEmbedded'; const defaultMailSettings = { HideEmbeddedImages: SHOW_IMAGES.SHOW, } as MailSettings; describe('transformEmbedded', () => { const setup = (message: MessageState, mailSettings = defaultMailSettings) => { return transformEmbedded( message, mailSettings, jest.fn(() => Promise.resolve([])) ); }; it('should detect cid embedded images', async () => { const cids = ['imageCID1', 'imageCID2', 'imageCID3', 'imageCID4', 'imageCID5', 'imageCID6']; const content = `<div> <img src='cid:${cids[0]}'/> <img src='${cids[1]}'/> <img src='${cids[2]}' data-embedded-img='${cids[2]}'/> <img src='${cids[3]}' data-embedded-img='cid:${cids[3]}'/> <img src='${cids[4]}' data-src='${cids[4]}'/> <img src='${cids[5]}' proton-src='${cids[5]}'/> </div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [ { Headers: { 'content-id': cids[0] } } as Attachment, { Headers: { 'content-id': cids[1] } } as Attachment, { Headers: { 'content-id': cids[2] } } as Attachment, { Headers: { 'content-id': cids[3] } } as Attachment, { Headers: { 'content-id': cids[4] } } as Attachment, { Headers: { 'content-id': cids[5] } } as Attachment, ], } as Message, messageDocument: { document: createDocument(content) }, }; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages.length).toEqual(6); embeddedImages.forEach((img, index) => { expect(embeddedImages[index].attachment.Headers?.['content-id']).toEqual(cids[index]); expect(embeddedImages[index].cid).toEqual(cids[index]); expect(embeddedImages[index].cloc).toEqual(''); expect(embeddedImages[index].type).toEqual('embedded'); }); }); it('should detect cloc embedded images', async () => { const cloc = 'imageCLOC'; const content = `<div><img src='${cloc}' proton-src='${cloc}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [{ Headers: { 'content-location': cloc } } as Attachment], } as Message, messageDocument: { document: createDocument(content) }, }; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-location']).toEqual(cloc); expect(embeddedImages[0].cloc).toEqual(cloc); expect(embeddedImages[0].cid).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); }); it('should detect embedded images when already loaded', async () => { const cid = 'imageCID'; const content = `<div><img src='cid:${cid}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [{ Headers: { 'content-id': cid } } as Attachment], } as Message, messageDocument: { document: createDocument(content) }, messageImages: { hasRemoteImages: false, hasEmbeddedImages: true, showRemoteImages: false, showEmbeddedImages: true, trackersStatus: 'not-loaded', images: [ { type: 'embedded', cid, cloc: '', attachment: { Headers: { 'content-id': cid } } as Attachment, } as MessageImage, ], }, }; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-id']).toEqual(cid); expect(embeddedImages[0].cid).toEqual(cid); expect(embeddedImages[0].cloc).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); }); it('should detect embedded images in drafts', async () => { const cid = 'imageCID'; const content = `<div><img src='cid:${cid}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Flags: 12, // Flag as draft Attachments: [{ Headers: { 'content-id': cid } } as Attachment], } as Message, messageDocument: { document: createDocument(content) }, }; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-id']).toEqual(cid); expect(embeddedImages[0].cid).toEqual(cid); expect(embeddedImages[0].cloc).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); expect(embeddedImages[0].status).toEqual('not-loaded'); }); it('should load embedded images by default whatever the loading setting value when Sender is Proton verified', async () => { const cid = 'imageCID'; const content = `<div><img src='cid:${cid}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [{ Headers: { 'content-id': cid } } as Attachment], Sender: { Name: 'Verified address', Address: 'verified@proton.me', IsProton: 1, }, } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideEmbeddedImages: SHOW_IMAGES.HIDE, } as MailSettings; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message, mailSettings); expect(showEmbeddedImages).toBeTruthy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-id']).toEqual(cid); expect(embeddedImages[0].cid).toEqual(cid); expect(embeddedImages[0].cloc).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); }); it('should not load embedded images by default when Sender is not Proton verified', async () => { const cid = 'imageCID'; const content = `<div><img src='cid:${cid}'/></div>`; const message: MessageState = { localID: 'messageWithEmbedded', data: { ID: 'messageID', Attachments: [{ Headers: { 'content-id': cid } } as Attachment], Sender: { Name: 'Normal address', Address: 'normal@proton.me', IsProton: 0, }, } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideEmbeddedImages: SHOW_IMAGES.HIDE, } as MailSettings; const { showEmbeddedImages, embeddedImages, hasEmbeddedImages } = await setup(message, mailSettings); expect(showEmbeddedImages).toBeFalsy(); expect(hasEmbeddedImages).toBeTruthy(); expect(embeddedImages[0].attachment.Headers?.['content-id']).toEqual(cid); expect(embeddedImages[0].cid).toEqual(cid); expect(embeddedImages[0].cloc).toEqual(''); expect(embeddedImages[0].type).toEqual('embedded'); }); });
3,934
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformEscape.test.ts
import { base64Cache, clearAll } from '../../test/helper'; import { attachBase64, transformEscape } from '../transformEscape'; describe('transformEscape', () => { const babase64 = `src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAABoIAAAVSCAYAAAAisOk2AAAMS2lDQ1BJQ0MgUHJv ZmlsZQAASImVVwdYU8kWnltSSWiBUKSE3kQp0qWE0CIISBVshCSQUGJMCCJ2FlkF 1y4ioK7oqoiLrgWQtaKudVHs/aGIysq6WLCh8iYF1tXvvfe9831z758z5/ynZO69 MwDo1PKk0jxUF4B8SYEsITKUNTEtnUXqAgSgD1AwGozk8eVSdnx8DIAydP+nvLkO"`; const DOM = ` <section> <svg id="svigi" width="5cm" height="4cm" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <image xlink:href="firefox.jpg" x="0" y="0" height="50px" width="50px" /> <image xlink:href="chrome.jpg" x="0" y="0" height="50px" width="50px" /> <image href="svg-href.jpg" x="0" y="0" height="50px" width="50px" /> </svg> <video src="fichiervideo.webm" autoplay poster="vignette.jpg"> </video> <div> <img border="0" usemap="#fp" src="cats.jpg "> <map name="fp"> <area coords="0,0,800,800" href="proton_exploit.html" shape="rect" target="_blank" > </map> </div> <video src="fichiervideo.webm" autoplay poster="vignette2.jpg"> </video> <img src="mon-image.jpg" srcset="mon-imageHD.jpg 2x" width="" height="" alt=""> <img src="lol-image.jpg" srcset="lol-imageHD.jpg 2x" width="" height="" alt=""> <img data-src="lol-image.jpg" width="" height="" alt=""> <a href="lol-image.jpg">Alll</a> <a href="jeanne-image.jpg">Alll</a> <div background="jeanne-image.jpg">Alll</div> <div background="jeanne-image2.jpg">Alll</div> <p style="font-size:10.0pt;font-family:\\2018Calibri\\2019;color:black"> Example style that caused regexps to crash </p> <img id="babase64" ${babase64}/> </section> `; const CODE_HTML_HIGHLIGHT = ` <div style="white-space: normal;" class="pre"><div style="color: #fff;max-inline-size: 100%;font-size: 16px;line-height: 1.3;" class="code"><span style="color: #DDDDDF;" class="nt">&lt;script</span> <span style="color: #84868B;" class="na">src="</span><span style="color: #68BEA2;" class="s"><span class="s">https<span>://</span>use.fontawesome<span>.</span>com/f0d8991ea9.js</span><span style="color: #84868B;" class="na">"</span><span style="color: #DDDDDF;" class="nt">&gt;</span><span style="color: #DDDDDF;" class="nt">&lt;/script&gt;</span></span></div></div><div class="pre"></div> `; const HTML_LINKS = ` <div> <a href="http://www.dewdwesrcset-dewdw.com/?srcset=de&srcset=Dewdwe"></a> <a href="http://www.dewdwesrc-dewdw.com/?src=de&src=Dewdwe"></a> <a href="http://www.dewdwebackground-dewdw.com/?background=de&background=Dewdwe"></a> <a href="http://www.dewdweposter-dewdw.com/?poster=de&poster=Dewdwe"></a> <a href="http://www.google.nl/?url=a"></a> <a href="http://www.google.nl/?src=a&srcset=dew"></a> </div> `; const CODE_HTML = '<pre><code><img src="polo.fr"></code></pre>'; const CODE_HTML_ESCAPED = '<pre><code><img proton-src="polo.fr"></code></pre>'; const CODE_TEXT = "<pre><code>{ background: url('monique.jpg') }</code></pre>"; const TEXT = '<p>salut monique est ceque tu as un src="lol" dans la poche ?</p><span>src=</span>'; const EDGE_CASE = '<div id="ymail_android_signature"><a href="https://overview.mail.yahoo.com/mobile/?.src=Android">Sent from Yahoo Mail on Android</a></div>'; const EDGE_CASE_2 = ` webEngineView->setUrl(" <span>webEngineView->setUrl("</span> <div>webEngineView->setUrl("</div> <pre>webEngineView->setUrl("</pre> <code>webEngineView->setUrl(".</code> `; const EX_URL = '<div style="background: url(\'https://i.imgur.com/WScAnHr.jpg\')">ddewdwed</div>'; const EX_URL_CLEAN = '<div style="background: proton-url(\'https://i.imgur.com/WScAnHr.jpg\')">ddewdwed</div>'; const BACKGROUND_URL = ` <div style="background: url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</div> <div style="color: red; background: #ffffff url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</div> <div style="color: red; background: url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</div> <div style="color: red; background:url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</div> <span style="color: red; background:url('https://i.imgur.com/WScAnHr.jpg')">ddewdwed</span>`; const BACKGROUND_URL_ESCAPED_WTF = '<div style="inline-size: 500px; block-size: 500px; background:u\\rl(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div>'; // DON'T REMOVE THEM const BACKGROUND_URL_ESCAPED_WTF2 = ` <div style="inline-size: 500px; block-size: 500px; background:url(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; background:u&#114;l(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; background:ur&#108;(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> `; const BACKGROUND_URL_ESCAPED = ` <div style="inline-size: 500px; block-size: 500px; background:&#117;rl(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; background:&#117;rl(&quot;https://i.imgur.com/WScAnHr.jpg&quot;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; background:&#117;rl(&apos;https://i.imgur.com/WScAnHr.jpg&apos;)">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; content: &quot; ass &quot;; background:url(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; content: &quot; ass &quot;; background:url(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 120px; content: &quot; ass &quot;; background:&#117;&#114;&#108;(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 120px; content: &quot; ass &quot;; background:&#117;r&#108;(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 120px; content: &quot; ass &quot;; background: u&#114l(https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; content: &quot; ass &quot;; background:url&#x00028;https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 500px; content: &quot; ass &quot;; background:url&lpar;https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> <div style="inline-size: 500px; block-size: 456px; content: &quot; ass &quot;; background:url&#40;https://i.imgur.com/WScAnHr.jpg);">ddewdwed</div> `; const BACKGROUND_URL_OCTAL_HEX_ENCODING = ` <div style="background: \\75&#114\\6C('https://TRACKING1/')">test1</div> <div style="background: \\75&#114;\\6C('https://TRACKING2/')">test2</div> <div style="background: \\75r&#108('https://TRACKING3/')">test3</div> <div style="background: &#117r\\6c('https://TRACKING4/')">test4</div> <div style="background: \\75 \\72 \\6C ('https://TRACKING5/')">test5</div> <div style="background: \\75\\72\\6c ('https://TRACKING6/')">test6</div> <div style="background: \\75\\72\\6C('https://TRACKING7/')">test7</div> <div style="background: \\75\\72\\6c('https://TRACKING8/')">test8</div> <div style="background: \x75\x72\x6C('https://TRACKING9/')">test9</div> <div style="background: \u0075\u0072\u006c('https://TRACKING10/')">test10</div> <div style="background: &#x75r\\6c('https://TRACKING11/')">test11</div> <div style="background: \\75&#x72;\\6C('https://TRACKING12/')">test12</div> <div style="background: \\75r&#x6c;('https://TRACKING13/')">test13</div> <div style="background: \\75r&#x6c;('https://TRACKING14/')">test14</div> `; const BACKGROUND_URL_SAFE = ` <span>url('dewd')</span> <span>style="dewdw" url('dewd')</span> <span>dew style="dewdw" url('dewd')</span> <span>dew style="dewdw": url(</span> <span>dew style="content: \\"a\\"": url(</span> <span>dew style="content: 'a": url(</span> <span>dew style="content: \\"a": url(</span> `; // TODO: Fix those 2 // <div style="inline-size: 500px; block-size: 500px; content: &quot; background:url(test)&quot;">ddewdwed</div> // <div style="inline-size: 500px; block-size: 500px; content: &apos; background:url(test)&apos;">ddewdwed</div> // Firefox support image-set :/ // https://jira.protontech.ch/browse/MAILWEB-2993 const BACKGROUND_IMAGE_SET = ` <div style='background: image-set("https://TRACKING/");'> `; // That's a nasty one! const BACKGROUND_DOUBLE_ESCAPING = ` <div style="background: ur\\\\5C\\\\6C(https://TRACKING/); /* url( */"></div> `; const setup = (content = DOM) => { const doc = transformEscape(content, base64Cache); const querySelector = (selectors: string) => doc.querySelector(selectors); const querySelectorAll = (selectors: string) => [...doc.querySelectorAll(selectors)]; return { document: doc, querySelector, querySelectorAll }; }; afterEach(clearAll); describe('Replace base64', () => { describe('No syntax hightlighting', () => { const getBase64Image = () => { const { querySelector } = setup(); return querySelector('img[data-proton-replace-base]') as HTMLImageElement; }; it('should remove the base64 from src', () => { const image = getBase64Image(); expect(image.src).toBe(''); expect(image.hasAttribute('src')).toBe(false); }); it('should add a custom marker attribute', () => { const image = getBase64Image(); expect(image.hasAttribute('data-proton-replace-base')).toBe(true); expect(image.getAttribute('data-proton-replace-base')).not.toBe(''); }); it('should add a custom marker attribute with a hash available inside the cache', () => { const image = getBase64Image(); const [hash] = base64Cache.keys(); expect(image.getAttribute('data-proton-replace-base')).toBe(hash); expect(base64Cache.get(hash)).toBe(babase64); }); it('should attach the base64', () => { const { document, querySelector } = setup(); attachBase64(document, base64Cache); const image = querySelector('img[src*=base64]') as HTMLImageElement; expect(image.hasAttribute('data-proton-replace-base')).toBe(false); expect(image.hasAttribute('src')).toBe(true); const value = babase64.replace(/^src="/, '').slice(0, 20); expect(image.src.startsWith(value)).toBe(true); }); }); describe('Syntax hightlighting', () => { it('should not escape inside a <code> tag', () => { const { document } = setup(CODE_HTML_HIGHLIGHT); expect(document.innerHTML).not.toMatch(/proton-/); }); }); }); describe('Escape <pre>', () => { describe('No syntax hightlighting', () => { it('should escape inside a <code> tag', () => { const { querySelector } = setup(CODE_HTML); expect(querySelector('body')?.innerHTML).toBe(CODE_HTML_ESCAPED); }); it('should not escape text inside a <code> tag', () => { const { querySelector } = setup(CODE_TEXT); expect(querySelector('body')?.innerHTML).toBe(CODE_TEXT); }); }); describe('Syntax hightlighting', () => { it('should not escape inside a <code> tag', () => { const { document } = setup(CODE_HTML_HIGHLIGHT); expect(document.innerHTML).not.toMatch(/proton-/); }); }); }); describe('Escape everything with proton-', () => { const getAttribute = (attribute: string) => { const { querySelectorAll } = setup(); return querySelectorAll(`[${attribute}]`); }; describe('Add a prefix', () => { it('should not add the prefix before href on a link', () => { const list = getAttribute('proton-href'); expect(list.filter((element) => element.tagName === 'A').length).toBe(0); }); it('should add the prefix before src', () => { const list = getAttribute('proton-src'); expect(list.length).toBe(5); }); it('should add the prefix before data-src', () => { const list = getAttribute('proton-data-src'); expect(list.length).toBe(1); }); it('should add the prefix before srcset', () => { const list = getAttribute('proton-srcset'); expect(list.length).toBe(2); }); it('should add the prefix before background', () => { const list = getAttribute('proton-background'); expect(list.length).toBe(2); }); it('should add the prefix before poster', () => { const list = getAttribute('proton-poster'); expect(list.length).toBe(2); }); }); describe('SVG have been totally discontinuated, should be removed, not prefixed!', () => { it('should not add the prefix for SVG', () => { const { querySelectorAll } = setup(); const list = querySelectorAll('proton-svg'); expect(list.length).toBe(0); }); it('should not add the prefix for xlink:href', () => { const { document } = setup(); const list = document.innerHTML.match(/proton-xlink:href/g); expect(list?.length).toBeUndefined(); }); it('should not add the prefix for svg href', () => { const { querySelector } = setup(); const svgHref = querySelector('[proton-href="svg-href.jpg"]'); expect(svgHref).toBe(null); }); }); describe('Excape all the things !', () => { it('should have escaped every src', () => { const list = getAttribute('src'); expect(list.length).toBe(0); }); it('should have escaped every srcset', () => { const list = getAttribute('srcset'); expect(list.length).toBe(0); }); it('should have escaped every background', () => { const list = getAttribute('background'); expect(list.length).toBe(0); }); it('should have escaped every poster', () => { const list = getAttribute('poster'); expect(list.length).toBe(0); }); it('should have escaped every SVG', () => { const { querySelectorAll } = setup(); const list = querySelectorAll('svg'); expect(list.length).toBe(0); }); }); }); describe('No escape inside URL', () => { it('should not escape the content of an anchor tag', () => { const { document } = setup(HTML_LINKS); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('No escape TXT', () => { it('should not escape txt', () => { const { document } = setup(TEXT); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('No escape EDGE_CASE', () => { it('should not escape EDGE_CASE', () => { const { document } = setup(EDGE_CASE); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('No escape EDGE_CASE2', () => { it('should not escape EDGE_CASE', () => { const { document } = setup(EDGE_CASE_2); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('No double escape', () => { it('should not double escape attributes', () => { const { document } = setup(DOM); expect(document.innerHTML).not.toMatch(/proton-proton-/); }); }); describe('Escape BACKGROUND_URL', () => { const getList = (content: string) => { const { querySelector } = setup(content); return ( querySelector('body') ?.innerHTML.split('\n') .map((s) => s.trim()) .filter(Boolean) || [] ); }; it('should escape all', () => { const list = getList(BACKGROUND_URL); list.forEach((key) => expect(key).toMatch(/proton-/)); }); it('should escape all encoded url', () => { const list = getList(BACKGROUND_URL_ESCAPED); list.forEach((key) => expect(key).toMatch(/proton-/)); }); it('should escape encoded url with escape \\r', () => { const { document } = setup(BACKGROUND_URL_ESCAPED_WTF); expect(document.innerHTML).toMatch(/proton-/); }); it('should escape encoded url with escape standard wtf', () => { const list = getList(BACKGROUND_URL_ESCAPED_WTF2); list.forEach((key) => expect(key).toMatch(/proton-/)); }); it('should escape octal and hex encoded urls with escape', () => { const list = getList(BACKGROUND_URL_OCTAL_HEX_ENCODING); list.forEach((key) => expect(key).toMatch(/proton-/)); }); it('should not break the HTML', () => { const { querySelector } = setup(EX_URL); expect(querySelector('body')?.innerHTML).toEqual(EX_URL_CLEAN); }); }); describe('base handling', () => { it('Should preserve <base href> in <head>', () => { const BASE = `<head><base href="https://bugzilla.mozilla.org/"></head>`; const { document, querySelector } = setup(BASE); expect(document.innerHTML).toMatch(/<base/); const base = querySelector('base'); expect(base).toBeTruthy(); expect(base?.getAttribute('href')).toEqual('https://bugzilla.mozilla.org/'); }); }); describe('Not escape BACKGROUND_URL', () => { it('should not escape anything', () => { const { document } = setup(BACKGROUND_URL_SAFE); expect(document.innerHTML).not.toMatch(/proton-/); }); }); describe('Escape BACKGROUND_IMAGE_SET', () => { it('should escape image-set', () => { const { document } = setup(BACKGROUND_IMAGE_SET); expect(document.innerHTML).toMatch(/proton-/); }); }); describe('Escape BACKGROUND_DOUBLE_ESCAPING', () => { it('should escape double escaping', () => { const { document } = setup(BACKGROUND_DOUBLE_ESCAPING); expect(document.innerHTML).toMatch(/proton-url\(https/); }); }); });
3,935
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformLinks.test.ts
import { transformLinks } from '../transformLinks'; describe('transformLinks service', () => { const ADD_REF = ` <a href="#lol" id="anchorLink">anchor</a> <a href="" id="emptyLink">nada</a> <a href="/monique">relative</a> <a href="https://lol.jpg">https</a> <a href="http://lol.jpg">http</a> <a href="ftp://lol.jpg">ftp</a> <a href="xmpp://lol.jpg">xmpp</a> <a href="tel://lol.jpg">tel</a> <a href="callto://lol.jpg">callto</a> <a href="mailto://lol.jpg">mailto</a> <a href="https://ads.com?utm_content=toto">utm</a> <div href id="hrefLink">xxxx</div> `; const EMPTY_LINK = '<a>anchor</a>'; const setup = (content = ADD_REF) => { const doc = document.createElement('DIV'); doc.innerHTML = content; transformLinks(doc, jest.fn(), true); const querySelector = (selectors: string) => doc.querySelector(selectors); const querySelectorAll = (selectors: string) => [...doc.querySelectorAll(selectors)]; return { document: doc, querySelector, querySelectorAll }; }; describe('Improve privacy', () => { const TOTAL = ADD_REF.split('\n') .map((s) => s.trim()) .filter(Boolean).length; it('should add referrer', () => { const { querySelectorAll } = setup(); expect(querySelectorAll('[rel="noreferrer nofollow noopener"]').length).toEqual(TOTAL); }); it('should add target for real link', () => { const { querySelectorAll } = setup(); expect(querySelectorAll('[target="_blank"]').length).toEqual(4); expect(querySelectorAll('[href^="http"][target="_blank"]').length).toEqual(4); }); it('should strip tracking parameters (utm)', () => { const { querySelector } = setup(ADD_REF); expect(querySelector('[href="https://ads.com/"]')).toBeTruthy(); expect(querySelector('[href*="utm_content=toto"]')).toBeFalsy(); }); }); describe('Fix links', () => { it('should add domain in from of the link relative', () => { const { querySelector } = setup(ADD_REF + EMPTY_LINK); expect(querySelector('[href="http:///monique"]')).toBeTruthy(); }); it('should not do anything for an empty anchor tag', () => { const { querySelector } = setup(ADD_REF + EMPTY_LINK); expect(querySelector('a:not([href])')?.outerHTML).toEqual(EMPTY_LINK); }); it('should add pointerEvents to an empty anchor or invalid', () => { const { querySelector, querySelectorAll } = setup(ADD_REF + EMPTY_LINK); expect(querySelectorAll('[style]').length).toBe(2); expect((querySelector('#emptyLink') as HTMLElement).style.pointerEvents).toBe('none'); expect((querySelector('#hrefLink') as HTMLElement).style.pointerEvents).toBe('none'); }); it('should not escape the anchor link', () => { const { querySelector } = setup(ADD_REF + EMPTY_LINK); expect(querySelector('#anchorLink')?.hasAttribute('style')).toBe(false); }); }); });
3,936
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformRemote.test.ts
import { wait } from '@proton/shared/lib/helpers/promise'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { IMAGE_PROXY_FLAGS, SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { createDocument } from '../../test/message'; import { transformRemote } from '../transformRemote'; describe('transformRemote', () => { let onLoadRemoteImagesProxy: jest.Mock; let onLoadFakeImagesProxy: jest.Mock; let onLoadRemoteImagesDirect: jest.Mock; const setup = (message: MessageState, mailSettings: MailSettings) => { onLoadRemoteImagesProxy = jest.fn(); onLoadFakeImagesProxy = jest.fn(); onLoadRemoteImagesDirect = jest.fn(); return transformRemote( message, mailSettings, onLoadRemoteImagesDirect, onLoadRemoteImagesProxy, onLoadFakeImagesProxy ); }; it('should detect remote images', async () => { const imageURL = 'imageURL'; const imageBackgroundURL = 'http://domain.com/image.jpg'; const content = `<div> <img proton-src='${imageURL}'/> </div> <div style="background: proton-url(${imageBackgroundURL})" /> `; const message: MessageState = { localID: 'messageWithRemote', data: { ID: 'messageID', } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideRemoteImages: SHOW_IMAGES.SHOW, } as MailSettings; const { showRemoteImages, remoteImages, hasRemoteImages } = setup(message, mailSettings); expect(showRemoteImages).toBeTruthy(); expect(hasRemoteImages).toBeTruthy(); expect(remoteImages[0].type).toEqual('remote'); expect(remoteImages[0].url).toEqual(imageURL); expect(remoteImages[1].type).toEqual('remote'); expect(remoteImages[1].url).toEqual(imageBackgroundURL); }); it('should load remote images through proxy', async () => { const imageURL = 'imageURL'; const imageBackgroundURL = 'http://domain.com/image.jpg'; const content = `<div> <img proton-src='${imageURL}'/> </div> <div style="background: proton-url(${imageBackgroundURL})" /> `; const message: MessageState = { localID: 'messageWithRemote', data: { ID: 'messageID', } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideRemoteImages: SHOW_IMAGES.SHOW, ImageProxy: IMAGE_PROXY_FLAGS.PROXY, } as MailSettings; const { showRemoteImages, remoteImages, hasRemoteImages } = setup(message, mailSettings); expect(showRemoteImages).toBeTruthy(); expect(hasRemoteImages).toBeTruthy(); expect(remoteImages[0].type).toEqual('remote'); expect(remoteImages[0].url).toEqual(imageURL); expect(remoteImages[1].type).toEqual('remote'); expect(remoteImages[1].url).toEqual(imageBackgroundURL); // There is a wait 0 inside the loadRemoteImages helper await wait(0); expect(onLoadRemoteImagesProxy).toHaveBeenCalled(); }); it('should load remote images by default whatever the loading setting value when Sender is Proton verified', async () => { const imageURL = 'imageURL'; const content = `<div> <img proton-src='${imageURL}'/> </div>`; const message: MessageState = { localID: 'messageWithRemote', data: { ID: 'messageID', Sender: { Name: 'Verified address', Address: 'verified@proton.me', IsProton: 1, }, } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY, } as MailSettings; const { showRemoteImages, remoteImages, hasRemoteImages } = setup(message, mailSettings); expect(showRemoteImages).toBeTruthy(); expect(hasRemoteImages).toBeTruthy(); expect(remoteImages[0].type).toEqual('remote'); expect(remoteImages[0].url).toEqual(imageURL); // There is a wait 0 inside the loadRemoteImages helper await wait(0); expect(onLoadRemoteImagesProxy).toHaveBeenCalled(); }); it('should not load remote images by default when setting is off and address is not Proton verified', async () => { const imageURL = 'imageURL'; const content = `<div> <img proton-src='${imageURL}'/> </div>`; const message: MessageState = { localID: 'messageWithRemote', data: { ID: 'messageID', Sender: { Name: 'normal address', Address: 'normal@proton.me', IsProton: 0, }, } as Message, messageDocument: { document: createDocument(content) }, }; const mailSettings = { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY, } as MailSettings; const { showRemoteImages, remoteImages, hasRemoteImages } = setup(message, mailSettings); expect(showRemoteImages).toBeFalsy(); expect(hasRemoteImages).toBeTruthy(); expect(remoteImages[0].type).toEqual('remote'); expect(remoteImages[0].url).toEqual(imageURL); // There is a wait 0 inside the loadRemoteImages helper await wait(0); expect(onLoadRemoteImagesProxy).not.toHaveBeenCalled(); }); });
3,937
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/transforms/tests/transformStyleAttributes.test.ts
import { transformStyleAttributes } from '../transformStyleAttributes'; describe('transformStyleAttributes', () => { const setup = () => { const doc = document.implementation.createHTMLDocument('test transform style attribute'); return doc; }; describe('Transform `vh` height property', () => { it('Should remove VH from style attributes with height containing vh unit', () => { const document = setup(); document.write(` <div id="a" style="margin: 0; width: 100vh; height: 100vh;"> <div id="b" style="margin: 0; width: 100px; height: 100px;"> <span id="c" style="margin: 0; width: 100px; height: 100vh;"></span> </div> </div> `); let a = document.getElementById('a'); let b = document.getElementById('b'); let c = document.getElementById('c'); expect(a?.style.height).toBe('100vh'); expect(a?.style.width).toBe('100vh'); expect(a?.style.margin).toBe('0px'); expect(b?.style.height).toBe('100px'); expect(b?.style.width).toBe('100px'); expect(b?.style.margin).toBe('0px'); expect(c?.style.height).toBe('100vh'); expect(c?.style.width).toBe('100px'); expect(c?.style.margin).toBe('0px'); transformStyleAttributes(document as unknown as Element); expect(a?.style.height).toBe('auto'); expect(a?.style.width).toBe('100vh'); expect(a?.style.margin).toBe('0px'); expect(b?.style.height).toBe('100px'); expect(b?.style.width).toBe('100px'); expect(b?.style.margin).toBe('0px'); expect(c?.style.height).toBe('auto'); expect(c?.style.width).toBe('100px'); expect(c?.style.margin).toBe('0px'); }); }); });
3,938
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useAddressesInputDrag.ts
import { Dispatch, DragEvent, RefObject, SetStateAction, useEffect, useState } from 'react'; import { generateUID, useCache, useDragOver, useHandler } from '@proton/components'; import { Recipient } from '@proton/shared/lib/interfaces'; import { DRAG_ADDRESS_KEY } from '../constants'; import { matchRecipientOrGroup, recipientOrGroupToRecipients } from '../helpers/message/messageRecipients'; import { RecipientOrGroup } from '../models/address'; export const ADDRESS_DRAG_CACHE_KEY = 'ADDRESS_DRAG'; interface DragInfo { inputID: string; recipient: RecipientOrGroup; size: { width: number; height: number }; } enum DragStatus { Success = 'success', None = 'none', } interface DragCacheEntry { dragInfo?: DragInfo; dragStatus?: DragStatus; } interface UseAddressesInputDrag { ( recipientsOrGroups: RecipientOrGroup[], setRecipientsOrGroups: Dispatch<SetStateAction<RecipientOrGroup[]>>, onChange: (value: Recipient[]) => void ): { draggedRecipient: RecipientOrGroup | undefined; placeholderPosition: number | undefined; placeholderSize: { width: number; height: number } | undefined; containerDragHandlers: { onDragEnter: (event: DragEvent) => void; onDragLeave: (event: DragEvent) => void; onDragOver: (event: DragEvent) => void; onDrop: (event: DragEvent) => void; }; itemDragHandlers: (recipient: RecipientOrGroup) => { onDragStart: (event: DragEvent) => void; onDragEnd: (event: DragEvent) => void; onDragOver: (ref: RefObject<HTMLDivElement>) => (event: DragEvent) => void; }; }; } export const useAddressesInputDrag: UseAddressesInputDrag = (recipientsOrGroups, setRecipientsOrGroups, onChange) => { const cache = useCache(); const [uid] = useState(generateUID('drag-address')); const [draggedRecipient, setDraggedRecipient] = useState<RecipientOrGroup>(); const [placeholderPosition, setPlaceholderPosition] = useState<number>(); const [placeholderSize, setPlaceholderSize] = useState<{ width: number; height: number }>(); const getCache = () => cache.get(ADDRESS_DRAG_CACHE_KEY) as DragCacheEntry | undefined; const setCache = (entry: DragCacheEntry) => cache.set(ADDRESS_DRAG_CACHE_KEY, entry); const handleContainerDrop = () => { const dragInfo = getCache()?.dragInfo as DragInfo; const draggedRecipient = dragInfo.recipient; const newRecipients = recipientsOrGroups.filter( (recipientOrGroup) => !matchRecipientOrGroup(recipientOrGroup, draggedRecipient) ); newRecipients.splice(placeholderPosition as number, 0, draggedRecipient); setCache({ dragStatus: DragStatus.Success }); setRecipientsOrGroups(newRecipients); onChange(recipientOrGroupToRecipients(newRecipients)); setDraggedRecipient(undefined); setPlaceholderPosition(undefined); }; const handleContainerDragLeave = () => { setPlaceholderPosition(undefined); }; const handleContainerDragEnter = () => { const dragInfo = getCache()?.dragInfo as DragInfo; setPlaceholderPosition(0); setPlaceholderSize(dragInfo.size); setCache({ dragInfo: { ...dragInfo, inputID: uid } }); }; const [, containerDragHandlers] = useDragOver( (event) => event.dataTransfer.types.includes(DRAG_ADDRESS_KEY), 'move', { onDragEnter: handleContainerDragEnter, onDragLeave: handleContainerDragLeave, onDrop: handleContainerDrop, } ); const handleItemDragStart = (recipient: RecipientOrGroup) => (event: DragEvent) => { event.dataTransfer.setData(DRAG_ADDRESS_KEY, 'true'); setDraggedRecipient(recipient); setPlaceholderPosition(recipientsOrGroups.findIndex((recipientOrGroup) => recipientOrGroup === recipient)); // Has to be in position on drag start unless it animates to the cursor // After that, we want the element hidden... const target = event.target as HTMLElement; target.style.top = `${target.offsetTop}px`; target.style.left = `${target.offsetLeft}px`; setTimeout(() => { target.style.top = '-100000px'; target.style.left = '-100000px'; }); const position = target.getBoundingClientRect(); const size = { width: position.width, height: position.height }; setPlaceholderSize(size); setCache({ dragInfo: { inputID: uid, recipient, size } }); }; const handleItemDragEndParsed = (dragStatus: DragStatus) => { if (dragStatus === DragStatus.Success && draggedRecipient !== undefined) { const newRecipients = recipientsOrGroups.filter( (recipientOrGroup) => !matchRecipientOrGroup(recipientOrGroup, draggedRecipient as RecipientOrGroup) ); setRecipientsOrGroups(newRecipients); onChange(recipientOrGroupToRecipients(newRecipients)); } setDraggedRecipient(undefined); setPlaceholderPosition(undefined); }; const handleItemDragEnd = (event: DragEvent) => { const dragStatus = event.dataTransfer.dropEffect === 'move' ? DragStatus.Success : DragStatus.None; handleItemDragEndParsed(dragStatus); setCache({ dragStatus }); }; const handleItemDragOverThrottled = useHandler( (recipient: RecipientOrGroup, ref: RefObject<HTMLDivElement>, event: DragEvent) => { if (!ref.current) { return; } const recipientIndex = recipientsOrGroups.findIndex((recipientOrGroup) => recipientOrGroup === recipient); const refPosition = ref.current.getBoundingClientRect(); const middleX = refPosition.left + (refPosition.right - refPosition.left) / 2; if (event.clientX < middleX && placeholderPosition !== recipientIndex) { setPlaceholderPosition(recipientIndex); } if (event.clientX >= middleX && placeholderPosition !== recipientIndex + 1) { setPlaceholderPosition(recipientIndex + 1); } }, { throttle: 100 } ); const handleItemDragOver = (recipient: RecipientOrGroup) => (ref: RefObject<HTMLDivElement>) => (event: DragEvent) => handleItemDragOverThrottled(recipient, ref, event); const cacheListener = useHandler((changedKey) => { if (changedKey === ADDRESS_DRAG_CACHE_KEY && placeholderPosition !== undefined) { const cacheEntry = getCache(); if (cacheEntry?.dragInfo && cacheEntry.dragInfo.inputID !== uid) { handleContainerDragLeave(); } if (cacheEntry?.dragStatus) { handleItemDragEndParsed(cacheEntry.dragStatus); } } }); useEffect(() => cache.subscribe(cacheListener), [cache]); return { draggedRecipient, placeholderPosition, placeholderSize, containerDragHandlers, itemDragHandlers: (recipient: RecipientOrGroup) => ({ onDragStart: handleItemDragStart(recipient), onDragEnd: handleItemDragEnd, onDragOver: handleItemDragOver(recipient), }), }; };
3,939
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useBase64Cache.ts
import { useCache } from '@proton/components'; import createCache, { Cache } from '@proton/shared/lib/helpers/cache'; const CACHE_KEY = 'Base64'; export type Base64Cache = Cache<string, string>; export const useBase64Cache = (): Base64Cache => { const globalCache = useCache(); if (!globalCache.has(CACHE_KEY)) { globalCache.set(CACHE_KEY, createCache()); } return globalCache.get(CACHE_KEY); };
3,940
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useBlockSender.tsx
import { MouseEvent, useMemo } from 'react'; import { c } from 'ttag'; import { useModalTwo } from '@proton/components/components/modalTwo/useModalTwo'; import { useAddresses, useApi, useNotifications } from '@proton/components/hooks'; import { updateBlockSenderConfirmation } from '@proton/shared/lib/api/mailSettings'; import { BLOCK_SENDER_CONFIRMATION } from '@proton/shared/lib/mail/constants'; import useMailModel from 'proton-mail/hooks/useMailModel'; import BlockSenderModal from '../components/message/modals/BlockSenderModal'; import { getSendersToBlock } from '../helpers/message/messageRecipients'; import { addBlockAddresses } from '../logic/incomingDefaults/incomingDefaultsActions'; import { useAppDispatch } from '../logic/store'; import { Element } from '../models/element'; import { useIncomingDefaultsAddresses, useIncomingDefaultsStatus } from './incomingDefaults/useIncomingDefaults'; interface Props { elements: Element[]; onCloseDropdown?: () => void; } const useBlockSender = ({ elements, onCloseDropdown }: Props) => { const api = useApi(); const dispatch = useAppDispatch(); const [addresses] = useAddresses(); const mailSettings = useMailModel('MailSettings'); const { createNotification } = useNotifications(); const incomingDefaultsAddresses = useIncomingDefaultsAddresses(); const incomingDefaultsStatus = useIncomingDefaultsStatus(); const [blockSenderModal, handleShowBlockSenderModal] = useModalTwo(BlockSenderModal); const senders = useMemo(() => { return getSendersToBlock(elements, incomingDefaultsAddresses, addresses); }, [elements, incomingDefaultsAddresses, addresses]); // We can display the block sender option if: // 1 - The feature flag is enabled // 3 - Incoming defaults addresses are loaded // 2 - The sender is not already blocked => Should be filtered from senders // 4 - The message is not sent by the user, we don't want to block self addresses => Should be filtered from senders const canShowBlockSender = incomingDefaultsStatus === 'loaded' && senders.length > 0; const handleBlockSender = (): Promise<void> => { if (!senders || senders.length === 0) { return Promise.resolve(); } const firstSenderAddress = senders[0]?.Address; // translator: The variable contains the address of the sender which will be blocked const successNotificationMessage = senders.length === 1 ? c('Notification').t`Sender ${firstSenderAddress} blocked` : c('Notification').t`Senders blocked`; return dispatch(addBlockAddresses({ addresses: senders.map((sender) => sender.Address), overwrite: true })) .unwrap() .then(() => { createNotification({ text: successNotificationMessage }); }); }; // Confirm blocking address from the modal const handleSubmitBlockSender = async (checked: boolean) => { const isSettingChecked = mailSettings.BlockSenderConfirmation === BLOCK_SENDER_CONFIRMATION.DO_NOT_ASK; const confirmHasChanged = checked !== isSettingChecked; if (confirmHasChanged) { await api(updateBlockSenderConfirmation(checked ? BLOCK_SENDER_CONFIRMATION.DO_NOT_ASK : null)); } await handleBlockSender(); }; // The user click on block sender option/action const handleClickBlockSender = async (event?: MouseEvent) => { event?.stopPropagation(); // Close dropdown in order to avoid having modal and dropdown opened at same time onCloseDropdown?.(); if (mailSettings.BlockSenderConfirmation !== BLOCK_SENDER_CONFIRMATION.DO_NOT_ASK) { await handleShowBlockSenderModal({ onConfirm: handleSubmitBlockSender, senders, mailSettings }); } else { void handleBlockSender(); } }; return { canShowBlockSender, incomingDefaultsStatus, handleClickBlockSender, blockSenderModal }; }; export default useBlockSender;
3,941
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useClickMailContent.tsx
import { ReactNode, RefObject, createContext, useContext, useEffect } from 'react'; import { useHandler } from '@proton/components'; const MailContentRefContext = createContext<RefObject<HTMLDivElement>>(null as any); /** * Call the handler whenever the user click on the mail app content * but not on any kind of modal / notification / composer window */ export const useClickMailContent = (handler: (event: Event) => void) => { const stableHandler = useHandler(handler); const mailContentRef = useContext(MailContentRefContext); // mousedown and touchstart avoid issue with the click in portal (modal, notification, composer, dropdown) useEffect(() => { mailContentRef.current?.addEventListener('mousedown', stableHandler, { passive: true }); mailContentRef.current?.addEventListener('touchstart', stableHandler, { passive: true }); return () => { mailContentRef.current?.removeEventListener('mousedown', stableHandler); mailContentRef.current?.removeEventListener('touchstart', stableHandler); }; }, []); }; interface Props { children: ReactNode; mailContentRef: RefObject<HTMLDivElement>; } export const MailContentRefProvider = ({ children, mailContentRef }: Props) => { return <MailContentRefContext.Provider value={mailContentRef}>{children}</MailContentRefContext.Provider>; };
3,942
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useDebouncedAction.ts
import { useRef } from 'react'; import debounce from '@proton/utils/debounce'; export const useDebouncedAction = (action: () => void, wait = 1000) => { return useRef(() => debounce(action, wait)); };
3,943
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useDeepMemo.ts
import { DependencyList, useMemo, useRef } from 'react'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; /** * Special performance oriented useMemo which will store the previous value, * Compare deeply a new one to the previous and keep the reference if there is no changes */ export const useDeepMemo = <T>(factory: () => T, deps: DependencyList): T => { const previousValue = useRef<T>(); return useMemo(() => { const newValue = factory(); if (isDeepEqual(newValue, previousValue.current)) { return previousValue.current as T; } previousValue.current = newValue; return newValue; }, deps); };
3,944
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useDelaySendSeconds.tsx
import { DELAY_IN_SECONDS } from '@proton/shared/lib/mail/mailSettings'; import useMailModel from 'proton-mail/hooks/useMailModel'; const useDelaySendSeconds = () => { const { DelaySendSeconds = DELAY_IN_SECONDS.NONE } = useMailModel('MailSettings'); return DelaySendSeconds; }; export default useDelaySendSeconds;
3,945
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useDraft.tsx
import { useCallback, useEffect } from 'react'; import { generateUID, useAddresses, useCache, useGetAddresses, useGetMailSettings, useGetUser, useUserSettings, } from '@proton/components'; import { useModalTwo } from '@proton/components/components/modalTwo/useModalTwo'; import { isPaid } from '@proton/shared/lib/user/helpers'; import useMailModel from 'proton-mail/hooks/useMailModel'; import SendingFromDefaultAddressModal from '../components/composer/modals/SendingFromDefaultAddressModal'; import { MESSAGE_ACTIONS } from '../constants'; import { cloneDraft, createNewDraft } from '../helpers/message/messageDraft'; import { findSender } from '../helpers/message/messageRecipients'; import { createDraft as createDraftAction } from '../logic/messages/draft/messagesDraftActions'; import { MessageState, MessageStateWithData, PartialMessageState } from '../logic/messages/messagesTypes'; import { useAppDispatch } from '../logic/store'; import { useGetAttachment } from './attachments/useAttachment'; const CACHE_KEY = 'Draft'; export const useDraftVerifications = () => { const getAddresses = useGetAddresses(); const getUser = useGetUser(); const [sendingFromDefaultAddressModal, handleShowModal] = useModalTwo(SendingFromDefaultAddressModal); const handleDraftVerifications = useCallback( async (action: MESSAGE_ACTIONS, referenceMessage?: PartialMessageState) => { const [user, addresses] = await Promise.all([getUser(), getAddresses()]); if (!isPaid(user) && findSender(addresses, referenceMessage?.data)?.Email.endsWith('@pm.me')) { const email = findSender(addresses, referenceMessage?.data, true)?.Email; await handleShowModal({ email }); } }, [getUser, getAddresses] ); return { handleDraftVerifications, sendingFromDefaultAddressModal }; }; /** * Hooks to create new draft messages. * It will prepare an empty draft to be quickly reused and create other drafts with helpers */ export const useDraft = () => { const cache = useCache(); const getMailSettings = useGetMailSettings(); const getAddresses = useGetAddresses(); const dispatch = useAppDispatch(); const { handleDraftVerifications: draftVerifications, sendingFromDefaultAddressModal } = useDraftVerifications(); const [addresses] = useAddresses(); const mailSettings = useMailModel('MailSettings'); const [userSettings] = useUserSettings(); const getAttachment = useGetAttachment(); useEffect(() => { const run = async () => { if (!mailSettings || !addresses) { return; } const message = createNewDraft( MESSAGE_ACTIONS.NEW, undefined, mailSettings, userSettings, addresses, getAttachment ); cache.set(CACHE_KEY, message); }; void run(); }, [cache, addresses, mailSettings]); const createDraft = useCallback( async (action: MESSAGE_ACTIONS, referenceMessage?: PartialMessageState, isQuickReply?: boolean) => { const [mailSettings, addresses] = await Promise.all([getMailSettings(), getAddresses()]); await draftVerifications(action, referenceMessage); let message: MessageState; if (action === MESSAGE_ACTIONS.NEW && cache.has(CACHE_KEY) && referenceMessage === undefined) { message = cloneDraft(cache.get(CACHE_KEY) as MessageStateWithData); } else { // This cast is quite dangerous but hard to remove message = createNewDraft( action, referenceMessage, mailSettings, userSettings, addresses, getAttachment, false, isQuickReply ) as MessageState; } message.localID = generateUID('draft'); dispatch(createDraftAction(message)); return message.localID; }, [cache, getMailSettings, getAddresses, draftVerifications] ); return { createDraft, sendingFromDefaultAddressModal }; };
3,946
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useExpiration.ts
import { useEffect, useState } from 'react'; import { differenceInHours, isAfter } from 'date-fns'; import { c } from 'ttag'; import { MINUTE } from '@proton/shared/lib/constants'; import { getAutoDeleteOnMessage, getExpiresOnMessage, getMessageExpirationDate, } from '../helpers/message/messageExpirationTime'; import { MessageState } from '../logic/messages/messagesTypes'; const useExpiration = (message: MessageState, autoDelete = false) => { const [expiresInLessThan24Hours, setExpiresInLessThan24Hours] = useState(false); const [expirationMessage, setExpirationMessage] = useState(''); const expirationDate = getMessageExpirationDate(message); useEffect(() => { const interval = () => { if (!expirationDate) { setExpiresInLessThan24Hours(false); setExpirationMessage(''); return; } const now = new Date(); if (differenceInHours(expirationDate, now) < 24) { setExpiresInLessThan24Hours(true); } if (isAfter(now, expirationDate)) { const message = c('Info').t`The message has expired`; setExpirationMessage(message); return; } if (autoDelete) { setExpirationMessage(getAutoDeleteOnMessage(expirationDate)); return; } setExpirationMessage(getExpiresOnMessage(expirationDate)); }; interval(); const intervalID = window.setInterval(interval, MINUTE); return () => clearInterval(intervalID); }, []); return { expirationMessage, expiresInLessThan24Hours, expirationDate }; }; export default useExpiration;
3,947
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useExpirationCheck.ts
import { serverTime } from 'pmcrypto'; import { useInterval } from '@proton/components'; import { isExpired } from 'proton-mail/helpers/expiration'; import { EXPIRATION_CHECK_FREQUENCY } from '../constants'; import { Element } from '../models/element'; export const useExpirationCheck = (elements: Element[], expiredCallback: (element: Element) => void) => { useInterval(EXPIRATION_CHECK_FREQUENCY, () => { const nowTimestamp = +serverTime(); elements.forEach((element) => { if (isExpired(element, nowTimestamp)) { expiredCallback(element); } }); }); };
3,948
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useExpiringElement.test.ts
import { fromUnixTime, getUnixTime } from 'date-fns'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { renderHook } from 'proton-mail/helpers/test/render'; import { globalReset } from 'proton-mail/logic/actions'; import { MessageState } from 'proton-mail/logic/messages/messagesTypes'; import { initialize } from 'proton-mail/logic/messages/read/messagesReadActions'; import { store } from 'proton-mail/logic/store'; import { Conversation } from 'proton-mail/models/conversation'; import { useExpiringElement } from './useExpiringElement'; // TODO: Remove when global mock is merged (later) class ResizeObserver { observe() {} unobserve() {} disconnect() {} } beforeAll(() => { window.ResizeObserver = ResizeObserver; }); const MESSAGE_ID = 'messageID'; type GetStoreMessageProps = { types: ('withDraftFlagExpiresIn' | 'withDataExpirationTime')[]; /** Unix timestamp */ expirationTime: number; conversationID: string; }; const getStoreMessage = ({ types, expirationTime, conversationID }: Partial<GetStoreMessageProps>) => { return { localID: MESSAGE_ID, data: { ...(conversationID ? { ConversationID: conversationID } : {}), ...(types?.includes('withDataExpirationTime') ? { ExpirationTime: expirationTime } : {}), }, draftFlags: { ...(types?.includes('withDraftFlagExpiresIn') ? { expiresIn: fromUnixTime(expirationTime as number) } : {}), }, } as MessageState; }; describe('useExpiringElement', () => { let dateTimestamp: number; beforeEach(() => { dateTimestamp = getUnixTime(new Date(2023, 7, 27, 0, 0, 0, 0)); }); afterEach(() => { store.dispatch(globalReset()); }); describe('Conversation mode ON', () => { const conversationID = 'conversationID'; const element = { ID: conversationID, } as Conversation; const labelID = '0'; it('Should not have expiration when no `contextExpirationTime` on the Element and no `expiresIn` draftFlag in messages from store', async () => { store.dispatch(initialize(getStoreMessage({ conversationID }))); const result = await renderHook(() => useExpiringElement(element, labelID, true)); expect(result.result.current.hasExpiration).toBe(false); expect(result.result.current.expirationTime).toBe(0); }); it('Should not have expiration with `expirationTime` data in messages from store', async () => { store.dispatch( initialize( getStoreMessage({ conversationID, types: ['withDataExpirationTime'], expirationTime: dateTimestamp, }) ) ); const result = await renderHook(() => useExpiringElement(element, labelID, true)); expect(result.result.current.hasExpiration).toBe(false); expect(result.result.current.expirationTime).toBe(0); }); it('Should have expiration with `contextExpirationTime` on the element', async () => { const result = await renderHook(() => useExpiringElement( { ...element, ContextExpirationTime: dateTimestamp, }, labelID, true ) ); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); it('Should have expiration with `expiresIn` draftFlag in messages from store', async () => { store.dispatch( initialize( getStoreMessage({ conversationID, types: ['withDraftFlagExpiresIn'], expirationTime: dateTimestamp, }) ) ); const result = await renderHook(() => useExpiringElement(element, labelID, true)); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); it('should look for ContextExpirationTime in Labels', async () => { const result = await renderHook(() => useExpiringElement( { ...element, Labels: [ { ID: labelID, ContextExpirationTime: dateTimestamp, }, ], }, labelID, true ) ); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); }); describe('Conversation mode OFF', () => { const element = { ID: MESSAGE_ID, } as Message; const labelID = '0'; it('Should not have expiration when no `ExpirationTime` on the Element and no `ExpirationTime` data or `expiresIn` draftFlag in message store', async () => { store.dispatch(initialize(getStoreMessage({ types: [], expirationTime: dateTimestamp }))); const result = await renderHook(() => useExpiringElement(element, labelID, false)); expect(result.result.current.hasExpiration).toBe(false); expect(result.result.current.expirationTime).toBe(0); }); it('Should have expiration when `ExpirationTime` on the Element', async () => { store.dispatch(initialize(getStoreMessage({ types: [], expirationTime: dateTimestamp }))); const result = await renderHook(() => useExpiringElement( { ...element, ExpirationTime: dateTimestamp, }, labelID, false ) ); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); it('Should have expiration when `expiresIn` is set on the message store draftFlags', async () => { store.dispatch( initialize(getStoreMessage({ types: ['withDraftFlagExpiresIn'], expirationTime: dateTimestamp })) ); const result = await renderHook(() => useExpiringElement(element, labelID, false)); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); it('Should have expiration when `ExpirationTime` is set on the message store data', async () => { store.dispatch( initialize(getStoreMessage({ types: ['withDataExpirationTime'], expirationTime: dateTimestamp })) ); const result = await renderHook(() => useExpiringElement(element, labelID, false)); expect(result.result.current.hasExpiration).toBe(true); expect(result.result.current.expirationTime).toBe(dateTimestamp); }); }); });
3,949
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useExpiringElement.ts
import { useMemo } from 'react'; import { getUnixTime } from 'date-fns'; import { Conversation } from '../models/conversation'; import { Element } from '../models/element'; import { useGetAllMessages, useGetMessage } from './message/useMessage'; const isConversationMode = (element: Element, conversationMode: boolean): element is Conversation => conversationMode; export const useExpiringElement = (element: Element, labelID: string, conversationMode = false) => { const getAllMessages = useGetAllMessages(); const getMessage = useGetMessage(); /** * We need to check if we find an expiration time set in the state. * We could have sent a message recently, and ExpirationTime could not be set already. * If we want to display the expiration icon in the list, we need to check the draft flag in the state */ const expirationTime = useMemo(() => { if (element) { if (isConversationMode(element, conversationMode)) { if (element.ContextExpirationTime) { return element.ContextExpirationTime; } const label = element.Labels?.find((label) => label.ID === labelID); if (label?.ContextExpirationTime) { return label.ContextExpirationTime; } // If the element is a conversation we check all messages to find a message having draft flags and being in the conversation const allMessages = getAllMessages(); const expiringMessageFromConversation = allMessages.find( (message) => message?.data?.ConversationID === element.ID && !!message?.draftFlags?.expiresIn ); const draftExpirationTime = expiringMessageFromConversation?.draftFlags?.expiresIn ? getUnixTime(expiringMessageFromConversation.draftFlags?.expiresIn) : 0; const expirationTime = expiringMessageFromConversation?.data?.ExpirationTime || draftExpirationTime || 0; return expirationTime; } else { if (element.ExpirationTime) { return element.ExpirationTime; } // If the element is a message we check if we have an expiration time in draftFlags const message = getMessage(element.ID); const draftExpirationTime = message?.draftFlags?.expiresIn ? getUnixTime(message.draftFlags?.expiresIn) : 0; const expirationTime = message?.data?.ExpirationTime || draftExpirationTime || 0; return expirationTime; } } return undefined; }, [element, conversationMode]); return { expirationTime, hasExpiration: !!expirationTime && expirationTime > 0, }; };
3,950
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useHasScroll.ts
import { RefObject, useEffect, useState } from 'react'; import { useHandler } from '@proton/components'; import debounce from '@proton/utils/debounce'; export const useHasScroll = (ref: RefObject<HTMLElement>) => { const [hasVerticalScrollbar, setHasVerticalScrollbar] = useState(false); const [hasHorizontalScrollbar, setHasHorizontalScrollbar] = useState(false); const handleResize = useHandler(() => { const element = ref.current; if (!element) { return; } setHasVerticalScrollbar(element.scrollHeight > element.clientHeight); setHasHorizontalScrollbar(element.scrollWidth > element.clientWidth); }); useEffect(() => { handleResize(); const element = ref.current; if (!element) { return; } const debouncedHandleResize = debounce(handleResize, 100); element.addEventListener('resize', debouncedHandleResize); // Must add an observer because nor resize or scroll event are enough const observer = new MutationObserver(debouncedHandleResize); observer.observe(element, { attributes: true, childList: true, subtree: true }); return () => { element.removeEventListener('resize', debouncedHandleResize); observer.disconnect(); }; }, []); return [hasVerticalScrollbar, hasHorizontalScrollbar]; };
3,951
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useInviteButtons.ts
import { useCallback } from 'react'; import { useApi, useConfig, useGetCalendarUserSettings, useRelocalizeText } from '@proton/components'; import { useGetCanonicalEmailsMap } from '@proton/components/hooks/useGetCanonicalEmailsMap'; import { useGetVtimezonesMap } from '@proton/components/hooks/useGetVtimezonesMap'; import useSendIcs from '@proton/components/hooks/useSendIcs'; import { serverTime } from '@proton/crypto'; import { withPartstat } from '@proton/shared/lib/calendar/attendees'; import { ICAL_ATTENDEE_STATUS, ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { getInviteLocale } from '@proton/shared/lib/calendar/getSettings'; import { createInviteIcs, generateEmailBody, generateVtimezonesComponents, getParticipantHasAddressID, } from '@proton/shared/lib/calendar/mailIntegration/invite'; import { reencryptCalendarSharedEvent } from '@proton/shared/lib/calendar/sync/reencrypt'; import { prodId } from '@proton/shared/lib/calendar/vcalConfig'; import { withDtstamp } from '@proton/shared/lib/calendar/veventHelper'; import { SECOND } from '@proton/shared/lib/constants'; import { omit } from '@proton/shared/lib/helpers/object'; import { wait } from '@proton/shared/lib/helpers/promise'; import { CalendarEvent, CalendarEventEncryptionData, CalendarWidgetData, Participant, PartstatActions, PmInviteData, SavedInviteData, } from '@proton/shared/lib/interfaces/calendar'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel'; import { getHasFullCalendarData } from '../helpers/calendar/invite'; import { createCalendarEventFromInvitation, deleteCalendarEventFromInvitation, updatePartstatFromInvitation, } from '../helpers/calendar/inviteApi'; import { useContactsMap } from './contact/useContacts'; interface Args { veventApi?: VcalVeventComponent; veventIcs: VcalVeventComponent; attendee?: Participant; organizer?: Participant; subject: string; messageID?: string; calendarData?: CalendarWidgetData; pmData?: PmInviteData; singleEditData?: CalendarEvent[]; reencryptionData?: Required<Pick<CalendarEventEncryptionData, 'encryptingAddressID' | 'sharedSessionKey'>>; calendarEvent?: CalendarEvent; onEmailSuccess: () => void; onEmailError: (error: Error) => void; onCreateEventSuccess: () => void; onUpdateEventSuccess: () => void; onCreateEventError: (partstat: ICAL_ATTENDEE_STATUS, isProtonInvite: boolean, error?: any) => void; onUpdateEventError: ( partstat: ICAL_ATTENDEE_STATUS, timestamp: number, isProtonInvite: boolean, error?: any ) => void; onReencryptEventError: (error: Error) => void; onSuccess: (savedData: SavedInviteData) => void; onUnexpectedError: () => void; overwrite: boolean; reinviteEventID?: string; disabled?: boolean; } const useInviteButtons = ({ veventApi, veventIcs, attendee, organizer, subject, messageID, calendarData, pmData, singleEditData, reencryptionData, calendarEvent, onEmailSuccess, onEmailError, onCreateEventSuccess, onUpdateEventSuccess, onSuccess, onCreateEventError, onUpdateEventError, onReencryptEventError, onUnexpectedError, overwrite, reinviteEventID, disabled = false, }: Args): PartstatActions => { const api = useApi(); const getCalendarUserSettings = useGetCalendarUserSettings(); const sendIcs = useSendIcs(); const relocalizeText = useRelocalizeText(); const config = useConfig(); const getCanonicalEmailsMap = useGetCanonicalEmailsMap(); const getVTimezonesMap = useGetVtimezonesMap(); const contactEmailsMap = useContactsMap(); // Returns true if the operation is succesful const sendReplyEmail = useCallback( async (partstat: ICAL_ATTENDEE_STATUS, timestamp: number) => { if (!attendee || !getParticipantHasAddressID(attendee) || !organizer || !config) { onUnexpectedError(); return false; } try { const attendeeWithPartstat = withPartstat(attendee.vcalComponent, partstat); const vevent = withDtstamp(omit(veventIcs, ['dtstamp']), timestamp); const vtimezones = await generateVtimezonesComponents(vevent, getVTimezonesMap); if (pmData?.sharedEventID && pmData?.sharedSessionKey) { vevent['x-pm-proton-reply'] = { value: 'true', parameters: { type: 'boolean' } }; } const ics = createInviteIcs({ method: ICAL_METHOD.REPLY, prodId, vevent: withDtstamp(omit(vevent, ['dtstamp']), timestamp), vtimezones, attendeesTo: [attendeeWithPartstat], keepDtstamp: true, }); const inviteLocale = getInviteLocale(await getCalendarUserSettings()); const getEmailBody = () => generateEmailBody({ method: ICAL_METHOD.REPLY, vevent, emailAddress: attendee.emailAddress, partstat, }); await sendIcs({ method: ICAL_METHOD.REPLY, ics, addressID: attendee.addressID, parentID: messageID, from: { Address: attendee.emailAddress, Name: attendee.name || attendee.emailAddress }, to: [{ Address: organizer.emailAddress, Name: organizer.name }], subject, plainTextBody: await relocalizeText({ getLocalizedText: getEmailBody, newLocaleCode: inviteLocale, relocalizeDateFormat: true, }), contactEmailsMap, }); onEmailSuccess(); return true; } catch (error: any) { onEmailError(error); return false; } }, [veventApi, veventIcs, attendee, organizer, config, onEmailSuccess, onEmailError] ); // Returns true if the operation is successful const deleteCalendarEvent = useCallback( async (reinviteEventID: string) => { if (!getHasFullCalendarData(calendarData)) { onUnexpectedError(); return false; } try { await deleteCalendarEventFromInvitation({ calendarEventID: reinviteEventID, calendarData, api }); return true; } catch (error: any) { onUnexpectedError(); return false; } }, [veventApi, veventIcs, attendee, api, calendarData] ); const createCalendarEvent = useCallback( async (partstat: ICAL_ATTENDEE_STATUS, isProtonInvite: boolean) => { if (!attendee || !veventIcs) { onUnexpectedError(); return; } try { const { savedEvent, savedVevent, savedVcalAttendee } = await createCalendarEventFromInvitation({ vevent: veventIcs, vcalAttendee: attendee.vcalComponent, partstat, api, getCanonicalEmailsMap, calendarData, pmData, overwrite, }); onCreateEventSuccess(); return { savedEvent, savedVevent, savedVcalAttendee }; } catch (error) { onCreateEventError(partstat, isProtonInvite, error); } }, [veventIcs, attendee, api, getCanonicalEmailsMap, calendarData, pmData, overwrite] ); const updateCalendarEvent = useCallback( async (partstat: ICAL_ATTENDEE_STATUS, timestamp: number, isProtonInvite: boolean, event?: CalendarEvent) => { if (!attendee || !veventApi || !event) { onUnexpectedError(); return; } try { const { savedEvent, savedVevent, savedVcalAttendee } = await updatePartstatFromInvitation({ veventIcs, veventApi, calendarEvent: event, vcalAttendee: attendee.vcalComponent, attendeeToken: attendee.token, partstat, oldPartstat: attendee.partstat, timestamp, api, calendarData, singleEditData, }); onUpdateEventSuccess(); return { savedEvent, savedVevent, savedVcalAttendee }; } catch (error: any) { onUpdateEventError(partstat, timestamp, isProtonInvite, error); } }, [veventApi, veventIcs, attendee, api, calendarData, singleEditData] ); const answerInvitation = useCallback( async (partstat: ICAL_ATTENDEE_STATUS) => { let maybeReencryptedEvent: CalendarEvent | undefined = calendarEvent ? { ...calendarEvent } : undefined; if (reencryptionData) { const { sharedSessionKey } = reencryptionData; const { calendarKeys } = calendarData || {}; if (!calendarKeys || !calendarEvent) { throw new Error('Missing data for re-encrypting event'); } const silentApi = <T>(config: any) => api<T>({ ...config, silence: true, }); try { maybeReencryptedEvent = await reencryptCalendarSharedEvent({ calendarEvent, sharedSessionKey, calendarKeys, api: silentApi, }); } catch (error: any) { onReencryptEventError(error); return; } } if (reinviteEventID) { const deleted = await deleteCalendarEvent(reinviteEventID); if (!deleted) { return; } } const currentTimestamp = +serverTime(); if (pmData) { // we perform the sync operations before sending the email, as the interaction // does not happen via email for Proton-Proton invites const result = !veventApi || reinviteEventID ? await createCalendarEvent(partstat, true) : await updateCalendarEvent(partstat, currentTimestamp, true, maybeReencryptedEvent); if (!result) { return; } const updateTime = result.savedEvent.Attendees.find( ({ Token }) => Token === attendee?.token )?.UpdateTime; if (!updateTime) { throw new Error('Failed to retrieve attendee update time'); } await sendReplyEmail(partstat, updateTime * SECOND); onSuccess(result); return; } // For other invites, we perform the sync operations after sending the email; // and only if the latter is successful, as the interaction happens via email const sent = await sendReplyEmail(partstat, currentTimestamp); if (!sent) { return; } const result = !veventApi || reinviteEventID ? await createCalendarEvent(partstat, false) : await updateCalendarEvent(partstat, currentTimestamp, false, maybeReencryptedEvent); if (result) { onSuccess(result); } }, [sendReplyEmail, createCalendarEvent, updateCalendarEvent, reinviteEventID, pmData, reencryptionData] ); const dummyActions = { accept: () => wait(0), acceptTentatively: () => wait(0), decline: () => wait(0), retryCreateEvent: () => wait(0), retryUpdateEvent: () => wait(0), }; if (!attendee || !organizer || disabled) { return dummyActions; } return { accept: () => answerInvitation(ICAL_ATTENDEE_STATUS.ACCEPTED), acceptTentatively: () => answerInvitation(ICAL_ATTENDEE_STATUS.TENTATIVE), decline: () => answerInvitation(ICAL_ATTENDEE_STATUS.DECLINED), retryCreateEvent: async ({ partstat, isProtonInvite, }: { partstat: ICAL_ATTENDEE_STATUS; isProtonInvite: boolean; }) => { const result = await createCalendarEvent(partstat, isProtonInvite); if (result) { onSuccess(result); } }, retryUpdateEvent: async ({ partstat, timestamp, isProtonInvite, calendarEvent, }: { partstat: ICAL_ATTENDEE_STATUS; timestamp: number; isProtonInvite: boolean; calendarEvent?: CalendarEvent; }) => { const result = await updateCalendarEvent(partstat, timestamp, isProtonInvite, calendarEvent); if (result) { onSuccess(result); } }, }; }; export default useInviteButtons;
3,952
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useLabelActions.test.ts
import { renderHook } from '@testing-library/react-hooks'; import { useFolders, useLabels } from '@proton/components/hooks'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { useLabelActions } from './useLabelActions'; jest.mock('@proton/components/hooks/useCategories'); const { TRASH, SPAM, DRAFTS, ARCHIVE, SENT, INBOX, ALL_DRAFTS, ALL_SENT, STARRED, ALL_MAIL, ALMOST_ALL_MAIL, SCHEDULED, SNOOZED, } = MAILBOX_LABEL_IDS; describe('useLabelActions', () => { const useFoldersMock = useFolders as jest.Mock; const useLabelsMock = useLabels as jest.Mock; beforeEach(() => { useFoldersMock.mockReturnValue([[], jest.fn()]); useLabelsMock.mockReturnValue([[], jest.fn()]); }); afterEach(() => { useFoldersMock.mockClear(); useLabelsMock.mockClear(); }); it('should render correct action for inbox label', () => { const { result } = renderHook(() => useLabelActions(INBOX)); expect(result.current[0]).toEqual(['trash', 'archive', 'spam']); }); it('should render correct action for drafts and all drafts label', () => { const resDrafts = renderHook(() => useLabelActions(DRAFTS)); expect(resDrafts.result.current[0]).toEqual(['trash', 'archive', 'delete']); const resAllDrafts = renderHook(() => useLabelActions(ALL_DRAFTS)); expect(resAllDrafts.result.current[0]).toEqual(['trash', 'archive', 'delete']); }); it('should render correct action for sent and all sent label', () => { const resSent = renderHook(() => useLabelActions(SENT)); expect(resSent.result.current[0]).toEqual(['trash', 'archive', 'delete']); const resAllSent = renderHook(() => useLabelActions(ALL_SENT)); expect(resAllSent.result.current[0]).toEqual(['trash', 'archive', 'delete']); }); it('should render correct action for scheduled and snooze label', () => { const resScheduled = renderHook(() => useLabelActions(SCHEDULED)); expect(resScheduled.result.current[0]).toEqual(['trash', 'archive']); const resSnoozed = renderHook(() => useLabelActions(SNOOZED)); expect(resSnoozed.result.current[0]).toEqual(['trash', 'archive']); }); it('should render correct action for starred label', () => { const { result } = renderHook(() => useLabelActions(STARRED)); expect(result.current[0]).toEqual(['trash', 'archive', 'spam']); }); it('should render correct action for archive label', () => { const { result } = renderHook(() => useLabelActions(ARCHIVE)); expect(result.current[0]).toEqual(['trash', 'inbox', 'spam']); }); it('should render correct action for spam label', () => { const { result } = renderHook(() => useLabelActions(SPAM)); expect(result.current[0]).toEqual(['trash', 'nospam', 'delete']); }); it('should render correct action for trash label', () => { const { result } = renderHook(() => useLabelActions(TRASH)); expect(result.current[0]).toEqual(['inbox', 'archive', 'delete']); }); it('should render correct action for all mail and almost all mail label', () => { const resAllMail = renderHook(() => useLabelActions(ALL_MAIL)); expect(resAllMail.result.current[0]).toEqual(['trash', 'archive', 'spam']); const resAlmostAllMail = renderHook(() => useLabelActions(ALMOST_ALL_MAIL)); expect(resAlmostAllMail.result.current[0]).toEqual(['trash', 'archive', 'spam']); }); it('should render correct action for custom folder label', () => { const customFolder = 'customFolder'; const customLabel = 'customLabel'; useFoldersMock.mockReturnValue([[{ ID: customFolder }], jest.fn()]); useLabelsMock.mockReturnValue([[{ ID: customLabel }], jest.fn()]); const resFolders = renderHook(() => useLabelActions(customFolder)); expect(resFolders.result.current[0]).toEqual(['trash', 'archive', 'spam']); const resLabels = renderHook(() => useLabelActions(customLabel)); expect(resLabels.result.current[0]).toEqual(['trash', 'archive', 'spam']); }); });
3,953
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useLabelActions.ts
import { useFolders, useLabels } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { isCustomFolder, isCustomLabel } from '../helpers/labels'; const { TRASH, SPAM, DRAFTS, ARCHIVE, SENT, INBOX, ALL_DRAFTS, ALL_SENT, STARRED, ALL_MAIL, ALMOST_ALL_MAIL, SCHEDULED, SNOOZED, } = MAILBOX_LABEL_IDS; type Actions = 'inbox' | 'trash' | 'delete' | 'archive' | 'spam' | 'nospam'; export const useLabelActions = (labelID: string): [primaryActions: Actions[], secondaryActions: Actions[]] => { const [labels = []] = useLabels(); const [folders = []] = useFolders(); let primaryActions: Actions[] = []; let secondaryActions: Actions[] = []; switch (labelID) { case INBOX: case STARRED: case ALL_MAIL: case ALMOST_ALL_MAIL: primaryActions = ['trash', 'archive', 'spam']; break; case DRAFTS: case ALL_DRAFTS: case SENT: case ALL_SENT: primaryActions = ['trash', 'archive', 'delete']; break; case SCHEDULED: case SNOOZED: primaryActions = ['trash', 'archive']; break; case ARCHIVE: primaryActions = ['trash', 'inbox', 'spam']; break; case SPAM: primaryActions = ['trash', 'nospam', 'delete']; break; case TRASH: primaryActions = ['inbox', 'archive', 'delete']; break; } if (isCustomFolder(labelID, folders)) { primaryActions = ['trash', 'archive', 'spam']; } else if (isCustomLabel(labelID, labels)) { primaryActions = ['trash', 'archive', 'spam']; } return [primaryActions, secondaryActions]; };
3,954
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useLongLivingState.ts
import { SetStateAction, useRef, useState } from 'react'; import useIsMounted from '@proton/hooks/useIsMounted'; /** * Enhanced useState supporting to continue living after component unmounting through the use of a ref. * Add a getter function which allow to get current value event after unmounting. */ export const useLongLivingState = <S>( initialState: S | (() => S) ): [S, (action: SetStateAction<S>) => void, () => S] => { const isMounted = useIsMounted(); const [stateValue, setStateValue] = useState(initialState); const refValue = useRef<S>(stateValue); const setState = (action: SetStateAction<S>) => { refValue.current = action instanceof Function ? action(refValue.current) : action; if (isMounted()) { setStateValue(refValue.current); } }; const getState = () => refValue.current; return [stateValue, setState, getState]; };
3,955
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useMailModel.ts
import { useMailSettings } from '@proton/components/hooks'; type MailModel = 'MailSettings'; const useMailModel = (key: MailModel) => { const [mailSettings] = useMailSettings(); if (key === 'MailSettings' && mailSettings) { return mailSettings; } throw new Error(`Model ${key} does not exist`); }; export default useMailModel;
3,956
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useMoveSystemFolders.helpers.test.ts
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { SYSTEM_FOLDER_SECTION, SystemFolder } from './useMoveSystemFolders'; import { moveSystemFolders } from './useMoveSystemFolders.helpers'; const INBOX: SystemFolder = { labelID: MAILBOX_LABEL_IDS.INBOX, display: SYSTEM_FOLDER_SECTION.MAIN, order: 1, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const DRAFTS: SystemFolder = { labelID: MAILBOX_LABEL_IDS.DRAFTS, display: SYSTEM_FOLDER_SECTION.MAIN, order: 2, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const SENT: SystemFolder = { labelID: MAILBOX_LABEL_IDS.SENT, display: SYSTEM_FOLDER_SECTION.MAIN, order: 3, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const ALL_SENT: SystemFolder = { labelID: MAILBOX_LABEL_IDS.ALL_SENT, display: SYSTEM_FOLDER_SECTION.MAIN, order: 4, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: false, }; const SCHEDULED: SystemFolder = { labelID: MAILBOX_LABEL_IDS.SCHEDULED, display: SYSTEM_FOLDER_SECTION.MAIN, order: 4, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const ARCHIVE_MORE: SystemFolder = { labelID: MAILBOX_LABEL_IDS.ARCHIVE, display: SYSTEM_FOLDER_SECTION.MORE, order: 5, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const ALL_MAIL_MORE: SystemFolder = { labelID: MAILBOX_LABEL_IDS.ALL_MAIL, display: SYSTEM_FOLDER_SECTION.MORE, order: 6, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; const SPAM_MORE: SystemFolder = { labelID: MAILBOX_LABEL_IDS.SPAM, display: SYSTEM_FOLDER_SECTION.MORE, order: 7, payloadExtras: { Color: 'white', Name: 'undefined', }, icon: 'alias', ID: 'payloadID', text: 'text', visible: true, }; describe('moveSystemFolders', () => { describe('inbox', () => { it('Should not move when dragged', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.INBOX, MAILBOX_LABEL_IDS.DRAFTS, navItems)).toEqual(navItems); }); it('Should not move when dropped', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.DRAFTS, MAILBOX_LABEL_IDS.INBOX, navItems)).toEqual(navItems); expect(moveSystemFolders(MAILBOX_LABEL_IDS.SENT, MAILBOX_LABEL_IDS.INBOX, navItems)).toEqual([ INBOX, { ...SENT, order: 2 }, { ...DRAFTS, order: 3 }, SCHEDULED, ]); }); it('Should allow drop', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SCHEDULED, ARCHIVE_MORE, ALL_MAIL_MORE]; const movedFolders = moveSystemFolders(MAILBOX_LABEL_IDS.ARCHIVE, MAILBOX_LABEL_IDS.INBOX, navItems); expect(movedFolders).toEqual([ INBOX, { ...ARCHIVE_MORE, order: 2, display: SYSTEM_FOLDER_SECTION.MAIN }, { ...DRAFTS, order: 3 }, { ...SCHEDULED, order: 4 }, { ...ALL_MAIL_MORE, order: 5 }, ]); }); }); describe('item', () => { it('Should move withing main section', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED]; // From top to bottom expect(moveSystemFolders(MAILBOX_LABEL_IDS.DRAFTS, MAILBOX_LABEL_IDS.SCHEDULED, navItems)).toEqual([ INBOX, { ...SENT, order: 2 }, { ...SCHEDULED, order: 3 }, { ...DRAFTS, order: 4 }, ]); // From bottom to top expect(moveSystemFolders(MAILBOX_LABEL_IDS.SCHEDULED, MAILBOX_LABEL_IDS.DRAFTS, navItems)).toEqual([ INBOX, { ...SCHEDULED, order: 2 }, { ...DRAFTS, order: 3 }, { ...SENT, order: 4 }, ]); }); it('Should change section (main to more) when dropped over "more" folder', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED, ARCHIVE_MORE, ALL_MAIL_MORE, SPAM_MORE]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.SCHEDULED, 'MORE_FOLDER_ITEM', navItems)).toEqual([ INBOX, DRAFTS, SENT, { ...ARCHIVE_MORE, order: 4 }, { ...ALL_MAIL_MORE, order: 5 }, { ...SPAM_MORE, order: 6 }, { ...SCHEDULED, order: 7, display: SYSTEM_FOLDER_SECTION.MORE }, ]); expect(moveSystemFolders(MAILBOX_LABEL_IDS.SENT, 'MORE_FOLDER_ITEM', navItems)).toEqual([ INBOX, DRAFTS, { ...SCHEDULED, order: 3 }, { ...ARCHIVE_MORE, order: 4 }, { ...ALL_MAIL_MORE, order: 5 }, { ...SPAM_MORE, order: 6 }, { ...SENT, order: 7, display: SYSTEM_FOLDER_SECTION.MORE }, ]); // Should take the last main element if more section is empty const navItemsWithMoreEmpty: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.SENT, 'MORE_FOLDER_ITEM', navItemsWithMoreEmpty)).toEqual([ INBOX, DRAFTS, { ...SCHEDULED, order: 3 }, { ...SENT, order: 4, display: SYSTEM_FOLDER_SECTION.MORE }, ]); }); it('Should stay in "more" section when dropped on first MORE element', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, SCHEDULED, ARCHIVE_MORE, ALL_MAIL_MORE, SPAM_MORE]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.ALL_MAIL, MAILBOX_LABEL_IDS.ARCHIVE, navItems)).toEqual([ INBOX, DRAFTS, SENT, SCHEDULED, { ...ALL_MAIL_MORE, order: 5 }, { ...ARCHIVE_MORE, order: 6 }, SPAM_MORE, ]); }); it('should move linked label such as sent, all sent', () => { const navItems: SystemFolder[] = [INBOX, DRAFTS, SENT, ALL_SENT, SCHEDULED]; expect(moveSystemFolders(MAILBOX_LABEL_IDS.SENT, MAILBOX_LABEL_IDS.INBOX, navItems)).toEqual([ INBOX, { ...ALL_SENT, order: 2 }, { ...SENT, order: 3 }, { ...DRAFTS, order: 4 }, { ...SCHEDULED, order: 5 }, ]); }); }); });
3,957
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useMoveSystemFolders.helpers.ts
import { c } from 'ttag'; import { ACCENT_COLORS } from '@proton/shared/lib/colors'; import { LINKED_LABEL_IDS, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings'; import move from '@proton/utils/move'; import orderBy from '@proton/utils/orderBy'; import { LABEL_IDS_TO_HUMAN } from '../constants'; import { BaseSystemFolder, SYSTEM_FOLDER_SECTION, SystemFolder, SystemFolderPayload, UseMoveSystemFoldersProps, } from './useMoveSystemFolders'; interface MoveSystemFolders { ( draggedID: MAILBOX_LABEL_IDS, droppedId: MAILBOX_LABEL_IDS | 'MORE_FOLDER_ITEM', systemFolders: SystemFolder[] ): SystemFolder[]; } /** * If called for "MAIN" section, result will always have at least "inbox" * so null is not possible in this case */ function getLastSectionElementIndex(collection: SystemFolder[], section: SYSTEM_FOLDER_SECTION.MAIN): number; function getLastSectionElementIndex(collection: SystemFolder[], section: SYSTEM_FOLDER_SECTION.MORE): null | number; function getLastSectionElementIndex(collection: SystemFolder[], section: SYSTEM_FOLDER_SECTION): null | number { return collection.reduce<number | null>((acc, element, index) => { if (element.display === section && (acc === null || index > acc) && element.visible === true) { acc = index; } return acc; }, null); } const cloneItem = (item: SystemFolder): SystemFolder => ({ ...item, payloadExtras: { ...item.payloadExtras } }); const reorderItems = (collection: SystemFolder[]): SystemFolder[] => collection.map((item, index) => { const nextItem = cloneItem(item); // Order is not 0 based index nextItem.order = index + 1; return nextItem; }); const moveItems = (systemFolders: SystemFolder[], draggedItemIndex: number, droppedItemIndex: number) => { const movedItems = move(systemFolders, draggedItemIndex, droppedItemIndex); const draggedID = systemFolders[draggedItemIndex].labelID; const linkedID = LINKED_LABEL_IDS[draggedID]; if (linkedID) { const allSentIndex = systemFolders.findIndex((item) => item.labelID === linkedID); if (allSentIndex !== -1) { return move(movedItems, allSentIndex, droppedItemIndex); } } return movedItems; }; export const moveSystemFolders: MoveSystemFolders = (draggedID, droppedId, systemFolders) => { if (draggedID === MAILBOX_LABEL_IDS.INBOX) { return systemFolders; } const droppedOver: 'ITEM' | 'INBOX' | 'MORE_FOLDER' = (() => { if (droppedId === MAILBOX_LABEL_IDS.INBOX) { return 'INBOX'; } if (droppedId === 'MORE_FOLDER_ITEM') { return 'MORE_FOLDER'; } return 'ITEM'; })(); const draggedItemIndex = systemFolders.findIndex((el) => el.labelID === draggedID); const droppedItemIndex = systemFolders.findIndex((el) => el.labelID === droppedId); if (droppedOver === 'ITEM') { if (draggedItemIndex === -1 || droppedItemIndex === -1 || draggedItemIndex === droppedItemIndex) { return systemFolders; } const droppedItem = systemFolders[droppedItemIndex]; const movedItems = moveItems(systemFolders, draggedItemIndex, droppedItemIndex); const reorderedItems = reorderItems(movedItems); const nextItems = reorderedItems.map((item) => { const clonedItem = cloneItem(item); const isDraggedItem = clonedItem.labelID === draggedID; if (isDraggedItem) { const changedSection = clonedItem.display !== droppedItem.display; if (changedSection) { clonedItem.display = droppedItem.display; } } return clonedItem; }); return nextItems; } if (droppedOver === 'INBOX') { const inboxItemIndex = systemFolders.findIndex((item) => item.labelID === MAILBOX_LABEL_IDS.INBOX); if (draggedItemIndex === -1 || inboxItemIndex === -1) { return systemFolders; } const inboxItem = systemFolders[inboxItemIndex]; const movedItems = moveItems(systemFolders, draggedItemIndex, inboxItemIndex + 1); const reorderedItems = reorderItems(movedItems); const nextItems = reorderedItems.map((item) => { const clonedItem = cloneItem(item); const isDraggedItem = clonedItem.labelID === draggedID; if (isDraggedItem) { const changedSection = clonedItem.display !== inboxItem.display; if (changedSection) { clonedItem.display = inboxItem.display; } } return clonedItem; }); return nextItems; } if (droppedOver === 'MORE_FOLDER') { if (draggedItemIndex === -1) { return systemFolders; } const draggedItem = systemFolders[draggedItemIndex]; const lastMoreSectionItemIndex = getLastSectionElementIndex(systemFolders, SYSTEM_FOLDER_SECTION.MORE); const lastMainSectionItemIndex = getLastSectionElementIndex(systemFolders, SYSTEM_FOLDER_SECTION.MAIN); const movedItems = moveItems( systemFolders, draggedItemIndex, draggedItem.display === SYSTEM_FOLDER_SECTION.MAIN ? lastMoreSectionItemIndex || lastMainSectionItemIndex : lastMainSectionItemIndex + 1 ); const reorderedItems = reorderItems(movedItems); const nextItems = reorderedItems.map((item) => { const clonedItem = cloneItem(item); const isDraggedItem = clonedItem.labelID === draggedID; if (isDraggedItem) { const nextSection = clonedItem.display === SYSTEM_FOLDER_SECTION.MORE ? SYSTEM_FOLDER_SECTION.MAIN : SYSTEM_FOLDER_SECTION.MORE; clonedItem.display = nextSection; } return clonedItem; }); return nextItems; } return systemFolders; }; export const getDefaultSystemFolders = ( showMoved: UseMoveSystemFoldersProps['showMoved'], showScheduled: UseMoveSystemFoldersProps['showScheduled'], showSnoozed: UseMoveSystemFoldersProps['showSnoozed'], showAlmostAllMail: UseMoveSystemFoldersProps['showAlmostAllMail'] ): BaseSystemFolder[] => [ { labelID: MAILBOX_LABEL_IDS.INBOX, ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.INBOX], icon: 'inbox', text: c('Link').t`Inbox`, shortcutText: '[G] [I]', visible: true, order: 1, display: SYSTEM_FOLDER_SECTION.MAIN, }, { labelID: MAILBOX_LABEL_IDS.ALL_DRAFTS, ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.ALL_DRAFTS], icon: 'file-lines', text: c('Link').t`Drafts`, shortcutText: '[G] [D]', visible: !!(showMoved & SHOW_MOVED.DRAFTS), order: 2, display: SYSTEM_FOLDER_SECTION.MAIN, }, { labelID: MAILBOX_LABEL_IDS.DRAFTS, ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.DRAFTS], icon: 'file-lines', text: c('Link').t`Drafts`, shortcutText: '[G] [D]', visible: !(showMoved & SHOW_MOVED.DRAFTS), order: 3, display: SYSTEM_FOLDER_SECTION.MAIN, }, { labelID: MAILBOX_LABEL_IDS.SCHEDULED, icon: 'paper-plane-horizontal-clock', text: c('Link').t`Scheduled`, ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.SCHEDULED], visible: !!showScheduled, order: 4, display: SYSTEM_FOLDER_SECTION.MAIN, }, { labelID: MAILBOX_LABEL_IDS.SNOOZED, icon: 'clock', text: c('Link').t`Snoozed`, ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.SNOOZED], visible: !!showSnoozed, order: 5, display: SYSTEM_FOLDER_SECTION.MAIN, }, { labelID: MAILBOX_LABEL_IDS.ALL_SENT, ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.ALL_SENT], icon: 'paper-plane-horizontal', text: c('Link').t`Sent`, shortcutText: '[G] [E]', visible: !!(showMoved & SHOW_MOVED.SENT), order: 6, display: SYSTEM_FOLDER_SECTION.MAIN, }, { labelID: MAILBOX_LABEL_IDS.SENT, ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.SENT], icon: 'paper-plane-horizontal', text: c('Link').t`Sent`, shortcutText: '[G] [E]', visible: !(showMoved & SHOW_MOVED.SENT), order: 7, display: SYSTEM_FOLDER_SECTION.MAIN, }, { labelID: MAILBOX_LABEL_IDS.STARRED, icon: 'star', text: c('Link').t`Starred`, shortcutText: '[G] [*]', ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.STARRED], visible: true, order: 8, display: SYSTEM_FOLDER_SECTION.MAIN, }, { labelID: MAILBOX_LABEL_IDS.ARCHIVE, icon: 'archive-box', text: c('Link').t`Archive`, shortcutText: '[G] [A]', ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.ARCHIVE], visible: true, order: 9, display: SYSTEM_FOLDER_SECTION.MORE, }, { labelID: MAILBOX_LABEL_IDS.SPAM, icon: 'fire', text: c('Link').t`Spam`, shortcutText: '[G] [S]', ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.SPAM], visible: true, order: 10, display: SYSTEM_FOLDER_SECTION.MORE, }, { labelID: MAILBOX_LABEL_IDS.TRASH, icon: 'trash', text: c('Link').t`Trash`, shortcutText: '[G] [T]', ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.TRASH], visible: true, order: 11, display: SYSTEM_FOLDER_SECTION.MORE, }, { labelID: MAILBOX_LABEL_IDS.ALL_MAIL, icon: 'envelopes', text: c('Link').t`All mail`, shortcutText: '[G] [M]', ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.ALL_MAIL], visible: !showAlmostAllMail, order: 12, display: SYSTEM_FOLDER_SECTION.MORE, }, { /** Added for mapping with API, we dont display outbox */ labelID: MAILBOX_LABEL_IDS.OUTBOX, icon: 'arrow-right', text: c('Link').t`Outbox`, ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.OUTBOX], order: 13, visible: false, display: SYSTEM_FOLDER_SECTION.MORE, }, { labelID: MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL, icon: 'envelopes', text: c('Link').t`All mail`, shortcutText: '[G] [M]', ID: LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL], visible: !!showAlmostAllMail, order: 14, display: SYSTEM_FOLDER_SECTION.MORE, }, ]; export const getSidebarNavItems = ( showMoved: UseMoveSystemFoldersProps['showMoved'], showScheduled: UseMoveSystemFoldersProps['showScheduled'], showSnoozed: UseMoveSystemFoldersProps['showSnoozed'], showAlmostAllMail: UseMoveSystemFoldersProps['showAlmostAllMail'], apiSystemFolders: SystemFolderPayload[] ): { orderedSystemFolders: SystemFolder[]; unexpectedFolderIDs: MAILBOX_LABEL_IDS[] } => { /** Harcoded system folders, used to complete missing infos in API fetched ones */ const defaultSystemFolders = getDefaultSystemFolders(showMoved, showScheduled, showSnoozed, showAlmostAllMail); /** * 1 - Fill the needed data from API */ const systemFolders = defaultSystemFolders .map((defaultSystemFolder): SystemFolder | null => { const apiSystemFolder = apiSystemFolders.find((pItem) => pItem.ID === defaultSystemFolder.labelID); if (!apiSystemFolder) { return null; } return { ...defaultSystemFolder, order: apiSystemFolder.Order ?? defaultSystemFolder.order, display: apiSystemFolder.Display ?? defaultSystemFolder.display, payloadExtras: { // Voluntary override in order to guarantee a valid color Color: ACCENT_COLORS[0], Name: apiSystemFolder.Name, }, }; }) .filter((item): item is SystemFolder => item !== null); /** * 2 - Split list in two sections (MAIN and MORE) and order them by 'order' value */ const mainSectionSystemFolders = orderBy( systemFolders.filter((item) => item.display === SYSTEM_FOLDER_SECTION.MAIN), 'order' ); const moreSectionSystemFolders = orderBy( systemFolders.filter((item) => item.display === SYSTEM_FOLDER_SECTION.MORE), 'order' ); /** * 3 - Merge previous ordered lists into 1 and update the order value based on the index */ const orderedSystemFolders = [...mainSectionSystemFolders, ...moreSectionSystemFolders].map((item, index) => ({ ...item, order: index + 1, })); /** * 4 - Check if API returned unexpected folders */ const unexpectedFolderIDs = apiSystemFolders .filter((apiFolder) => systemFolders.every((folder) => apiFolder.ID !== folder.labelID)) .map((apiFolder) => apiFolder.ID); return { orderedSystemFolders, unexpectedFolderIDs }; };
3,958
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useMoveSystemFolders.ts
import { useEffect, useRef, useState } from 'react'; import { IconName, useApi } from '@proton/components'; import { useSystemFolders } from '@proton/components/hooks/useCategories'; import { orderSystemFolders, updateSystemFolders } from '@proton/shared/lib/api/labels'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { getSidebarNavItems, moveSystemFolders } from './useMoveSystemFolders.helpers'; export interface UseMoveSystemFoldersProps { showMoved: MailSettings['ShowMoved']; showScheduled: boolean; showSnoozed: boolean; showAlmostAllMail: MailSettings['AlmostAllMail']; } export enum SYSTEM_FOLDER_SECTION { MAIN = 1, MORE = 0, } export interface SystemFolderPayload { ID: MAILBOX_LABEL_IDS; Order: number; Display: SYSTEM_FOLDER_SECTION; /** Mandatory for "update" api call */ Color: string; /** Mandatory for "update" api call */ Name: string; } export interface BaseSystemFolder { labelID: MAILBOX_LABEL_IDS; ID: string; icon: IconName; text: string; shortcutText?: string; visible: boolean; order: number; display: SYSTEM_FOLDER_SECTION; } export interface SystemFolder extends BaseSystemFolder { /** Mandatory fields for api calls */ payloadExtras: { Name: SystemFolderPayload['Color']; Color: SystemFolderPayload['Name']; }; } type UseSidebarElementsResponse = [ sidebarElements: SystemFolder[], moveSidebarElements: (draggedId: MAILBOX_LABEL_IDS, droppedId: MAILBOX_LABEL_IDS | 'MORE_FOLDER_ITEM') => void, loading: boolean ]; const useMoveSystemFolders = ({ showMoved, showScheduled, showSnoozed, showAlmostAllMail, }: UseMoveSystemFoldersProps): UseSidebarElementsResponse => { const api = useApi(); const abortUpdateOrderCallRef = useRef<AbortController>(new AbortController()); const [systemFoldersFromApi, loading] = useSystemFolders(); const [systemFolders, setSystemFolders] = useState<SystemFolder[]>([]); const [unexpectedSystemFolderIDs, setUnexpectedSystemFolderIDs] = useState<MAILBOX_LABEL_IDS[]>([]); const visibleSystemFolders = systemFolders.filter((element) => element.visible); const moveItem = (draggedID: MAILBOX_LABEL_IDS, droppedID: MAILBOX_LABEL_IDS | 'MORE_FOLDER_ITEM') => { if (draggedID === droppedID) { return; } const nextItems = moveSystemFolders(draggedID, droppedID, systemFolders); // Optimistic update setSystemFolders(nextItems); const prevDraggedItem = systemFolders.find((item) => item.labelID === draggedID); const nextDraggedItem = nextItems.find((item) => item.labelID === draggedID); if (!prevDraggedItem || !nextDraggedItem) { return; } const hasSectionChanged = prevDraggedItem.display !== undefined && nextDraggedItem.display !== undefined && nextDraggedItem.display !== prevDraggedItem.display; // Abort prev requests abortUpdateOrderCallRef.current.abort(); abortUpdateOrderCallRef.current = new AbortController(); if (hasSectionChanged) { void api( updateSystemFolders(nextDraggedItem.labelID, { Display: nextDraggedItem.display, Color: nextDraggedItem.payloadExtras.Color, Name: nextDraggedItem.payloadExtras.Name, }) ); } void api({ ...orderSystemFolders({ LabelIDs: [...nextItems.map((item) => item.labelID), ...unexpectedSystemFolderIDs], }), signal: abortUpdateOrderCallRef.current.signal, }); }; useEffect(() => { if (systemFoldersFromApi?.length) { const formattedLabels: SystemFolderPayload[] = systemFoldersFromApi .map((label) => ({ ID: label.ID as MAILBOX_LABEL_IDS, Display: label.Display ?? SYSTEM_FOLDER_SECTION.MAIN, Order: label.Order, Color: label.Color, Name: label.Name, })) .filter((item) => !!item.ID); const { orderedSystemFolders, unexpectedFolderIDs } = getSidebarNavItems( showMoved, showScheduled, showSnoozed, showAlmostAllMail, formattedLabels ); setSystemFolders(orderedSystemFolders); setUnexpectedSystemFolderIDs(unexpectedFolderIDs); } }, [systemFoldersFromApi, showMoved, showSnoozed, showScheduled, showAlmostAllMail]); return [visibleSystemFolders, moveItem, loading]; }; export default useMoveSystemFolders;
3,959
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/usePaging.ts
import { useCallback, useEffect, useState } from 'react'; import { pageCount } from '../helpers/paging'; export const usePaging = (inputPage: number, inputTotal: number | undefined, onPage: (page: number) => void) => { const getPage = () => inputPage + 1; const getTotal = () => (inputTotal === undefined ? 0 : pageCount(inputTotal)); const [page, setPage] = useState(getPage); const [total, setTotal] = useState(getTotal); // Willingly delay updates of page and total values to wait for view content to update alongside useEffect(() => { setPage(getPage); setTotal(getTotal); }, [inputPage, inputTotal]); const handleNext = useCallback( () => onPage(inputPage === total - 1 ? total - 1 : inputPage + 1), [onPage, inputPage, total] ); const handlePrevious = useCallback(() => onPage(inputPage === 0 ? 0 : inputPage - 1), [onPage, inputPage]); const handlePage = useCallback((newPage: number) => onPage(newPage - 1), [onPage]); const handleStart = useCallback(() => onPage(0), [onPage]); const handleEnd = useCallback(() => onPage(total - 1), [onPage, total]); return { onNext: handleNext, onPrevious: handlePrevious, onPage: handlePage, onStart: handleStart, onEnd: handleEnd, page, total, }; };
3,960
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/usePlaceholders.ts
import { useMemo } from 'react'; import { generateUID } from '@proton/components'; import range from '@proton/utils/range'; import { Element } from '../models/element'; export const PLACEHOLDER_ID_PREFIX = 'placeholder'; export const usePlaceholders = ( inputElements: Element[] | undefined, loading: boolean, expectedLength: number ): Element[] => { const placeholders: Element[] = useMemo( () => range(0, expectedLength).map(() => ({ ID: generateUID(PLACEHOLDER_ID_PREFIX) })), [loading, expectedLength] ); const elements: Element[] = useMemo( () => (loading ? placeholders : (inputElements as Element[])), [loading, inputElements] ); return elements; };
3,961
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/usePromise.ts
import { useRef, useState } from 'react'; import useIsMounted from '@proton/hooks/useIsMounted'; import noop from '@proton/utils/noop'; export type PromiseHandlers<P> = { promise: Promise<P>; resolver: (payload: P) => void; rejecter: (error: any) => void; renew: () => void; isPending: boolean; }; const initializingValue = { promise: Promise.resolve(), resolver: noop, rejecter: noop, renew: noop, isPending: false, } as PromiseHandlers<any>; /** * Instrument a promise to allow a component to start, resolve or reject it as will. * Support to be used even after component unmounting. * Internally use a ref for storing data but use a fake state to trigger updates. */ export const usePromise = <P>() => { const isMounted = useIsMounted(); const [, setFakeState] = useState({}); const promiseRef = useRef<PromiseHandlers<P>>(initializingValue); const renew = () => { let resolver: (payload: P) => void = noop; let rejecter: (error: any) => void = noop; const promise = new Promise<P>((resolve, reject) => { resolver = (payload) => { if (isMounted()) { promiseRef.current.isPending = false; setFakeState({}); } resolve(payload); }; rejecter = (error) => { if (isMounted()) { promiseRef.current.isPending = false; setFakeState({}); } reject(error); }; }); Object.assign(promiseRef.current, { promise, resolver, rejecter, renew, isPending: true }); if (isMounted()) { setFakeState({}); } return promise; }; if (promiseRef.current === initializingValue) { promiseRef.current = { ...initializingValue, renew }; } return promiseRef.current as PromiseHandlers<P>; };
3,962
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useResizeMessageView.ts
import { RefObject, useCallback, useEffect, useState } from 'react'; import { useDrawer, useHandler, useHotkeys, useWindowSize } from '@proton/components'; import { getItem, setItem } from '@proton/shared/lib/helpers/storage'; import throttle from '@proton/utils/throttle'; export const useResizeMessageView = ( containerRef: RefObject<HTMLDivElement>, resizeAreaRef: RefObject<HTMLButtonElement>, listRef: RefObject<HTMLDivElement> ) => { const { appInView } = useDrawer(); const [isResizing, setIsResizing] = useState(false); const [scrollBarWidth, setScrollBarWidth] = useState(0); const [windowWidth] = useWindowSize(); // Original ratio of the messageList const realDefaultRatio = 0.35; const realDefaultRatioWithDrawer = 0.25; const [defaultRatio, setDefaultRatio] = useState<number>(+(getItem('messageListRatio') || realDefaultRatio)); const [defaultWindowWidth, setDefaultWindowWidth] = useState(windowWidth); // Get left of container to have the size of the sidebar const sidebarWidth = containerRef.current ? containerRef.current.getBoundingClientRect().left : 0; const saveRatio = useHandler( (newWidth: number) => { const newRatio = newWidth / windowWidth; setDefaultRatio(newRatio); if (appInView) { setItem('messageListRatioWithDrawer', newRatio.toString()); } else { setItem('messageListRatio', newRatio.toString()); } }, { debounce: 2000 } ); const resize = (newWidth: number) => { document.documentElement.style.setProperty('--width-conversation-column', `${newWidth}px`); }; const resizeWithAmount = (amount: number) => { const newWidth = (listRef.current ? listRef.current.getBoundingClientRect().width : 0) + amount; saveRatio(newWidth); resize(newWidth); }; const resizeWithMouse = useCallback( (e) => { if (isResizing) { const newWidth = e.clientX - sidebarWidth + scrollBarWidth; saveRatio(newWidth); resize(newWidth); } }, [isResizing] ); const enableResize = useCallback(() => { setIsResizing(true); }, [setIsResizing]); const disableResize = useCallback(() => { setIsResizing(false); }, [setIsResizing]); const resetWidth = () => { resize(windowWidth * realDefaultRatio); }; useHotkeys(resizeAreaRef, [ [ 'ArrowRight', (e) => { e.stopPropagation(); resizeWithAmount(50); }, ], [ 'ArrowLeft', (e) => { e.stopPropagation(); resizeWithAmount(-50); }, ], ]); useEffect(() => { if (appInView) { setDefaultRatio(+(getItem('messageListRatioWithDrawer') || realDefaultRatioWithDrawer)); } else { setDefaultRatio(+(getItem('messageListRatio') || realDefaultRatio)); } }, [appInView]); // If the window is resized, resize the width too useEffect(() => { if (windowWidth !== defaultWindowWidth) { resize(windowWidth * defaultRatio); setDefaultWindowWidth(windowWidth); } }, [windowWidth]); // When launching the app, set the message view size to the default width (localStorage value if found, else the "real" default value) useEffect(() => { if (defaultRatio) { const defaultWidth = windowWidth * defaultRatio; resize(defaultWidth); } }, [defaultRatio]); useEffect(() => { const resizeThrottle = throttle(resizeWithMouse, 20); document.addEventListener('mousemove', resizeThrottle); document.addEventListener('mouseup', disableResize); document.addEventListener('mouseleave', disableResize); return () => { document.removeEventListener('mousemove', resizeThrottle); document.removeEventListener('mouseup', disableResize); document.removeEventListener('mouseleave', disableResize); }; }, [disableResize, resize]); const scrollBarListener = useHandler( () => { const listRect = listRef.current?.getBoundingClientRect(); const innerRect = listRef.current?.querySelector('.items-column-list-inner')?.getBoundingClientRect(); setScrollBarWidth((listRect?.width || 0) - (innerRect?.width || 0)); }, { debounce: 100 } ); useEffect(() => { scrollBarListener(); return () => scrollBarListener.cancel?.(); }); return { enableResize, resetWidth, scrollBarWidth, isResizing }; };
3,963
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useSendInfo.tsx
import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useState } from 'react'; import { c, msgid } from 'ttag'; import { useGetEncryptionPreferences, useKeyTransparencyContext } from '@proton/components'; import { useModalTwo } from '@proton/components/components/modalTwo/useModalTwo'; import { PublicKeyReference } from '@proton/crypto'; import useIsMounted from '@proton/hooks/useIsMounted'; import { processApiRequestsSafe } from '@proton/shared/lib/api/helpers/safeApiRequests'; import { validateEmailAddress } from '@proton/shared/lib/helpers/email'; import { omit } from '@proton/shared/lib/helpers/object'; import { KeyTransparencyActivation } from '@proton/shared/lib/interfaces'; import { Recipient } from '@proton/shared/lib/interfaces/Address'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { GetEncryptionPreferences } from '@proton/shared/lib/interfaces/hooks/GetEncryptionPreferences'; import { ENCRYPTION_PREFERENCES_ERROR_TYPES } from '@proton/shared/lib/mail/encryptionPreferences'; import { getRecipientsAddresses } from '@proton/shared/lib/mail/messages'; import getSendPreferences from '@proton/shared/lib/mail/send/getSendPreferences'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import AskForKeyPinningModal from '../components/composer/addresses/AskForKeyPinningModal'; import ContactResignModal from '../components/message/modals/ContactResignModal'; import { getSendStatusIcon } from '../helpers/message/icon'; import { ContactsMap } from '../logic/contacts/contactsTypes'; import { MessageState } from '../logic/messages/messagesTypes'; import { MapSendInfo, STATUS_ICONS_FILLS } from '../models/crypto'; import { useContactsMap } from './contact/useContacts'; const { PRIMARY_NOT_PINNED, CONTACT_SIGNATURE_NOT_VERIFIED } = ENCRYPTION_PREFERENCES_ERROR_TYPES; export interface MessageSendInfo { message: MessageState; mapSendInfo: MapSendInfo; setMapSendInfo: Dispatch<SetStateAction<MapSendInfo>>; } export const useMessageSendInfo = (message: MessageState) => { const isMounted = useIsMounted(); // Map of send preferences and send icons for each recipient const [mapSendInfo, setMapSendInfo] = useState<MapSendInfo>({}); const safeSetMapSendInfo = (value: SetStateAction<MapSendInfo>) => isMounted() && setMapSendInfo(value); // Use memo is ok there but not really effective as any message change will update the ref const messageSendInfo: MessageSendInfo = useMemo( () => ({ message, mapSendInfo, setMapSendInfo: safeSetMapSendInfo, }), [message, mapSendInfo] ); return messageSendInfo; }; export const useUpdateRecipientSendInfo = ( messageSendInfo: MessageSendInfo | undefined, recipient: Recipient, onRemove: () => void ) => { const getEncryptionPreferences = useGetEncryptionPreferences(); const contactsMap = useContactsMap(); const emailAddress = recipient.Address; const { ktActivation } = useKeyTransparencyContext(); const [askForKeyPinningModal, handleShowAskForKeyPinningModal] = useModalTwo(AskForKeyPinningModal); const [contactResignModal, handleContactResignModal] = useModalTwo(ContactResignModal); const handleRemove = () => { if (messageSendInfo) { const { setMapSendInfo } = messageSendInfo; setMapSendInfo((mapSendInfo) => omit(mapSendInfo, [emailAddress])); } onRemove(); }; useEffect(() => { const updateRecipientIcon = async (): Promise<void> => { // Inactive if no send info or data already present if (!messageSendInfo || messageSendInfo.mapSendInfo[emailAddress]) { return; } const { message, setMapSendInfo } = messageSendInfo; const emailValidation = validateEmailAddress(emailAddress); // Prevent sending request if email is not even valid if (!emailValidation) { setMapSendInfo((mapSendInfo) => ({ ...mapSendInfo, [emailAddress]: { encryptionPreferenceError: ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR, sendPreferences: undefined, sendIcon: { colorClassName: 'color-danger', isEncrypted: false, fill: STATUS_ICONS_FILLS.FAIL, text: c('Composer email icon').t`The address might be misspelled`, }, loading: false, emailValidation, emailAddressWarnings: [], contactSignatureInfo: undefined, }, })); return; } setMapSendInfo((mapSendInfo) => ({ ...mapSendInfo, [emailAddress]: { loading: true, emailValidation, }, })); const encryptionPreferences = await getEncryptionPreferences({ email: emailAddress, lifetime: 0, contactEmailsMap: contactsMap, }); const sendPreferences = getSendPreferences(encryptionPreferences, message.data); if (sendPreferences.error?.type === CONTACT_SIGNATURE_NOT_VERIFIED) { if (!recipient.ContactID) { return; } const contact = { contactID: recipient.ContactID }; const contactAddress = recipient.Address; const contactName = recipient.Name || contactAddress; const text = c('Info') .t`The verification of ${contactName} has failed: the contact is not signed correctly. This may be the result of a password reset. You must re-sign the contact in order to send a message to ${contactAddress} or edit the contact.`; await handleContactResignModal({ title: c('Title').t`Re-sign contact`, contacts: [contact], onNotResign: onRemove, onError: handleRemove, children: text, }); return updateRecipientIcon(); } if (sendPreferences.error?.type === PRIMARY_NOT_PINNED) { if (!recipient.ContactID) { return; } const contacts = [ { contactID: recipient.ContactID, emailAddress, isInternal: encryptionPreferences.isInternal, bePinnedPublicKey: encryptionPreferences.sendKey as PublicKeyReference, }, ]; await handleShowAskForKeyPinningModal({ contacts, onNotTrust: handleRemove, onError: handleRemove, }); return updateRecipientIcon(); } const sendIcon = getSendStatusIcon(sendPreferences, ktActivation); const contactSignatureInfo = { isVerified: encryptionPreferences.isContactSignatureVerified, creationTime: encryptionPreferences.contactSignatureTimestamp, }; setMapSendInfo((mapSendInfo) => ({ ...mapSendInfo, [emailAddress]: { sendPreferences, sendIcon, loading: false, emailValidation, encryptionPreferenceError: encryptionPreferences.error?.type, emailAddressWarnings: encryptionPreferences.emailAddressWarnings || [], contactSignatureInfo, }, })); }; void updateRecipientIcon(); }, [emailAddress, contactsMap, ktActivation]); return { handleRemove, askForKeyPinningModal, contactResignModal }; }; interface LoadParams { emailAddress: string; contactID: string; contactName: string; abortController: AbortController; checkForError: boolean; } export const useUpdateGroupSendInfo = ( messageSendInfo: MessageSendInfo | undefined, contacts: ContactEmail[], onRemove: () => void ) => { const getEncryptionPreferences = useGetEncryptionPreferences(); const contactsMap = useContactsMap(); const emailsInGroup = contacts.map(({ Email }) => Email); const [askForKeyPinningModal, handleShowAskForKeyPinningModal] = useModalTwo(AskForKeyPinningModal); const [contactResignModal, handleContactResignModal] = useModalTwo(ContactResignModal); const handleRemove = () => { if (messageSendInfo) { const { setMapSendInfo } = messageSendInfo; setMapSendInfo((mapSendInfo) => omit(mapSendInfo, emailsInGroup)); } onRemove(); }; const { ktActivation } = useKeyTransparencyContext(); useEffect(() => { const abortController = new AbortController(); // loadSendIcon tries to load the corresponding icon for an email address. If all goes well, it returns nothing. // If there are errors, it returns an error type and information about the email address that failed const loadSendIcon = async ({ emailAddress, contactID, contactName, abortController, checkForError, }: LoadParams) => { const { signal } = abortController; const icon = messageSendInfo?.mapSendInfo[emailAddress]?.sendIcon; const emailValidation = validateEmailAddress(emailAddress); if ( !emailValidation || !emailAddress || icon || !messageSendInfo || !!messageSendInfo.mapSendInfo[emailAddress] || signal.aborted ) { return; } const { message, setMapSendInfo } = messageSendInfo; if (!signal.aborted) { setMapSendInfo((mapSendInfo) => { const sendInfo = mapSendInfo[emailAddress]; return { ...mapSendInfo, [emailAddress]: { ...sendInfo, loading: true, emailValidation }, }; }); } const encryptionPreferences = await getEncryptionPreferences({ email: emailAddress, lifetime: 0, contactEmailsMap: contactsMap, }); const sendPreferences = getSendPreferences(encryptionPreferences, message.data); const sendIcon = getSendStatusIcon(sendPreferences, ktActivation); const contactSignatureInfo = { isVerified: encryptionPreferences.isContactSignatureVerified, creationTime: encryptionPreferences.contactSignatureTimestamp, }; if (!signal.aborted) { setMapSendInfo((mapSendInfo) => ({ ...mapSendInfo, [emailAddress]: { sendPreferences, sendIcon, loading: false, emailValidation, emailAddressWarnings: encryptionPreferences.emailAddressWarnings || [], contactSignatureInfo, }, })); } if (checkForError && sendPreferences.error) { return { error: sendPreferences.error, contact: { contactID, contactName, emailAddress, isInternal: encryptionPreferences.isInternal, bePinnedPublicKey: encryptionPreferences.sendKey as PublicKeyReference, }, }; } }; const loadSendIcons = async ({ abortController, checkForError, }: Pick<LoadParams, 'abortController' | 'checkForError'>): Promise<void> => { const requests = contacts.map( ({ Email, ContactID, Name }) => () => loadSendIcon({ emailAddress: Email, contactID: ContactID, contactName: Name, abortController, checkForError, }) ); // the routes called in requests support 100 calls every 10 seconds const results = await processApiRequestsSafe(requests, 100, 10 * 1000); const contactsResign = results .filter(isTruthy) .filter(({ error: { type } }) => type === CONTACT_SIGNATURE_NOT_VERIFIED) .map(({ contact }) => contact); const totalContactsResign = contactsResign.length; if (totalContactsResign) { const title = c('Title').ngettext(msgid`Re-sign contact`, `Re-sign contacts`, totalContactsResign); const contactNames = contactsResign.map(({ contactName }) => contactName).join(', '); const contactAddresses = contactsResign.map(({ emailAddress }) => emailAddress).join(', '); const text = c('Info').ngettext( msgid`The verification of ${contactNames} has failed: the contact is not signed correctly. This may be the result of a password reset. You must re-sign the contact in order to send a message to ${contactAddresses} or edit the contact.`, `The verification of ${contactNames} has failed: the contacts are not signed correctly. This may be the result of a password reset. You must re-sign the contacts in order to send a message to ${contactAddresses} or edit the contacts.`, totalContactsResign ); await handleContactResignModal({ title: title, contacts: contactsResign, onNotResign: noop, onError: noop, children: text, }); return loadSendIcons({ abortController, checkForError: false }); } const contactsKeyPinning = results .filter(isTruthy) .filter(({ error: { type } }) => type === PRIMARY_NOT_PINNED) .map(({ contact }) => contact); if (contactsKeyPinning.length) { await handleShowAskForKeyPinningModal({ contacts: contactsKeyPinning, onNotTrust: noop, onError: noop, }); return loadSendIcons({ abortController, checkForError: false }); } }; void loadSendIcons({ abortController, checkForError: true }); return () => { abortController.abort(); }; }, [ktActivation]); return { handleRemove, askForKeyPinningModal, contactResignModal }; }; const getUpdatedSendInfo = async ( emailAddress: string, message: MessageState, setMapSendInfo: Dispatch<SetStateAction<MapSendInfo>>, getEncryptionPreferences: GetEncryptionPreferences, ktActivation: KeyTransparencyActivation, contactsMap: ContactsMap ) => { const encryptionPreferences = await getEncryptionPreferences({ email: emailAddress, lifetime: 0, contactEmailsMap: contactsMap, }); const sendPreferences = getSendPreferences(encryptionPreferences, message.data); const sendIcon = getSendStatusIcon(sendPreferences, ktActivation); const contactSignatureInfo = { isVerified: encryptionPreferences.isContactSignatureVerified, creationTime: encryptionPreferences.contactSignatureTimestamp, }; const updatedSendInfo = { sendPreferences, sendIcon, loading: false, emailAddressWarnings: encryptionPreferences.emailAddressWarnings || [], contactSignatureInfo, }; setMapSendInfo((mapSendInfo) => { const sendInfo = mapSendInfo[emailAddress]; if (!sendInfo) { return { ...mapSendInfo }; } return { ...mapSendInfo, [emailAddress]: { ...sendInfo, ...updatedSendInfo }, }; }); }; export const useReloadSendInfo = () => { const getEncryptionPreferences = useGetEncryptionPreferences(); const contactsMap = useContactsMap(); const { ktActivation } = useKeyTransparencyContext(); return useCallback( async (messageSendInfo: MessageSendInfo | undefined, message: MessageState) => { const { mapSendInfo, setMapSendInfo } = messageSendInfo || {}; if (mapSendInfo === undefined || !setMapSendInfo || !message.data) { return; } const recipients = getRecipientsAddresses(message.data); const requests = recipients.map( (emailAddress) => () => getUpdatedSendInfo( emailAddress, message, setMapSendInfo, getEncryptionPreferences, ktActivation, contactsMap ) ); const loadingMapSendInfo = recipients.reduce( (acc, emailAddress) => { const sendInfo = acc[emailAddress] || { emailValidation: validateEmailAddress(emailAddress) }; acc[emailAddress] = { ...sendInfo, loading: true }; return acc; }, { ...mapSendInfo } ); setMapSendInfo(loadingMapSendInfo); // the routes called in requests support 100 calls every 10 seconds await processApiRequestsSafe(requests, 100, 10 * 1000); }, [getEncryptionPreferences, contactsMap, ktActivation] ); };
3,964
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useShouldMoveOut.test.ts
import useShouldMoveOut from './useShouldMoveOut'; describe('useShouldMoveOut', () => { it('should move out if elementID is not in elementIDs', () => { const onBack = jest.fn(); useShouldMoveOut({ elementID: '1', elementIDs: ['2', '3'], onBack, loadingElements: false, }); expect(onBack).toHaveBeenCalled(); }); it('should do nothing if elements are loading', () => { const onBack = jest.fn(); useShouldMoveOut({ elementID: '1', elementIDs: ['2', '3'], onBack, loadingElements: true, }); expect(onBack).not.toHaveBeenCalled(); }); it('should move out if elementID is not defined', () => { const onBack = jest.fn(); useShouldMoveOut({ elementIDs: ['2', '3'], onBack, loadingElements: false, }); expect(onBack).toHaveBeenCalled(); }); it('should move out if there is not elements', () => { const onBack = jest.fn(); useShouldMoveOut({ elementID: '1', elementIDs: [], onBack, loadingElements: false, }); expect(onBack).toHaveBeenCalled(); }); });
3,965
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useShouldMoveOut.ts
interface Props { elementID?: string; elementIDs: string[]; onBack: () => void; loadingElements: boolean; } const useShouldMoveOut = ({ elementID = '', elementIDs, onBack, loadingElements }: Props) => { if (loadingElements) { return; } const shouldMoveOut = !elementID || elementIDs.length === 0 || !elementIDs.includes(elementID); if (shouldMoveOut) { onBack(); } }; export default useShouldMoveOut;
3,966
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useShowUpsellBanner.ts
import { useEffect, useRef, useState } from 'react'; import { useUser } from '@proton/components/hooks'; import { DAY, MAILBOX_LABEL_IDS, MONTH } from '@proton/shared/lib/constants'; import { getItem, setItem } from '@proton/shared/lib/helpers/storage'; const useShowUpsellBanner = (labelID: string) => { const [user] = useUser(); // Ref that we set to false on the upsell banner unmount so that we can display the banner only the first time const needToShowUpsellBanner = useRef<boolean>(true); /** * Users can dismiss the banner. However, we want to show it again every 3 months * A value is stored in the localStorage so that we know if we need to show it again or not * - If no value is set, user did not click on dismiss => We want to show the banner (if other conditions are valid) * - If value is set * - If it was less than 3 months ago => Hide the banner * - If it was more than 3 months ago => Show the banner (if other conditions are valid) */ const [showAgain, setShowAgain] = useState(false); const userCreateTime = user.CreateTime || 0; const isInbox = labelID === MAILBOX_LABEL_IDS.INBOX; const threeDaysAfterCreationDate = userCreateTime * 1000 + 3 * DAY; /* Display upsell banners if - User is free - The user created his account more than 3 days ago - User is in Inbox - User is seeing the banner for the first time in the session - No other banner is shown in the message list - If a value is found in the localStorage that should trigger a new display */ const canDisplayUpsellBanner = user.isFree && Date.now() > threeDaysAfterCreationDate && isInbox && needToShowUpsellBanner.current && showAgain; const handleDismissBanner = () => { // Set the ref to false so that we hide the banner and update the localStorage value needToShowUpsellBanner.current = false; setShowAgain(false); const now = Date.now(); setItem('DismissedMailUpsellBanner', now.toString()); }; const handleNeedsToShowBanner = (storedTime: number) => { const today = Date.now(); const limitInterval = 3 * MONTH; return storedTime + limitInterval < today; }; // Get the value in the localStorage useEffect(() => { try { const storedTime = getItem('DismissedMailUpsellBanner'); if (storedTime) { setShowAgain(handleNeedsToShowBanner(parseInt(storedTime))); } else { // If no value found, the user did not click on dismiss => we want to show the banner setShowAgain(true); } } catch (e: any) { console.error(e); } }, []); return { canDisplayUpsellBanner, needToShowUpsellBanner, handleDismissBanner }; }; export default useShowUpsellBanner;
3,967
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/useSignatures.ts
// import { useCallback } from 'react'; import { useCache } from '@proton/components'; // import { verify as verifySignature } from '../helpers/signatures'; const CACHE_KEY = 'Signatures'; // TODO: Use a listenable cache to be able to get reactive data from views export type SignatureCache = Map<string, any>; export const useSignaturesCache = (): SignatureCache => { const cache = useCache(); if (!cache.has(CACHE_KEY)) { cache.set(CACHE_KEY, new Map()); } return cache.get(CACHE_KEY); }; // export const useSignatures = () => { // const cache = useSignaturesCache(); // const verify = useCallback((attachment, decryptedAttachment, { publicKeys }, embeddedSigs = []) => // verifySignature(attachment, decryptedAttachment, { publicKeys }, embeddedSigs, cache) // ); // return { verify }; // };
3,968
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useApplyLabels.tsx
import { useCallback } from 'react'; import { c, msgid } from 'ttag'; import { useApi, useEventManager, useLabels, useNotifications } from '@proton/components'; import { labelConversations, unlabelConversations } from '@proton/shared/lib/api/conversations'; import { undoActions } from '@proton/shared/lib/api/mailUndoActions'; import { labelMessages, unlabelMessages } from '@proton/shared/lib/api/messages'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import isTruthy from '@proton/utils/isTruthy'; import UndoActionNotification from '../../components/notifications/UndoActionNotification'; import { SUCCESS_NOTIFICATION_EXPIRATION } from '../../constants'; import { isMessage as testIsMessage } from '../../helpers/elements'; import { backendActionFinished, backendActionStarted } from '../../logic/elements/elementsActions'; import { useAppDispatch } from '../../logic/store'; import { Element } from '../../models/element'; import { useOptimisticApplyLabels } from '../optimistic/useOptimisticApplyLabels'; import { useCreateFilters } from './useCreateFilters'; const getNotificationTextStarred = (isMessage: boolean, elementsCount: number) => { if (isMessage) { if (elementsCount === 1) { return c('Success').t`Message marked as Starred.`; } return c('Success').ngettext( msgid`${elementsCount} message marked as Starred.`, `${elementsCount} messages marked as Starred.`, elementsCount ); } if (elementsCount === 1) { return c('Success').t`Conversation marked as Starred.`; } return c('Success').ngettext( msgid`${elementsCount} conversation marked as Starred.`, `${elementsCount} conversations marked as Starred.`, elementsCount ); }; const getNotificationTextRemoved = (isMessage: boolean, elementsCount: number, labelName: string) => { if (isMessage) { if (elementsCount === 1) { return c('Success').t`Message removed from ${labelName}.`; } return c('Success').ngettext( msgid`${elementsCount} message removed from ${labelName}.`, `${elementsCount} messages removed from ${labelName}.`, elementsCount ); } if (elementsCount === 1) { return c('Success').t`Conversation removed from ${labelName}.`; } return c('Success').ngettext( msgid`${elementsCount} conversation removed from ${labelName}.`, `${elementsCount} conversations removed from ${labelName}.`, elementsCount ); }; const getNotificationTextAdded = (isMessage: boolean, elementsCount: number, labelName: string) => { if (isMessage) { if (elementsCount === 1) { return c('Success').t`Message added to ${labelName}.`; } return c('Success').ngettext( msgid`${elementsCount} message added to ${labelName}.`, `${elementsCount} messages added to ${labelName}.`, elementsCount ); } if (elementsCount === 1) { return c('Success').t`Conversation added to ${labelName}.`; } return c('Success').ngettext( msgid`${elementsCount} conversation added to ${labelName}.`, `${elementsCount} conversations added to ${labelName}.`, elementsCount ); }; export const useApplyLabels = () => { const api = useApi(); const { call, stop, start } = useEventManager(); const { createNotification } = useNotifications(); const [labels = []] = useLabels(); const optimisticApplyLabels = useOptimisticApplyLabels(); const dispatch = useAppDispatch(); const { getFilterActions } = useCreateFilters(); const applyLabels = useCallback( async ( elements: Element[], changes: { [labelID: string]: boolean }, createFilters: boolean, silent = false, selectedLabelIDs: string[] = [] ) => { if (!elements.length) { return; } let undoing = false; const isMessage = testIsMessage(elements[0]); const labelAction = isMessage ? labelMessages : labelConversations; const unlabelAction = isMessage ? unlabelMessages : unlabelConversations; const changesKeys = Object.keys(changes); const elementIDs = elements.map((element) => element.ID); const rollbacks = {} as { [labelID: string]: () => void }; const { doCreateFilters, undoCreateFilters } = getFilterActions(); const handleDo = async () => { let tokens = []; try { // Stop the event manager to prevent race conditions stop(); dispatch(backendActionStarted()); [tokens] = await Promise.all([ Promise.all( changesKeys.map(async (LabelID) => { rollbacks[LabelID] = optimisticApplyLabels(elements, { [LabelID]: changes[LabelID] }); try { const action = changes[LabelID] ? labelAction : unlabelAction; const { UndoToken } = await api<{ UndoToken: { Token: string } }>( action({ LabelID, IDs: elementIDs }) ); return UndoToken.Token; } catch (error: any) { rollbacks[LabelID](); throw error; } }) ), createFilters ? doCreateFilters(elements, selectedLabelIDs, false) : undefined, ]); } finally { dispatch(backendActionFinished()); if (!undoing) { start(); await call(); } } return tokens; }; // No await ==> optimistic const promise = handleDo(); const handleUndo = async () => { try { undoing = true; const tokens = await promise; // Stop the event manager to prevent race conditions stop(); Object.values(rollbacks).forEach((rollback) => rollback()); const filteredTokens = tokens.filter(isTruthy); await Promise.all([ Promise.all(filteredTokens.map((token) => api(undoActions(token)))), createFilters ? undoCreateFilters() : undefined, ]); } finally { start(); await call(); } }; let notificationText = c('Success').t`Labels applied.`; const elementsCount = elementIDs.length; if (changesKeys.length === 1) { const labelName = labels.filter((l) => l.ID === changesKeys[0])[0]?.Name; if (changesKeys[0] === MAILBOX_LABEL_IDS.STARRED) { notificationText = getNotificationTextStarred(isMessage, elementsCount); } else if (!Object.values(changes)[0]) { notificationText = getNotificationTextRemoved(isMessage, elementsCount, labelName); } else { notificationText = getNotificationTextAdded(isMessage, elementsCount, labelName); } } if (!silent) { createNotification({ text: <UndoActionNotification onUndo={handleUndo}>{notificationText}</UndoActionNotification>, expiration: SUCCESS_NOTIFICATION_EXPIRATION, }); } }, [labels] ); return applyLabels; };
3,969
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useCreateFilters.tsx
import { useCallback, useMemo } from 'react'; import { c } from 'ttag'; import { NotificationButton, useAddresses, useApi, useFilters, useFolders, useLabels, useNotifications, } from '@proton/components'; import { useAppLink } from '@proton/components/components'; import { Filter } from '@proton/components/containers/filters/interfaces'; import { createDefaultLabelsFilter } from '@proton/components/containers/filters/utils'; import { addTreeFilter, deleteFilter } from '@proton/shared/lib/api/filters'; import { APPS, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { canonicalizeEmail } from '@proton/shared/lib/helpers/email'; import { Label } from '@proton/shared/lib/interfaces'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import diff from '@proton/utils/diff'; import isTruthy from '@proton/utils/isTruthy'; import unique from '@proton/utils/unique'; import { getSenders, isMessage as testIsMessage } from '../../helpers/elements'; import { getFolderName } from '../../helpers/labels'; import { Element } from '../../models/element'; const { INBOX, TRASH, SPAM, ARCHIVE } = MAILBOX_LABEL_IDS; const DEFAULT_FOLDERS: Folder[] = [ { ID: INBOX, Name: getFolderName(INBOX), } as Folder, { ID: TRASH, Name: getFolderName(TRASH), } as Folder, { ID: SPAM, Name: getFolderName(SPAM), } as Folder, { ID: ARCHIVE, Name: getFolderName(ARCHIVE), } as Folder, ]; const getNotificationTextFolder = (isMessage: boolean, senders: string[], folder: string) => { let notificationText: string; const sendersList = senders.join(', '); if (isMessage) { notificationText = c('Success').t`Messages from ${sendersList} will be moved to ${folder}`; } else { notificationText = c('Success').t`Conversations from ${sendersList} will be moved to ${folder}`; } return notificationText; }; const getNotificationTextLabels = (isMessage: boolean, senders: string[], labels: string[]) => { let notificationText: string; const sendersList = senders.join(', '); const labelsList = labels.join(', '); if (isMessage) { notificationText = c('Success').t`Messages from ${sendersList} will be labelled as ${labelsList}`; } else { notificationText = c('Success').t`Conversations from ${sendersList} will be labelled as ${labelsList}`; } return notificationText; }; export const useCreateFilters = () => { const { createNotification, hideNotification } = useNotifications(); const [filters = []] = useFilters(); const api = useApi(); const appLink = useAppLink(); const [labels = []] = useLabels(); const [folders = []] = useFolders(); const [addresses = []] = useAddresses(); const ownAddresses = useMemo(() => { return addresses.map((address) => canonicalizeEmail(address.Email)); }, [addresses]); const getSendersToFilter = useCallback( (elements: Element[]) => { const allSenderAddresses = unique( elements .flatMap((element) => getSenders(element)) .map((recipient) => recipient?.Address) .filter(isTruthy) .map((email) => canonicalizeEmail(email)) ); const senders = diff(allSenderAddresses, ownAddresses); return senders; }, [ownAddresses] ); const getFilterActions = useCallback(() => { let createdFilters: Filter[] = []; let notificationID: number | undefined; const doCreateFilters = async (elements: Element[], labelIDs: string[], isFolder: boolean) => { const senders = getSendersToFilter(elements); const usedLabels: (Label | Folder)[] = isFolder ? [...folders, ...DEFAULT_FOLDERS] : labels; const appliedLabels = labelIDs .map((labelID) => usedLabels.find((label) => label.ID === labelID)) .filter(isTruthy); const newFilters = createDefaultLabelsFilter(senders, appliedLabels, filters); const results = await Promise.all( newFilters.map((filter) => api<{ Filter: Filter }>(addTreeFilter(filter, isFolder ? 'AutoFolder' : 'AutoLabel')) ) ); createdFilters = results.map((result) => result.Filter); const isMessage = testIsMessage(elements[0]); const notificationText = isFolder ? getNotificationTextFolder(isMessage, senders, appliedLabels[0].Name) : getNotificationTextLabels( isMessage, senders, appliedLabels.map((label) => label.Name) ); notificationID = createNotification({ text: ( <> <span>{notificationText}</span> <NotificationButton onClick={() => { appLink('/mail/filters', APPS.PROTONACCOUNT); }} > {c('Action').t`Edit`} </NotificationButton> </> ), }); }; const undoCreateFilters = async () => { if (notificationID !== undefined) { hideNotification(notificationID); } return Promise.all(createdFilters.map((filter) => api(deleteFilter(filter.ID)))); }; return { getSendersToFilter, doCreateFilters, undoCreateFilters }; }, [filters, labels, folders, getSendersToFilter]); return { getSendersToFilter, getFilterActions }; };
3,970
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useEmptyLabel.tsx
import { useCallback, useMemo, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ErrorButton, Prompt, useApi, useEventManager, useFolders, useLabels, useModalState, useNotifications, } from '@proton/components'; import { emptyLabel as emptyLabelRequest } from '@proton/shared/lib/api/messages'; import { isCustomLabel } from '../../helpers/labels'; import { backendActionFinished, backendActionStarted } from '../../logic/elements/elementsActions'; import { useAppDispatch } from '../../logic/store'; import { useOptimisticEmptyLabel } from '../optimistic/useOptimisticEmptyLabel'; export const useEmptyLabel = () => { const { createNotification } = useNotifications(); const { call } = useEventManager(); const api = useApi(); const optimisticEmptyLabel = useOptimisticEmptyLabel(); const [labels = []] = useLabels(); const [folders = []] = useFolders(); const dispatch = useAppDispatch(); const [labelID, setLabelID] = useState<string>(''); const [deleteModalProps, setDeleteModalOpen] = useModalState(); const isLabel = useMemo(() => { return isCustomLabel(labelID, labels); }, [labelID]); const handleSubmit = async () => { deleteModalProps.onClose(); let rollback = () => {}; try { dispatch(backendActionStarted()); rollback = optimisticEmptyLabel(labelID); await api(emptyLabelRequest({ LabelID: labelID, AddressID: undefined })); } catch (error: any) { rollback(); throw error; } finally { dispatch(backendActionFinished()); } await call(); createNotification({ text: isLabel ? // translator: Notification displayed when the user clicked on the "Delete all" action inside a custom label c('empty messages: success').t`Label cleared` : // translator: Notification displayed when the user clicked on the "Delete all" action inside a custom folder c('empty messages: success').t`Folder cleared`, }); }; const modal = ( <Prompt title={c('Title').t`Delete all messages`} buttons={[ <ErrorButton data-testid="confirm-empty-folder" onClick={handleSubmit}> {c('Action').t`Delete`} </ErrorButton>, <Button onClick={deleteModalProps.onClose}>{c('Action').t`Cancel`}</Button>, ]} {...deleteModalProps} > {isLabel ? ( <> {c('Info').t`All messages stored with this label will be permanently deleted.`} <br /> {c('Info').t`Are you sure you want to delete all messages with this label?`} </> ) : ( <> {c('Info').t`All messages stored in this folder will be permanently deleted.`} <br /> {c('Info').t`Are you sure you want to delete all messages in this folder?`} </> )} </Prompt> ); const emptyLabel = useCallback( async (labelID: string) => { setLabelID(labelID); setDeleteModalOpen(true); }, [labels, folders] ); return { emptyLabel, modal }; };
3,971
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useMarkAs.tsx
import { useCallback } from 'react'; import { c, msgid } from 'ttag'; import { useApi, useEventManager, useNotifications } from '@proton/components'; import { markConversationsAsRead, markConversationsAsUnread } from '@proton/shared/lib/api/conversations'; import { undoActions } from '@proton/shared/lib/api/mailUndoActions'; import { markMessageAsRead, markMessageAsUnread } from '@proton/shared/lib/api/messages'; import UndoActionNotification from '../../components/notifications/UndoActionNotification'; import { SUCCESS_NOTIFICATION_EXPIRATION } from '../../constants'; import { isMessage as testIsMessage } from '../../helpers/elements'; import { backendActionFinished, backendActionStarted } from '../../logic/elements/elementsActions'; import { isElementReminded } from '../../logic/snoozehelpers'; import { useAppDispatch } from '../../logic/store'; import { Element } from '../../models/element'; import { useOptimisticMarkAs } from '../optimistic/useOptimisticMarkAs'; export enum MARK_AS_STATUS { READ = 'read', UNREAD = 'unread', } const getNotificationTextMarked = (isMessage: boolean, elementsCount: number, status: MARK_AS_STATUS) => { if (isMessage) { if (elementsCount === 1) { return status === MARK_AS_STATUS.READ ? c('Success').t`Message marked as read.` : c('Success').t`Message marked as unread.`; } return status === MARK_AS_STATUS.READ ? c('Success').ngettext( msgid`${elementsCount} message marked as read.`, `${elementsCount} messages marked as read.`, elementsCount ) : c('Success').ngettext( msgid`${elementsCount} message marked as unread.`, `${elementsCount} messages marked as unread.`, elementsCount ); } if (elementsCount === 1) { return status === MARK_AS_STATUS.READ ? c('Success').t`Conversation marked as read.` : c('Success').t`Conversation marked as unread.`; } return status === MARK_AS_STATUS.READ ? c('Success').ngettext( msgid`${elementsCount} conversation marked as read.`, `${elementsCount} conversations marked as read.`, elementsCount ) : c('Success').ngettext( msgid`${elementsCount} conversation marked as unread.`, `${elementsCount} conversations marked as unread.`, elementsCount ); }; export const useMarkAs = () => { const api = useApi(); const { call, start, stop } = useEventManager(); const optimisticMarkAs = useOptimisticMarkAs(); const { createNotification } = useNotifications(); const dispatch = useAppDispatch(); const markAs = useCallback((elements: Element[], labelID = '', status: MARK_AS_STATUS, silent = true) => { if (!elements.length) { return; } const isMessage = testIsMessage(elements[0]); const markAsReadAction = isMessage ? markMessageAsRead : markConversationsAsRead; const markAsUnreadAction = isMessage ? markMessageAsUnread : markConversationsAsUnread; const action = status === MARK_AS_STATUS.READ ? markAsReadAction : markAsUnreadAction; const displaySnoozedReminder = status === MARK_AS_STATUS.READ ? false : isElementReminded(elements[0]); let rollback: (() => void) | undefined = () => {}; const request = async () => { let token; try { // Stop the event manager to prevent race conditions stop(); dispatch(backendActionStarted()); rollback = optimisticMarkAs(elements, labelID, { status, displaySnoozedReminder, }); const { UndoToken } = await api( action( elements.map((element) => element.ID), labelID ) ); token = UndoToken.Token; } catch (error: any) { rollback?.(); throw error; } finally { dispatch(backendActionFinished()); start(); await call(); } return token; }; // No await since we are doing optimistic UI here const promise = request(); if (!silent) { const notificationText = getNotificationTextMarked(isMessage, elements.length, status); const handleUndo = async () => { try { // Stop the event manager to prevent race conditions stop(); rollback?.(); const token = await promise; await api(undoActions(token)); } finally { start(); await call(); } }; createNotification({ text: <UndoActionNotification onUndo={handleUndo}>{notificationText}</UndoActionNotification>, expiration: SUCCESS_NOTIFICATION_EXPIRATION, }); } }, []); return markAs; };
3,972
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useMoveAll.tsx
import { useCallback, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ErrorButton, Prompt, useApi, useFolders, useModalState } from '@proton/components'; import { TelemetryMailSelectAllEvents } from '@proton/shared/lib/api/telemetry'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { getCleanedFolderID, sendSelectAllTelemetryReport } from 'proton-mail/helpers/moveToFolder'; import { moveAll } from '../../logic/elements/elementsActions'; import { useAppDispatch } from '../../logic/store'; const getTitle = (destinationLabelID: string) => { switch (destinationLabelID) { case MAILBOX_LABEL_IDS.TRASH: return c('Title').t`Move all messages to Trash`; case MAILBOX_LABEL_IDS.ARCHIVE: return c('Title').t`Move all messages to Archive`; default: return ''; } }; const getContent = (destinationLabelID: string) => { switch (destinationLabelID) { case MAILBOX_LABEL_IDS.TRASH: return c('Info').t`Are you sure you want to move all messages in this location to Trash?`; case MAILBOX_LABEL_IDS.ARCHIVE: return c('Info').t`Are you sure you want to move all messages in this location to Archive?`; default: return ''; } }; export const useMoveAll = () => { const [folders = []] = useFolders(); const api = useApi(); const dispatch = useAppDispatch(); const [modalProps, setModalOpen] = useModalState(); const [actionProps, setActionProps] = useState<{ SourceLabelID: string; DestinationLabelID: string }>({ SourceLabelID: '', DestinationLabelID: MAILBOX_LABEL_IDS.TRASH, }); const handleSubmit = async () => { // We want to see how much and how the Move all feature is used // For that, we need to know from where the user performed the action // However custom folders have a unique ID, so we return "custom_folder" instead const { SourceLabelID } = actionProps; const cleanedSourceLabelID = getCleanedFolderID(SourceLabelID, folders); void sendSelectAllTelemetryReport({ api, sourceLabelID: cleanedSourceLabelID, event: TelemetryMailSelectAllEvents.notification_move_to, }); void dispatch(moveAll({ ...actionProps })); modalProps.onClose?.(); }; const modal = ( <Prompt title={getTitle(actionProps.DestinationLabelID)} buttons={[ <ErrorButton data-testid="confirm-empty-folder" onClick={handleSubmit}> {c('Action').t`Move`} </ErrorButton>, <Button onClick={modalProps.onClose}>{c('Action').t`Cancel`}</Button>, ]} {...modalProps} > {getContent(actionProps.DestinationLabelID)} </Prompt> ); const moveAllCallback = useCallback((SourceLabelID: string, DestinationLabelID: string) => { setActionProps({ SourceLabelID, DestinationLabelID }); setModalOpen(true); }, []); return { moveAll: moveAllCallback, modal }; };
3,973
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useMoveToFolder.tsx
import { Dispatch, SetStateAction, useCallback, useState } from 'react'; import { useLocation } from 'react-router-dom'; import { useApi, useEventManager, useFolders, useLabels, useNotifications } from '@proton/components'; import { useModalTwo } from '@proton/components/components/modalTwo/useModalTwo'; import { labelConversations } from '@proton/shared/lib/api/conversations'; import { undoActions } from '@proton/shared/lib/api/mailUndoActions'; import { labelMessages } from '@proton/shared/lib/api/messages'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { SPAM_ACTION } from '@proton/shared/lib/mail/mailSettings'; import MoveSnoozedModal from '../../components/list/snooze/components/MoveSnoozedModal'; import MoveScheduledModal from '../../components/message/modals/MoveScheduledModal'; import MoveToSpamModal from '../../components/message/modals/MoveToSpamModal'; import MoveAllNotificationButton from '../../components/notifications/MoveAllNotificationButton'; import UndoActionNotification from '../../components/notifications/UndoActionNotification'; import { PAGE_SIZE, SUCCESS_NOTIFICATION_EXPIRATION } from '../../constants'; import { isMessage as testIsMessage, isSearch as testIsSearch } from '../../helpers/elements'; import { isCustomLabel, isLabel } from '../../helpers/labels'; import { extractSearchParameters } from '../../helpers/mailboxUrl'; import { getMessagesAuthorizedToMove } from '../../helpers/message/messages'; import { askToUnsubscribe, getNotificationTextMoved, getNotificationTextUnauthorized, searchForScheduled, searchForSnoozed, } from '../../helpers/moveToFolder'; import { useDeepMemo } from '../../hooks/useDeepMemo'; import useMailModel from '../../hooks/useMailModel'; import { backendActionFinished, backendActionStarted } from '../../logic/elements/elementsActions'; import { useAppDispatch } from '../../logic/store'; import { Element } from '../../models/element'; import { SearchParameters } from '../../models/tools'; import { useOptimisticApplyLabels } from '../optimistic/useOptimisticApplyLabels'; import { useCreateFilters } from './useCreateFilters'; import { useMoveAll } from './useMoveAll'; const { TRASH, ARCHIVE, ALMOST_ALL_MAIL: ALMOST_ALL_MAIL_ID, SNOOZED, ALL_MAIL, INBOX } = MAILBOX_LABEL_IDS; const MOVE_ALL_FOLDERS = [TRASH, ARCHIVE]; export const useMoveToFolder = (setContainFocus?: Dispatch<SetStateAction<boolean>>) => { const api = useApi(); const location = useLocation(); const { call, stop, start } = useEventManager(); const { createNotification } = useNotifications(); const [labels = []] = useLabels(); const [folders = []] = useFolders(); const optimisticApplyLabels = useOptimisticApplyLabels(); const mailSettings = useMailModel('MailSettings'); const dispatch = useAppDispatch(); const { getFilterActions } = useCreateFilters(); const searchParameters = useDeepMemo<SearchParameters>(() => extractSearchParameters(location), [location]); const isSearch = testIsSearch(searchParameters); const [canUndo, setCanUndo] = useState(true); // Used to not display the Undo button if moving only scheduled messages/conversations to trash const { moveAll, modal: moveAllModal } = useMoveAll(); const [moveScheduledModal, handleShowScheduledModal] = useModalTwo(MoveScheduledModal); const [moveSnoozedModal, handleMoveSnoozedModal] = useModalTwo(MoveSnoozedModal); const [moveToSpamModal, handleShowSpamModal] = useModalTwo< { isMessage: boolean; elements: Element[] }, { unsubscribe: boolean; remember: boolean } >(MoveToSpamModal); const moveToFolder = useCallback( async ( elements: Element[], folderID: string, folderName: string, fromLabelID: string, createFilters: boolean, silent = false, askUnsub = true ) => { if (!elements.length) { return; } let undoing = false; const isMessage = testIsMessage(elements[0]); const destinationLabelID = isCustomLabel(fromLabelID, labels) ? INBOX : fromLabelID; // Open a modal when moving a scheduled message/conversation to trash to inform the user that it will be cancelled await searchForScheduled( folderID, isMessage, elements, setCanUndo, handleShowScheduledModal, setContainFocus ); // Open a modal when moving a snoozed message/conversation to trash or archive to inform the user that it will be cancelled // We only check if we're in the ALMOST_ALL_MAIL, ALL_MAIL or SNOOZE folder since this is the only place where we have snoozed emails if (fromLabelID === ALMOST_ALL_MAIL_ID || fromLabelID === ALL_MAIL || fromLabelID === SNOOZED) { await searchForSnoozed( folderID, isMessage, elements, setCanUndo, handleMoveSnoozedModal, setContainFocus, folders ); } let spamAction: SPAM_ACTION | undefined = undefined; if (askUnsub) { // Open a modal when moving items to spam to propose to unsubscribe them spamAction = await askToUnsubscribe( folderID, isMessage, elements, api, handleShowSpamModal, mailSettings ); } const action = isMessage ? labelMessages : labelConversations; const authorizedToMove = isMessage ? getMessagesAuthorizedToMove(elements as Message[], folderID) : elements; const elementIDs = authorizedToMove.map((element) => element.ID); if (!authorizedToMove.length) { createNotification({ text: getNotificationTextUnauthorized(folderID, destinationLabelID), type: 'error', }); return; } const { doCreateFilters, undoCreateFilters } = getFilterActions(); let rollback = () => {}; const handleDo = async () => { let token; try { // Stop the event manager to prevent race conditions stop(); dispatch(backendActionStarted()); rollback = optimisticApplyLabels( authorizedToMove, { [folderID]: true }, true, [], destinationLabelID ); const [{ UndoToken }] = await Promise.all([ api<{ UndoToken: { Token: string } }>( action({ LabelID: folderID, IDs: elementIDs, SpamAction: spamAction }) ), createFilters ? doCreateFilters(elements, [folderID], true) : undefined, ]); // We are not checking ValidUntil since notification stay for few seconds after this action token = UndoToken.Token; } catch (error: any) { rollback(); } finally { dispatch(backendActionFinished()); if (!undoing) { start(); await call(); } } return token; }; // No await ==> optimistic const promise = handleDo(); if (!silent) { const notificationText = getNotificationTextMoved( isMessage, authorizedToMove.length, elements.length - authorizedToMove.length, folderName, folderID, destinationLabelID ); const handleUndo = async () => { try { undoing = true; const token = await promise; // Stop the event manager to prevent race conditions stop(); rollback(); await Promise.all([ token !== undefined ? api(undoActions(token)) : undefined, createFilters ? undoCreateFilters() : undefined, ]); } finally { start(); await call(); } }; const suggestMoveAll = elements.length === PAGE_SIZE && MOVE_ALL_FOLDERS.includes(folderID as MAILBOX_LABEL_IDS) && !isCustomLabel(fromLabelID, labels) && !isSearch; const handleMoveAll = suggestMoveAll ? () => moveAll(fromLabelID, folderID) : undefined; const moveAllButton = handleMoveAll ? ( <MoveAllNotificationButton onMoveAll={handleMoveAll} isMessage={isMessage} isLabel={isLabel(fromLabelID, labels)} /> ) : null; createNotification({ text: ( <UndoActionNotification onUndo={canUndo ? handleUndo : undefined}> <span className="text-left"> {notificationText} {moveAllButton} </span> </UndoActionNotification> ), expiration: SUCCESS_NOTIFICATION_EXPIRATION, }); } }, [labels] ); return { moveToFolder, moveScheduledModal, moveSnoozedModal, moveAllModal, moveToSpamModal }; };
3,974
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/usePermanentDelete.tsx
import { useMemo, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { ErrorButton, Prompt, useApi, useEventManager, useModalState, useNotifications } from '@proton/components'; import { deleteConversations } from '@proton/shared/lib/api/conversations'; import { deleteMessages } from '@proton/shared/lib/api/messages'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { isConversation } from '../../helpers/elements'; import { backendActionFinished, backendActionStarted } from '../../logic/elements/elementsActions'; import { useAppDispatch } from '../../logic/store'; import { useGetElementsFromIDs } from '../mailbox/useElements'; import useOptimisticDelete from '../optimistic/useOptimisticDelete'; const { DRAFTS, ALL_DRAFTS } = MAILBOX_LABEL_IDS; export const getDeleteTitle = ( isDraft: boolean, isConversationMode: boolean, count: number, totalMessages?: number ) => { if (isDraft) { if (count === 1) { // translator: deleting strictly 1 draft return c('Title').t`Delete draft`; } // translator: number of drafts to delete, the variable is a positive integer (written in digits) always greater than 1 return c('Title').ngettext(msgid`Delete ${count} draft`, `Delete ${count} drafts`, count); } if (isConversationMode) { if (count === 1) { if (totalMessages === 1) { // translator: deleting strictly 1 message return c('Title').t`Delete message`; } // translator: deleting strictly 1 conversation return c('Title').t`Delete conversation`; } // translator: number of conversations to delete, the variable is a positive integer (written in digits) always greater than 1 return c('Title').ngettext(msgid`Delete ${count} conversation`, `Delete ${count} conversations`, count); } if (count === 1) { // translator: deleting strictly 1 message return c('Title').t`Delete message`; } // translator: number of messages to delete, the variable is a positive integer (written in digits) always greater than 1 return c('Title').ngettext(msgid`Delete ${count} message`, `Delete ${count} messages`, count); }; export const getModalText = (isDraft: boolean, isConversationMode: boolean, count: number, totalMessages?: number) => { if (isDraft) { if (count === 1) { // translator: deleting strictly 1 draft return c('Info').t`Are you sure you want to permanently delete this draft?`; } // translator: number of drafts to delete, the variable is a positive integer (written in digits) always greater than 1 return c('Info').ngettext( msgid`Are you sure you want to permanently delete ${count} draft?`, `Are you sure you want to permanently delete ${count} drafts?`, count ); } if (isConversationMode) { if (count === 1) { if (totalMessages === 1) { // translator: deleting strictly 1 message return c('Info').t`Are you sure you want to permanently delete this message?`; } // translator: deleting strictly 1 conversation return c('Info').t`Are you sure you want to permanently delete this conversation?`; } // translator: number of conversations to delete, the variable is a positive integer (written in digits) always greater than 1 return c('Info').ngettext( msgid`Are you sure you want to permanently delete ${count} conversation?`, `Are you sure you want to permanently delete ${count} conversations?`, count ); } if (count === 1) { // translator: deleting strictly 1 message return c('Info').t`Are you sure you want to permanently delete this message?`; } // translator: number of messages to delete, the variable is a positive integer (written in digits) always greater than 1 return c('Info').ngettext( msgid`Are you sure you want to permanently delete ${count} message?`, `Are you sure you want to permanently delete ${count} messages?`, count ); }; export const getNotificationText = ( isDraft: boolean, isConversationMode: boolean, count: number, totalMessages?: number ) => { if (isDraft) { if (count === 1) { // translator: deleting strictly 1 draft return c('Success').t`Draft deleted`; } // translator: number of drafts to delete, the variable is a positive integer (written in digits) always greater than 1 return c('Success').ngettext(msgid`${count} draft deleted`, `${count} drafts deleted`, count); } if (isConversationMode) { if (count === 1) { if (totalMessages === 1) { // translator: deleting strictly 1 message return c('Success').t`Message deleted`; } // translator: deleting strictly 1 conversation return c('Success').t`Conversation deleted`; } // translator: number of conversations to delete, the variable is a positive integer (written in digits) always greater than 1 return c('Success').ngettext(msgid`${count} conversation deleted`, `${count} conversations deleted`, count); } if (count === 1) { // translator: deleting strictly 1 message return c('Success').t`Message deleted`; } // translator: number of messages to delete, the variable is a positive integer (written in digits) always greater than 1 return c('Success').ngettext(msgid`${count} message deleted`, `${count} messages deleted`, count); }; export const usePermanentDelete = (labelID: string) => { const { createNotification } = useNotifications(); const { call } = useEventManager(); const api = useApi(); const getElementsFromIDs = useGetElementsFromIDs(); const optimisticDelete = useOptimisticDelete(); const dispatch = useAppDispatch(); const [selectedIDs, setSelectedIDs] = useState<string[]>([]); const [deleteModalProps, setDeleteModalOpen] = useModalState(); const draft = labelID === DRAFTS || labelID === ALL_DRAFTS; const selectedItemsCount = useMemo(() => { return selectedIDs.length; }, [selectedIDs]); const elements = useMemo(() => { return getElementsFromIDs(selectedIDs); }, [selectedIDs]); // If the selected item is a conversation, it may contain more than one message. // We need to know how much messages we want to delete in order to display a specific message if we only delete one of them const totalMessages = useMemo(() => { return elements.reduce((total, element) => { return total + (('ContextNumMessages' in element && element.ContextNumMessages) || 0); }, 0); }, [elements]); const conversationMode = isConversation(elements[0]); const handleSubmit = async () => { deleteModalProps.onClose(); let rollback = () => {}; try { dispatch(backendActionStarted()); rollback = optimisticDelete(elements, labelID); const action = conversationMode ? deleteConversations(selectedIDs, labelID) : deleteMessages(selectedIDs); await api(action); const notificationText = getNotificationText(draft, conversationMode, selectedItemsCount, totalMessages); createNotification({ text: notificationText }); } catch { rollback(); } finally { dispatch(backendActionFinished()); } await call(); }; const modal = ( <Prompt title={getDeleteTitle(draft, conversationMode, selectedItemsCount, totalMessages)} buttons={[ <ErrorButton onClick={handleSubmit} data-testid="permanent-delete-modal:submit">{c('Action') .t`Delete`}</ErrorButton>, <Button onClick={deleteModalProps.onClose}>{c('Action').t`Cancel`}</Button>, ]} {...deleteModalProps} > {getModalText(draft, conversationMode, selectedItemsCount, totalMessages)} </Prompt> ); const handleDelete = async (selectedIDs: string[]) => { setSelectedIDs(selectedIDs); setDeleteModalOpen(true); }; return { handleDelete, modal }; };
3,975
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useSnooze.test.ts
import * as reactRedux from 'react-redux'; import { act, renderHook } from '@testing-library/react-hooks'; import { useFlag } from '@proton/components/containers'; import useSnooze from './useSnooze'; jest.mock('@proton/components/containers/unleash'); jest.mock('react-redux', () => ({ ...jest.requireActual('react-redux'), useSelector: jest.fn(), })); jest.mock('@proton/components/hooks', () => ({ useUser: () => [{ hasPaidMail: false }, jest.fn], })); jest.mock('@proton/components/hooks', () => ({ useEventManager: () => ({ call: jest.fn(), stop: jest.fn(), start: jest.fn() }), useNotifications: () => ({ createNotification: jest.fn() }), useApi: () => jest.fn(), })); jest.mock('../optimistic/useOptimisticApplyLabels', () => ({ useOptimisticApplyLabels: () => jest.fn(), })); jest.mock('../../logic/store', () => ({ useAppDispatch: () => jest.fn(), })); describe('useSnooze', () => { const useSelectorMock = reactRedux.useSelector as jest.Mock; const mockedUseFlag = useFlag as jest.Mock; beforeEach(() => { useSelectorMock.mockReturnValue({ labelID: '0', conversationMode: true }); mockedUseFlag.mockReturnValue(true); }); afterEach(() => { useSelectorMock.mockClear(); }); it('canSnooze should be true when in inbox and conversation mode', () => { useSelectorMock.mockReturnValue({ labelID: '0', conversationMode: true }); const { result } = renderHook(() => useSnooze()); expect(result.current.canSnooze).toEqual(true); expect(result.current.isSnoozeEnabled).toEqual(true); }); it('canSnooze should be false when in inbox and not conversation mode', () => { useSelectorMock.mockReturnValue({ labelID: '0', conversationMode: false }); const { result } = renderHook(() => useSnooze()); expect(result.current.canSnooze).toEqual(false); expect(result.current.isSnoozeEnabled).toEqual(true); }); it('canUnsnooze should be true when in snooze and conversation mode', () => { useSelectorMock.mockReturnValue({ labelID: '16', conversationMode: true }); const { result } = renderHook(() => useSnooze()); expect(result.current.canUnsnooze).toEqual(true); expect(result.current.isSnoozeEnabled).toEqual(true); }); it('canUnsnooze should be false when in snooze and not conversation mode', () => { useSelectorMock.mockReturnValue({ labelID: '16', conversationMode: false }); const { result } = renderHook(() => useSnooze()); expect(result.current.canUnsnooze).toEqual(false); expect(result.current.isSnoozeEnabled).toEqual(true); }); it('isSnoozeEnabled should be false when flag is off', () => { mockedUseFlag.mockReturnValue(false); const { result } = renderHook(() => useSnooze()); expect(result.current.isSnoozeEnabled).toEqual(false); }); it('should update snooze state after custom click and close', () => { const { result } = renderHook(() => useSnooze()); expect(result.current.snoozeState).toEqual('snooze-selection'); act(() => { result.current.handleCustomClick(); }); expect(result.current.snoozeState).toEqual('custom-snooze'); act(() => { result.current.handleClose(); }); expect(result.current.snoozeState).toEqual('snooze-selection'); }); });
3,976
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useSnooze.ts
import { useState } from 'react'; import { useSelector } from 'react-redux'; import { useFlag } from '@proton/components/containers'; import { useApi, useEventManager, useNotifications } from '@proton/components/hooks'; import { snoozeConversations, unsnoozeConversations } from '@proton/shared/lib/api/conversations'; import { MAILBOX_IDENTIFIERS, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { backendActionFinished, backendActionStarted } from '../../logic/elements/elementsActions'; import { params } from '../../logic/elements/elementsSelectors'; import { getSnoozeNotificationText, getSnoozeUnixTime } from '../../logic/snoozehelpers'; import { useAppDispatch } from '../../logic/store'; import { Element } from '../../models/element'; import { useOptimisticApplyLabels } from '../optimistic/useOptimisticApplyLabels'; export type SNOOZE_DURATION = 'tomorrow' | 'later' | 'weekend' | 'nextweek' | 'custom'; type SnoozeState = 'snooze-selection' | 'custom-snooze'; type SnoozeProps = { elements: Element[]; duration: SNOOZE_DURATION; snoozeTime?: Date; }; const useSnooze = () => { const { labelID, conversationMode } = useSelector(params); const isSnoozeEnabled = useFlag('SnoozeFeature'); const api = useApi(); const { createNotification } = useNotifications(); const { call, stop, start } = useEventManager(); const optimisticApplyLabels = useOptimisticApplyLabels(); const dispatch = useAppDispatch(); const [snoozeState, setSnoozeState] = useState<SnoozeState>('snooze-selection'); const isInbox = labelID === MAILBOX_IDENTIFIERS.inbox; const isSnoozed = labelID === MAILBOX_LABEL_IDS.SNOOZED; const canSnooze = isInbox && conversationMode; const canUnsnooze = isSnoozed && conversationMode; const proceedSnoozeUnsnooze = async (elements: Element[], snooze: boolean, data?: SnoozeProps) => { const conversationIDs = elements.map(({ ID }) => ID); const snoozeText = getSnoozeNotificationText(snooze, elements.length); let rollback = () => {}; try { stop(); dispatch(backendActionStarted()); rollback = optimisticApplyLabels(elements, { [MAILBOX_LABEL_IDS.SNOOZED]: snooze }, true); if (snooze && data) { const { duration, snoozeTime } = data; const time = duration === 'custom' ? snoozeTime : undefined; const snoozeUnixTime = getSnoozeUnixTime(duration, time); await api(snoozeConversations(conversationIDs, snoozeUnixTime)); } else { await api(unsnoozeConversations(conversationIDs)); } createNotification({ text: snoozeText }); } catch (error: any) { rollback(); throw error; } finally { dispatch(backendActionFinished()); start(); await call(); } }; const snooze = async (data: SnoozeProps) => { await proceedSnoozeUnsnooze(data.elements, true, data); }; const unsnooze = async (elements: Element[]) => { await proceedSnoozeUnsnooze(elements, false); }; const handleCustomClick = () => { setSnoozeState('custom-snooze'); }; const handleClose = () => { setSnoozeState('snooze-selection'); }; return { isSnoozeEnabled, canSnooze, canUnsnooze, snooze, unsnooze, handleClose, handleCustomClick, snoozeState, }; }; export default useSnooze;
3,977
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/actions/useStar.tsx
import { useCallback } from 'react'; import { useApi, useEventManager } from '@proton/components'; import { labelConversations, unlabelConversations } from '@proton/shared/lib/api/conversations'; import { labelMessages, unlabelMessages } from '@proton/shared/lib/api/messages'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { isMessage as testIsMessage } from '../../helpers/elements'; import { backendActionFinished, backendActionStarted } from '../../logic/elements/elementsActions'; import { useAppDispatch } from '../../logic/store'; import { Element } from '../../models/element'; import { useOptimisticApplyLabels } from '../optimistic/useOptimisticApplyLabels'; export const useStar = () => { const api = useApi(); const { call, stop, start } = useEventManager(); const optimisticApplyLabels = useOptimisticApplyLabels(); const dispatch = useAppDispatch(); const star = useCallback(async (elements: Element[], value: boolean) => { if (!elements.length) { return; } const isMessage = testIsMessage(elements[0]); const labelAction = isMessage ? labelMessages : labelConversations; const unlabelAction = isMessage ? unlabelMessages : unlabelConversations; const action = value ? labelAction : unlabelAction; let rollback = () => {}; try { // Stop the event manager to prevent race conditions stop(); dispatch(backendActionStarted()); rollback = optimisticApplyLabels(elements, { [MAILBOX_LABEL_IDS.STARRED]: value }); await api(action({ LabelID: MAILBOX_LABEL_IDS.STARRED, IDs: elements.map((element) => element.ID) })); } catch (error: any) { rollback(); throw error; } finally { dispatch(backendActionFinished()); start(); await call(); } }, []); return star; };
3,978
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/attachments/useAttachment.ts
import { useCallback } from 'react'; import { useStore } from 'react-redux'; import { attachmentByID } from '../../logic/attachments/attachmentsSelectors'; import { RootState } from '../../logic/store'; export const useGetAttachment = () => { const store = useStore<RootState>(); return useCallback((ID: string) => attachmentByID(store.getState(), { ID }), []); };
3,979
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/attachments/useAttachmentThumbnailDownload.ts
import JSBI from 'jsbi'; import { useModalTwo } from '@proton/components/components'; import { useApi, useGetVerificationPreferences } from '@proton/components/hooks'; import { WorkerDecryptionResult } from '@proton/crypto'; import { getAttachment as getAttachmentRequest, getAttachmentsMetadata } from '@proton/shared/lib/api/attachments'; import { AttachmentFullMetadata, AttachmentsMetadata } from '@proton/shared/lib/interfaces/mail/Message'; import { MESSAGE_FLAGS, VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { getSessionKey } from '@proton/shared/lib/mail/send/attachments'; import ConfirmDownloadAttachments from 'proton-mail/components/attachment/modals/ConfirmDownloadAttachments'; import { Download, generateDownload } from 'proton-mail/helpers/attachment/attachmentDownloader'; import { decryptAndVerify, getVerificationStatusFromKeys } from 'proton-mail/helpers/attachment/attachmentLoader'; import { useGetAttachment } from 'proton-mail/hooks/attachments/useAttachment'; import { useContactsMap } from 'proton-mail/hooks/contact/useContacts'; import { useGetMessageKeys } from 'proton-mail/hooks/message/useGetMessageKeys'; import { updateAttachment } from 'proton-mail/logic/attachments/attachmentsActions'; import { useAppDispatch } from 'proton-mail/logic/store'; const enum DOWNLOAD_TYPE { PREVIEW = 'PREVIEW', DOWNLOAD = 'DOWNLOAD', } /** * This hook has some similarities with useDownload and usePreview hooks, but download logic using attachment metadata is quite different. * For now, it's difficult to merge them, but the old download part needs a rework. * When this rework will be done, we might be able to refactor these hooks to merge them. */ export const useAttachmentThumbnailDownload = () => { const api = useApi(); const getAttachment = useGetAttachment(); const getMessageKeys = useGetMessageKeys(); const dispatch = useAppDispatch(); const [confirmDownloadModal, handleShowModal] = useModalTwo(ConfirmDownloadAttachments); const getVerificationPreferences = useGetVerificationPreferences(); const contactsMap = useContactsMap(); const downloadAttachment = async (type: DOWNLOAD_TYPE, attachmentsMetadata: AttachmentsMetadata) => { let download: Download; let attachment: WorkerDecryptionResult<Uint8Array>; const { ID } = attachmentsMetadata; const attachmentInState = getAttachment(ID); try { if (attachmentInState) { download = { // Add MIMEType and Name so that we can build the file when user wants to download the file attachment: { ...attachmentInState, MIMEType: attachmentsMetadata.MIMEType, Name: attachmentsMetadata.Name, }, data: attachmentInState.data, // If attachment is in state, we already verified it during download process // So if we open the attachment using Redux state, we should see the same verifications (e.g. modals are displayed in case of SIGNED_AND_INVALID) verified: attachmentInState.verified, }; attachment = attachmentInState; } else { /* API Calls to get * 1 - Attachment encrypted data * 2 - Attachment metadata (signature, keyPackets etc...) */ const [apiEncryptedBinary, apiAttachmentFullMetadata] = await Promise.all([ api(getAttachmentRequest(ID)), api<{ Attachment: AttachmentFullMetadata }>(getAttachmentsMetadata(ID)), ]); const { AddressID, KeyPackets, Signature, /*EncSignature,*/ Sender } = apiAttachmentFullMetadata.Attachment; if (!Sender) { throw new Error(`Cannot decrypt attachment, sender is missing`); } const messageKeys = await getMessageKeys({ AddressID }); // TODO: this is a temporary hack. // The BE needs to add the message flags to the AttachmentMetadata route, so that we // know which attachments were autoforwarded. // In the meantime, we temporarily allow using forwading keys on all attachments. const messageFlags = JSBI.toNumber(MESSAGE_FLAGS.FLAG_AUTO_FORWARDEE); const sessionKey = await getSessionKey({ KeyPackets }, messageKeys.privateKeys, messageFlags); // Verify API keys and get pinned keys if there are some const verificationPreferences = await getVerificationPreferences({ email: Sender.Address, lifetime: 0, contactEmailsMap: contactsMap, }); const decryptedAttachment = await decryptAndVerify( apiEncryptedBinary, sessionKey, Signature, verificationPreferences.verifyingKeys // EncSignature TODO uncomment when fixed ); const verified = getVerificationStatusFromKeys( decryptedAttachment, verificationPreferences.verifyingKeys ); // Set verified state in the attachment to keep track of it in Redux attachment = { ...decryptedAttachment, verified, } as WorkerDecryptionResult<Uint8Array>; download = { // Add MIMEType and Name so that we can build the file when user wants to download the file attachment: { ...attachment, MIMEType: attachmentsMetadata.MIMEType, Name: attachmentsMetadata.Name, Size: attachmentsMetadata.Size, }, data: decryptedAttachment.data, verified, }; } dispatch(updateAttachment({ ID, attachment })); } catch (error: any) { if (type === DOWNLOAD_TYPE.PREVIEW) { // When previewing, if an error occurs while decrypting, remove loading state and show a "not supported preview" text download = { attachment: { // Overriding mime type to prevent opening any visualizer with empty data, especially needed for pdfs MIMEType: '', Name: attachmentsMetadata.Name, Size: attachmentsMetadata.Size, }, data: new Uint8Array([]), verified: VERIFICATION_STATUS.NOT_VERIFIED, }; } else { // When downloading, if an error occurs while decrypting, download the encrypted version download = { attachment: { Name: `${attachmentsMetadata.Name}.pgp`, Size: attachmentsMetadata.Size, MIMEType: 'application/pgp-encrypted', ID: attachmentsMetadata.ID, }, data: error.binary, verified: VERIFICATION_STATUS.NOT_VERIFIED, }; } } return download; }; const handleThumbnailPreview = async (attachmentsMetadata: AttachmentsMetadata) => { const download = await downloadAttachment(DOWNLOAD_TYPE.PREVIEW, attachmentsMetadata); if (download.isError || download.verified === VERIFICATION_STATUS.SIGNED_AND_INVALID) { const handleError = async () => { await handleShowModal({ downloads: [download] }); await generateDownload(download); }; void handleError(); } return download; }; const handleThumbnailDownload = async (attachmentsMetadata: AttachmentsMetadata) => { const download = await downloadAttachment(DOWNLOAD_TYPE.DOWNLOAD, attachmentsMetadata); if (download.isError || download.verified === VERIFICATION_STATUS.SIGNED_AND_INVALID) { await handleShowModal({ downloads: [download] }); } await generateDownload(download); return download.verified; }; return { handleThumbnailPreview, handleThumbnailDownload, confirmDownloadModal }; };
3,980
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/attachments/useDownload.tsx
import { useCallback } from 'react'; import { FeatureCode, useApi, useFeature } from '@proton/components/index'; import { useModalTwo } from '@proton/components/components/modalTwo/useModalTwo'; import { WorkerDecryptionResult } from '@proton/crypto'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { getAttachments } from '@proton/shared/lib/mail/messages'; import ConfirmDownloadAttachments from '../../components/attachment/modals/ConfirmDownloadAttachments'; import { Download, formatDownload, formatDownloadAll, generateDownload, generateDownloadAll, } from '../../helpers/attachment/attachmentDownloader'; import { getAttachmentCounts } from '../../helpers/message/messages'; import { updateAttachment } from '../../logic/attachments/attachmentsActions'; import { MessageKeys, MessageStateWithData, OutsideKey } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; import { useGetMessageKeys } from '../message/useGetMessageKeys'; import { useGetMessage } from '../message/useMessage'; import { useGetAttachment } from './useAttachment'; /** * Returns the keys from the sender of the message version in cache * Extra security here because when used in the composer context, * sender address can be desynchronized from the attachment key packets */ const useSyncedMessageKeys = () => { const getMessage = useGetMessage(); const getMessageKeys = useGetMessageKeys(); return (localID: string) => { const messageFromCache = getMessage(localID) as MessageStateWithData; return getMessageKeys(messageFromCache.data); }; }; export const useDownload = () => { const api = useApi(); const getAttachment = useGetAttachment(); const dispatch = useAppDispatch(); const getMessageKeys = useSyncedMessageKeys(); const [confirmDownloadModal, handleShowModal] = useModalTwo(ConfirmDownloadAttachments); const onUpdateAttachment = (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => { dispatch(updateAttachment({ ID, attachment })); }; const handleDownload = useCallback( async (message: MessageStateWithData, attachment: Attachment, outsideKey?: MessageKeys) => { let download; if (!outsideKey) { const messageKeys = await getMessageKeys(message.localID); download = await formatDownload( attachment, message.verification, messageKeys, onUpdateAttachment, api, getAttachment, message.data.Flags ); } else { download = await formatDownload( attachment, message.verification, outsideKey, onUpdateAttachment, api, getAttachment, message.data.Flags ); } if (download.isError || download.verified === VERIFICATION_STATUS.SIGNED_AND_INVALID) { await handleShowModal({ downloads: [download] }); } await generateDownload(download); return download.verified; }, [api] ); return { handleDownload, confirmDownloadModal }; }; export const useDownloadAll = () => { const api = useApi(); const getAttachment = useGetAttachment(); const dispatch = useAppDispatch(); const getMessageKeys = useSyncedMessageKeys(); const isNumAttachmentsWithoutEmbedded = useFeature(FeatureCode.NumAttachmentsWithoutEmbedded).feature?.Value; const [confirmDownloadModal, handleShowModal] = useModalTwo(ConfirmDownloadAttachments); const onUpdateAttachment = (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => { dispatch(updateAttachment({ ID, attachment })); }; const handleDownloadAll = useCallback( async (message: MessageStateWithData, outsideKey?: MessageKeys) => { const attachments = getAttachments(message.data); const { pureAttachments } = getAttachmentCounts(attachments, message.messageImages); let list; if (!outsideKey) { const messageKeys = await getMessageKeys(message.localID); list = await formatDownloadAll( isNumAttachmentsWithoutEmbedded ? pureAttachments : attachments, message.verification, messageKeys, onUpdateAttachment, api, getAttachment, message.data.Flags ); } else { list = await formatDownloadAll( isNumAttachmentsWithoutEmbedded ? pureAttachments : attachments, message.verification, outsideKey, onUpdateAttachment, api, undefined, message.data.Flags ); } const isError = list.some(({ isError }) => isError); const senderVerificationFailed = list.some( ({ verified }) => verified === VERIFICATION_STATUS.SIGNED_AND_INVALID ); if (isError || senderVerificationFailed) { await handleShowModal({ downloads: list }); } await generateDownloadAll(message.data, list); }, [api] ); return { handleDownloadAll, confirmDownloadModal }; }; export const usePreview = () => { const api = useApi(); const getAttachment = useGetAttachment(); const dispatch = useAppDispatch(); const getMessageKeys = useSyncedMessageKeys(); const [confirmDownloadModal, handleShowModal] = useModalTwo(ConfirmDownloadAttachments); const onUpdateAttachment = (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => { dispatch(updateAttachment({ ID, attachment })); }; const handlePreview = useCallback( async (message: MessageStateWithData, attachment: Attachment, outsideKey?: OutsideKey) => { let download: Download; if (!outsideKey) { const messageKeys = await getMessageKeys(message.localID); download = await formatDownload( attachment, message.verification, messageKeys, onUpdateAttachment, api, getAttachment, message.data.Flags ); } else { download = await formatDownload( attachment, message.verification, outsideKey, onUpdateAttachment, api, undefined, message.data.Flags ); } if (download.isError || download.verified === VERIFICATION_STATUS.SIGNED_AND_INVALID) { const handleError = async () => { await handleShowModal({ downloads: [download] }); await generateDownload(download); }; void handleError(); } return download; }, [api] ); return { handlePreview, confirmDownloadModal }; };
3,981
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useAttachments.ts
import { MutableRefObject, useState } from 'react'; import { useApi, useAuthentication, useHandler, useNotifications } from '@proton/components'; import { removeAttachment } from '@proton/shared/lib/api/attachments'; import { readFileAsBuffer } from '@proton/shared/lib/helpers/file'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { ATTACHMENT_DISPOSITION, ATTACHMENT_MAX_COUNT } from '@proton/shared/lib/mail/constants'; import { getAttachments, isPlainText } from '@proton/shared/lib/mail/messages'; import { MessageChange } from '../../components/composer/Composer'; import { ExternalEditorActions } from '../../components/composer/editor/EditorWrapper'; import { MESSAGE_ALREADY_SENT_INTERNAL_ERROR } from '../../constants'; import { UploadResult, checkSizeAndLength, upload } from '../../helpers/attachment/attachmentUploader'; import { createEmbeddedImageFromUpload, isEmbeddable, matchSameCidOrLoc, readContentIDandLocation, } from '../../helpers/message/messageEmbeddeds'; import { getEmbeddedImages, updateImages } from '../../helpers/message/messageImages'; import { Upload } from '../../helpers/upload'; import { addAttachment } from '../../logic/attachments/attachmentsActions'; import { MessageState, MessageStateWithData } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; import { useGetMessageKeys } from '../message/useGetMessageKeys'; import { useGetMessage } from '../message/useMessage'; import { useLongLivingState } from '../useLongLivingState'; import { usePromise } from '../usePromise'; export interface PendingUpload { file: File; upload: Upload<UploadResult>; } interface UseAttachmentsParameters { message: MessageState; onChange: MessageChange; onSaveNow: () => Promise<void>; editorActionsRef?: MutableRefObject<ExternalEditorActions | undefined>; onMessageAlreadySent: () => void; } export const useAttachments = ({ message, onChange, onSaveNow, editorActionsRef, onMessageAlreadySent, }: UseAttachmentsParameters) => { const api = useApi(); const { createNotification } = useNotifications(); const auth = useAuthentication(); const getMessage = useGetMessage(); const getMessageKeys = useGetMessageKeys(); const dispatch = useAppDispatch(); // Pending files to upload const [pendingFiles, setPendingFiles] = useState<File[]>(); // Pending uploads // Long living because we have to track upload progress after closing const [pendingUploads, setPendingUploads, getPendingUpload] = useLongLivingState<PendingUpload[]>([]); const { promise: promiseUpload, resolver: resolveUpload, rejecter: rejectUpload, renew: newUpload, isPending: uploadInProgress, } = usePromise<void>(); const { localID } = message; const updatePendingUpload = useHandler((pendingUploads: PendingUpload[], error?: any) => { const previousValue = getPendingUpload(); setPendingUploads(pendingUploads); if (error) { rejectUpload(error); } else if (!pendingUploads.length && previousValue.length) { resolveUpload(); } }); const addPendingUploads = (pendingUploads: PendingUpload[]) => { updatePendingUpload([...getPendingUpload(), ...pendingUploads]); }; const removePendingUpload = (pendingUpload: PendingUpload, error?: any) => { updatePendingUpload( getPendingUpload().filter((aPendingUpload) => aPendingUpload !== pendingUpload), error ); }; const ensureMessageIsCreated = async () => { await onSaveNow(); // Message from cache has data because we just saved it if not return getMessage(localID) as MessageStateWithData; }; /** * Wait for upload to finish, modify the message, add to embedded images if needed */ const handleAddAttachmentEnd = useHandler(async (action: ATTACHMENT_DISPOSITION, pendingUpload: PendingUpload) => { try { const upload = await pendingUpload.upload.resultPromise; const data = new Uint8Array(await readFileAsBuffer(pendingUpload.file)); const filename = pendingUpload.file.name; dispatch( addAttachment({ ID: upload.attachment.ID || '', attachment: { data, verified: 1, filename, signatures: [] }, }) ); // 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), upload.attachment]; const embeddedImages = getEmbeddedImages(message); if (action === ATTACHMENT_DISPOSITION.INLINE) { embeddedImages.push(createEmbeddedImageFromUpload(upload.attachment)); } const messageImages = updateImages(message.messageImages, undefined, undefined, embeddedImages); return { data: { Attachments }, messageImages }; }); if (action === ATTACHMENT_DISPOSITION.INLINE) { editorActionsRef?.current?.insertEmbedded(upload.attachment, upload.packets.Preview); } removePendingUpload(pendingUpload); } catch (error: any) { if (error?.message === MESSAGE_ALREADY_SENT_INTERNAL_ERROR) { onMessageAlreadySent(); } removePendingUpload(pendingUpload, error); } }); /** * Start uploading a file, the choice between attachment or inline is done. */ const handleAddAttachmentsUpload = useHandler( async (action: ATTACHMENT_DISPOSITION, files: File[] = pendingFiles || []) => { setPendingFiles(undefined); // Trigger upload state before ensureMessageIsCreated // In case of the user close or send even before if (getPendingUpload().length === 0) { newUpload(); } const messageFromState = await ensureMessageIsCreated(); const messageKeys = await getMessageKeys(messageFromState.data); // Message already sent if (messageFromState.draftFlags?.isSentDraft) { onMessageAlreadySent(); return; } const uploads = upload(files, messageFromState, messageKeys, action, auth.UID); const pendingUploads = files.map((file, i) => ({ file, upload: uploads[i] })); addPendingUploads(pendingUploads); pendingUploads.forEach((pendingUpload) => handleAddAttachmentEnd(action, pendingUpload)); } ); /** * Trigger an directly an embedded upload. */ const handleAddEmbeddedImages = async (files: File[]) => { const pendingUploadFiles = pendingUploads.map((upload) => upload.file); const hasReachedLimits = checkSizeAndLength({ createNotification, message, files, pendingUploadFiles, attachmentsCountLimit: ATTACHMENT_MAX_COUNT, }); if (hasReachedLimits) { return; } void handleAddAttachmentsUpload(ATTACHMENT_DISPOSITION.INLINE, files); }; /** * Entry point for upload, will check and ask for attachment action if possible */ const handleAddAttachmentsStart = useHandler(async (files: File[]) => { const embeddable = files.every((file) => isEmbeddable(file.type)); const plainText = isPlainText(message.data); const pendingUploadFiles = pendingUploads.map((upload) => upload.file); const hasReachedLimits = checkSizeAndLength({ createNotification, message, files, pendingUploadFiles, attachmentsCountLimit: ATTACHMENT_MAX_COUNT, }); if (hasReachedLimits) { return; } if (!plainText && embeddable) { setPendingFiles(files); } else { void handleAddAttachmentsUpload(ATTACHMENT_DISPOSITION.ATTACHMENT, files); } }); const handleCancelAddAttachment = () => setPendingFiles(undefined); /** * Remove an existing attachment, deal with potential embedded image */ const handleRemoveAttachment = useHandler(async (attachment: Attachment) => { if (attachment.ID && message.data?.ID) { await api(removeAttachment(attachment.ID, message.data.ID)); } 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 }; }); }); /** * Cancel pending upload */ const handleRemoveUpload = async (pendingUpload: PendingUpload) => { pendingUpload.upload.abort(); void removePendingUpload(pendingUpload); }; return { pendingFiles, pendingUploads, promiseUpload, uploadInProgress, handleAddAttachmentsStart, handleAddEmbeddedImages, handleAddAttachmentsUpload, handleCancelAddAttachment, handleRemoveAttachment, handleRemoveUpload, }; };
3,982
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useAutoSave.tsx
import { useRef, useState } from 'react'; import { useHandler } from '@proton/components'; import { Cancellable } from '@proton/components/hooks/useHandler'; import { isDecryptionError, isNetworkError } from '../../helpers/errors'; import { MessageState, MessageStateWithData } from '../../logic/messages/messagesTypes'; import { useDeleteDraft, useSaveDraft } from '../message/useSaveDraft'; import { usePromise } from '../usePromise'; interface AutoSaveArgs { onMessageAlreadySent?: () => void; } export const useAutoSave = ({ onMessageAlreadySent }: AutoSaveArgs) => { const [hasNetworkError, setHasNetworkError] = useState(false); const pendingAutoSave = usePromise<void>(); const pendingSave = usePromise<void>(); const pauseDebouncer = useRef<boolean>(false); const lastCall = useRef<MessageState>(); const saveDraft = useSaveDraft({ onMessageAlreadySent }); const deleteDraftSource = useDeleteDraft(); let pause: () => void; let restart: () => void; const actualSave = useHandler(async (message: MessageState) => { pause(); try { await pendingSave.promise; } catch { // Nothing } try { lastCall.current = undefined; pendingSave.renew(); await saveDraft(message as MessageStateWithData); setHasNetworkError(false); } catch (error: any) { if (isNetworkError(error) || isDecryptionError(error)) { console.error(error); setHasNetworkError(true); } else { throw error; } } finally { pendingSave.resolver(); restart(); } }); const debouncedHandler = useHandler( (message: MessageState) => { pendingAutoSave.resolver(); return actualSave(message); }, { debounce: 2000 } ); pause = useHandler(() => { pauseDebouncer.current = true; }); restart = useHandler(() => { pauseDebouncer.current = false; if (lastCall.current !== undefined) { void debouncedHandler(lastCall.current as MessageState); } }); const pausableHandler = useHandler((message: MessageState) => { if (!pendingAutoSave.isPending) { pendingAutoSave.renew(); } lastCall.current = message; if (!pauseDebouncer.current) { return debouncedHandler(message); } }); const cancel = useHandler(() => { debouncedHandler.cancel?.(); pendingAutoSave.resolver(); pauseDebouncer.current = false; }); pausableHandler.cancel = cancel; const saveNow = (message: MessageState) => { cancel(); return actualSave(message); }; const deleteDraft = useHandler(async (message: MessageState) => { cancel(); const hasMessageID = message.data?.ID; try { await pendingSave.promise; } catch { // Nothing } try { pendingSave.renew(); await deleteDraftSource(message); } finally { pendingSave.resolver(); // Restart function can trigger an autoSave // If message has not been saved yet (no messageID), // we don't want to trigger an autoSave if (hasMessageID) { restart(); } } }); return { autoSave: pausableHandler as ((message: MessageState) => Promise<void>) & Cancellable, saveNow, deleteDraft, pendingSave, pendingAutoSave, pause, restart, hasNetworkError, }; };
3,983
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useCloseHandler.tsx
import { useRef, useState } from 'react'; import { c } from 'ttag'; import { useHandler, useNotifications } from '@proton/components'; import { Cancellable } from '@proton/components/hooks/useHandler'; import useIsMounted from '@proton/hooks/useIsMounted'; import { wait } from '@proton/shared/lib/helpers/promise'; import SavingDraftNotification, { SavingDraftNotificationAction, } from '../../components/notifications/SavingDraftNotification'; import { useOnCompose } from '../../containers/ComposeProvider'; import { MessageState } from '../../logic/messages/messagesTypes'; import { PromiseHandlers } from '../usePromise'; import { ComposeTypes } from './useCompose'; export interface UseCloseHandlerParameters { modelMessage: MessageState; syncedMessage: MessageState; lock: boolean; ensureMessageContent: () => void; uploadInProgress?: boolean; promiseUpload?: Promise<void>; pendingAutoSave: PromiseHandlers<void>; autoSave: ((message: MessageState) => Promise<void>) & Cancellable; saveNow: (message: MessageState) => Promise<void>; onClose: () => void; onDiscard: () => void; onMessageAlreadySent: () => void; hasNetworkError: boolean; } export const useCloseHandler = ({ modelMessage, syncedMessage, lock, ensureMessageContent, saveNow, uploadInProgress, pendingAutoSave, promiseUpload, onClose, onDiscard, onMessageAlreadySent, hasNetworkError, }: UseCloseHandlerParameters) => { const { createNotification, hideNotification } = useNotifications(); const isMounted = useIsMounted(); const onCompose = useOnCompose(); // Indicates that the composer is saving a draft const [saving, setSavingUnsafe] = useState(false); // Manual save mostly used when closing, save state is not relevant then const setSaving = (value: boolean) => { if (isMounted()) { setSavingUnsafe(value); } }; const notficationRef = useRef<SavingDraftNotificationAction>(); const handleManualSaveAfterUploads = useHandler(async (notificationID: number) => { try { await saveNow(modelMessage); notficationRef.current?.saved(); await wait(3000); } finally { hideNotification(notificationID); setSaving(false); } }); const handleManualSave = useHandler(async () => { // Message already sent if (syncedMessage.draftFlags?.isSentDraft) { onMessageAlreadySent(); return; } const notificationID = createNotification({ text: ( <SavingDraftNotification ref={notficationRef} onDiscard={() => { if (notificationID) { hideNotification(notificationID); } void onDiscard(); }} /> ), expiration: -1, showCloseButton: false, }); setSaving(true); ensureMessageContent(); try { await promiseUpload; } catch (error: any) { hideNotification(notificationID); setSaving(false); throw error; } // Split handlers to have the updated version of the message await handleManualSaveAfterUploads(notificationID); }); const handleClose = useHandler(async () => { if (!lock) { // Has to be done before the onClose call // It needs to refer to composer components which will be disposed otherwise ensureMessageContent(); } // Closing the composer instantly, all the save process will be in background onClose(); if (syncedMessage.draftFlags?.isSentDraft) { createNotification({ text: c('Error').t`This message has already been sent`, type: 'error', }); return; } if (lock) { // If the composer was locked, either it could have // - failed at loading // - still being created // - still being loaded // In all of those situation we don't need to save something, we can safely skip all the rest return; } // Message requires to be saved in background if (pendingAutoSave.isPending || uploadInProgress || hasNetworkError) { try { await handleManualSave(); } catch { createNotification({ text: c('Error').t`Draft could not be saved. Try again.`, type: 'error', }); onCompose({ type: ComposeTypes.existingDraft, existingDraft: modelMessage, fromUndo: true }); } } }); return { handleClose, handleManualSave, saving }; };
3,984
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useCompose.tsx
import { MutableRefObject, useCallback } from 'react'; import { c, msgid } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { ErrorButton, Prompt, useAddresses, useApi, useEventManager, useGetUser, useHandler, useModalState, useNotifications, useSettingsLink, } from '@proton/components'; import { useModalTwo } from '@proton/components/components/modalTwo/useModalTwo'; import { forceSend } from '@proton/shared/lib/api/messages'; import { APP_UPSELL_REF_PATH, MAIL_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { pick } from '@proton/shared/lib/helpers/object'; import { getUpsellRef } from '@proton/shared/lib/helpers/upsell'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { isOutbox, isScheduledSend } from '@proton/shared/lib/mail/messages'; import { composerActions } from 'proton-mail/logic/composers/composersSlice'; import SendingOriginalMessageModal from '../../components/composer/modals/SendingOriginalMessageModal'; import { MESSAGE_ACTIONS } from '../../constants'; import { isDirtyAddress } from '../../helpers/addresses'; import { openDraft } from '../../logic/messages/draft/messagesDraftActions'; import { MessageState, PartialMessageState } from '../../logic/messages/messagesTypes'; import { store, useAppDispatch } from '../../logic/store'; import { useGetLocalID, useGetMessage } from '../message/useMessage'; import { useDraft } from '../useDraft'; import { EditorTypes } from './useComposerContent'; export enum ComposeTypes { existingDraft, newMessage, fromMessage, } export interface ComposeExisting { type: ComposeTypes.existingDraft; existingDraft: MessageState; fromUndo: boolean; fromQuickReply?: boolean; } export interface ComposeNew { type: ComposeTypes.newMessage; action: MESSAGE_ACTIONS; referenceMessage?: PartialMessageState; } export interface ComposeModelMessage { type: ComposeTypes.fromMessage; modelMessage: MessageState; } export type ComposeArgs = (ComposeExisting | ComposeNew | ComposeModelMessage) & { returnFocusTo?: HTMLElement; }; export const getComposeArgs = (composeArgs: ComposeArgs) => ({ ...composeArgs, returnFocusTo: composeArgs.returnFocusTo || (document.activeElement as HTMLElement), }); export interface OnCompose { (args: ComposeArgs): Promise<void>; } interface UseComposeProps { openedComposerIDs: string[]; focusComposer: (messageID: string) => void; maxActiveComposer: number; returnFocusToElementRef: MutableRefObject<HTMLElement | null>; } export const useCompose = ({ openedComposerIDs, focusComposer, maxActiveComposer, returnFocusToElementRef, }: UseComposeProps) => { // Avoid useUser for performance issues const getUser = useGetUser(); const [addresses = []] = useAddresses(); const { createNotification } = useNotifications(); const dispatch = useAppDispatch(); const { createDraft, sendingFromDefaultAddressModal } = useDraft(); const goToSettings = useSettingsLink(); const api = useApi(); const { call } = useEventManager(); const getLocalID = useGetLocalID(); const getMessage = useGetMessage(); const openComposer = useCallback( ({ messageID, type, returnFocusTo, }: { messageID: string; type: ComposeTypes; returnFocusTo?: HTMLElement; }) => { const message = getMessage(messageID); if (type === ComposeTypes.existingDraft) { dispatch( composerActions.addComposer({ type: EditorTypes.composer, messageID, senderEmailAddress: undefined, status: 'loading', }) ); } else { if (!message?.data?.Sender.Address) { throw new Error('No address'); } dispatch( composerActions.addComposer({ type: EditorTypes.composer, messageID, senderEmailAddress: message.data.Sender.Address, recipients: pick(message.data, ['ToList', 'CCList', 'BCCList']), status: 'idle', }) ); } if (returnFocusTo) { returnFocusToElementRef.current = returnFocusTo; } }, [] ); const [storageCapacityModalProps, setStorageCapacityModalOpen] = useModalState(); const [sendingOriginalMessageModal, handleSendingOriginalMessage] = useModalTwo(SendingOriginalMessageModal); const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.MODAL, feature: MAIL_UPSELL_PATHS.STORAGE_FULL, }); const storageCapacityModal = ( <Prompt title={c('Title').t`Storage capacity warning`} buttons={[ <ErrorButton onClick={() => goToSettings(`/upgrade?ref=${upsellRef}`)}>{c('Action') .t`Upgrade`}</ErrorButton>, <Button onClick={storageCapacityModalProps.onClose}>{c('Action').t`Close`}</Button>, ]} {...storageCapacityModalProps} > {c('Info') .t`You have reached 100% of your storage capacity. Consider freeing up some space or upgrading your account with additional storage space to compose new messages.`} <br /> <Href href={getKnowledgeBaseUrl('/increase-storage-space')}>{c('Link').t`Learn more`}</Href> </Prompt> ); const handleCompose = useHandler(async (composeArgs: ComposeArgs) => { const user = await getUser(); const activeAddresses = addresses.filter((address) => !isDirtyAddress(address)); if (activeAddresses.length === 0) { createNotification({ type: 'error', text: ( <> {c('Error').t`No address with keys available to compose a message`} <br /> {c('Error').t`Contact your organization’s administrator to resolve this`} </> ), }); return; } const spacePercentage = (user.UsedSpace * 100) / user.MaxSpace; if (!Number.isNaN(spacePercentage) && spacePercentage >= 100) { setStorageCapacityModalOpen(true); return; } if (openedComposerIDs.length >= maxActiveComposer) { createNotification({ type: 'error', // translator: maxActiveComposer should never be 1, is fixed to 3 today but can potentially vary from 2 to 5(?) in the future. text: c('Error').ngettext( msgid`You cannot open more than ${maxActiveComposer} composer window at a time`, `You cannot open more than ${maxActiveComposer} composer windows at a time`, maxActiveComposer ), }); return; } const compose = getComposeArgs(composeArgs); if (compose.type === ComposeTypes.existingDraft) { const { existingDraft, fromUndo, returnFocusTo } = compose; const localID = getLocalID(existingDraft.localID); let composer = Object.values(store.getState().composers.composers).find( ({ messageID }) => messageID === localID ); if (composer) { focusComposer(composer.ID); return; } const existingMessage = getMessage(localID); // If message is in sending state we stop here if (existingMessage?.draftFlags?.sending && !fromUndo) { return; } dispatch(openDraft({ ID: localID, fromUndo })); openComposer({ messageID: localID, returnFocusTo, type: compose.type }); composer = Object.values(store.getState().composers.composers).find( ({ messageID }) => messageID === localID ); if (composer) { focusComposer(composer.ID); } return; } if (compose.type === ComposeTypes.newMessage) { const { action, referenceMessage, returnFocusTo } = compose; const message = referenceMessage?.data; if (isOutbox(message) && message?.ID) { if (isScheduledSend(message)) { createNotification({ text: c('Error').t`Message needs to be sent first`, type: 'error' }); return; } await handleSendingOriginalMessage({}); await api(forceSend(message?.ID)); await call(); } const newMessageID = await createDraft(action, referenceMessage); openComposer({ messageID: newMessageID, returnFocusTo, type: compose.type }); const composer = Object.values(store.getState().composers.composers).find( ({ messageID }) => messageID === newMessageID ); if (composer) { focusComposer(composer?.ID); } } if (compose.type === ComposeTypes.fromMessage) { const { modelMessage, returnFocusTo } = compose; openComposer({ messageID: modelMessage.localID, returnFocusTo, type: compose.type }); const composer = Object.values(store.getState().composers.composers).find( ({ messageID }) => messageID === modelMessage.localID ); if (composer) { focusComposer(composer?.ID); } } }); return { handleCompose, storageCapacityModal, sendingFromDefaultAddressModal, sendingOriginalMessageModal }; };
3,985
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useComposerContent.tsx
import { Dispatch, MutableRefObject, RefObject, SetStateAction, useEffect, useMemo, useRef, useState } from 'react'; import { c } from 'ttag'; import { EditorActions, EditorMetadata } from '@proton/components/components'; import { useAddresses, useHandler, useNotifications, useUserSettings } from '@proton/components/hooks'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { DIRECTION, SHORTCUTS } from '@proton/shared/lib/mail/mailSettings'; import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants'; import { getRecipients, isPlainText as testIsPlainText } from '@proton/shared/lib/mail/messages'; import noop from '@proton/utils/noop'; import { selectComposer } from 'proton-mail/logic/composers/composerSelectors'; import { composerActions } from 'proton-mail/logic/composers/composersSlice'; import { messageByID } from 'proton-mail/logic/messages/messagesSelectors'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { MessageChange } from '../../components/composer/Composer'; import { ExternalEditorActions } from '../../components/composer/editor/EditorWrapper'; import { MESSAGE_ACTIONS } from '../../constants'; import { useOnCompose } from '../../containers/ComposeProvider'; import { updateKeyPackets } from '../../helpers/attachment/attachment'; import { getDate } from '../../helpers/elements'; import { getContent, getContentWithBlockquotes, setContent } from '../../helpers/message/messageContent'; import { isNewDraft } from '../../helpers/message/messageDraft'; import { replaceEmbeddedAttachments } from '../../helpers/message/messageEmbeddeds'; import { mergeMessages } from '../../helpers/message/messages'; import { ComposerID } from '../../logic/composers/composerTypes'; import { deleteDraft as deleteDraftAction, removeInitialAttachments, removeQuickReplyFlag, updateDraftContent, updateIsSavingFlag, } from '../../logic/messages/draft/messagesDraftActions'; import { MessageState } from '../../logic/messages/messagesTypes'; import { useAppDispatch, useAppStore } from '../../logic/store'; import { useInitializeMessage } from '../message/useInitializeMessage'; import { useGetMessage, useMessage } from '../message/useMessage'; import { useLongLivingState } from '../useLongLivingState'; import { useMessageSendInfo, useReloadSendInfo } from '../useSendInfo'; import { useAttachments } from './useAttachments'; import { useAutoSave } from './useAutoSave'; import { useCloseHandler } from './useCloseHandler'; import { ComposeTypes } from './useCompose'; import { EditorHotkeysHandlers, useComposerHotkeys } from './useComposerHotkeys'; import { useComposerInnerModals } from './useComposerInnerModals'; import { useDraftSenderVerification } from './useDraftSenderVerification'; import { useHandleMessageAlreadySent } from './useHandleMessageAlreadySent'; import useReduxRefac from './useReduxRefac'; import { useSendHandler } from './useSendHandler'; export enum EditorTypes { composer, quickReply, } export interface EditorComposer { type: EditorTypes.composer; editorRef: MutableRefObject<ExternalEditorActions | undefined>; addressesFocusRef?: MutableRefObject<() => void>; toggleMinimized?: () => void; toggleMaximized?: () => void; composerID: ComposerID; minimizeButtonRef: RefObject<HTMLButtonElement>; } export interface EditorQuickReply { type: EditorTypes.quickReply; messageID: string; editorRef: MutableRefObject<EditorActions | undefined>; referenceMessage?: MessageState; replyUpdated?: boolean; setReplyUpdated?: Dispatch<SetStateAction<boolean>>; setDeleteDraftModalOpen?: (newValue: boolean) => void; onNoAttachments?: (keyword: string) => Promise<unknown>; } export type EditorArgs = (EditorComposer | EditorQuickReply) & { onClose: () => void; composerFrameRef: RefObject<HTMLDivElement>; isFocused?: boolean; editorReady: boolean; }; export const useComposerContent = (args: EditorArgs) => { const [addresses] = useAddresses(); const mailSettings = useMailModel('MailSettings'); const [userSettings] = useUserSettings(); const { createNotification } = useNotifications(); const getMessage = useGetMessage(); const onCompose = useOnCompose(); const dispatch = useAppDispatch(); const store = useAppStore(); const skipNextInputRef = useRef(false); const { onClose, composerFrameRef, type: editorType, isFocused, editorReady } = args; const messageID = useMemo(() => { switch (editorType) { case EditorTypes.composer: const composer = selectComposer(store.getState(), args.composerID); return composer.messageID; case EditorTypes.quickReply: return args.messageID; } }, []); const isComposer = editorType === EditorTypes.composer; const isQuickReply = editorType === EditorTypes.quickReply; // Indicates that the composer is in its initial opening // Needed to be able to force focus only at first time const [opening, setOpening] = useState(true); // Use long living state so that we can use it from the send handler const [isSending, setIsSending] = useLongLivingState<boolean>(false); // Model value of the edited message in the composer const [modelMessage, setModelMessage, getModelMessage] = useLongLivingState<MessageState>({ localID: messageID, }); // Computed composer status const hasRecipients = getRecipients(modelMessage.data).length > 0; // Map of send preferences and send icons for each recipient const messageSendInfo = useMessageSendInfo(modelMessage); const reloadSendInfo = useReloadSendInfo(); const { message: syncedMessage } = useMessage(messageID); const date = getDate(syncedMessage.data, ''); const timestamp = date ? date.getTime() : 0; // Handles message already sent error const onMessageAlreadySent = useHandleMessageAlreadySent({ modelMessage, onClose, }); // All message actions const initialize = useInitializeMessage(); const { autoSave, saveNow, deleteDraft, pendingSave, pendingAutoSave, pause: pauseAutoSave, restart: restartAutoSave, hasNetworkError, } = useAutoSave({ onMessageAlreadySent }); useEffect(() => { if (isQuickReply && (pendingSave.isPending || pendingAutoSave.isPending)) { dispatch(updateIsSavingFlag({ ID: messageID, isSaving: true })); } else { dispatch(updateIsSavingFlag({ ID: messageID, isSaving: false })); } }, [pendingSave.isPending, pendingAutoSave.isPending]); const [blockquoteExpanded, setBlockquoteExpanded] = useState(true); const isPlainText = testIsPlainText(modelMessage.data); const rightToLeft = modelMessage.data?.RightToLeft ? DIRECTION.RIGHT_TO_LEFT : DIRECTION.LEFT_TO_RIGHT; const metadata: EditorMetadata = useMemo( () => ({ supportPlainText: true, isPlainText, supportRightToLeft: true, rightToLeft, supportImages: true, supportDefaultFontSelector: true, blockquoteExpanded, setBlockquoteExpanded, }), [isPlainText, rightToLeft, blockquoteExpanded, setBlockquoteExpanded] ); // Manage existing draft initialization useEffect(() => { const initDraft = async () => { if ( !pendingSave.isPending && (syncedMessage.data?.ID || (!syncedMessage.data?.ID && !isNewDraft(syncedMessage.localID))) && syncedMessage.messageDocument?.initialized === undefined && modelMessage.messageDocument?.initialized === undefined ) { await initialize(syncedMessage.localID); const initializedMessage = messageByID(store.getState(), { ID: syncedMessage.localID }); if (editorType === EditorTypes.composer) { const composerID = args.composerID; if (initializedMessage?.data && composerID) { dispatch(composerActions.setInitialized({ ID: composerID, message: initializedMessage })); } } } }; void initDraft(); }, [ pendingSave.isPending, syncedMessage.localID, syncedMessage.data?.ID, syncedMessage.messageDocument?.initialized, modelMessage.messageDocument?.initialized, ]); // Manage populating the model from the server useEffect(() => { // Draft creation if (modelMessage.data?.ID !== syncedMessage.data?.ID) { const newModelMessage = { ...syncedMessage, ...modelMessage, data: { ...syncedMessage.data, ...modelMessage.data, // Attachments are updated by the draft creation request Attachments: syncedMessage.data?.Attachments, } as Message, messageImages: replaceEmbeddedAttachments(modelMessage, syncedMessage.data?.Attachments), }; setModelMessage(newModelMessage); } else { // Draft update const { changed, Attachments } = updateKeyPackets(modelMessage, syncedMessage); if (changed) { setModelMessage({ ...modelMessage, data: { ...modelMessage.data, Attachments } as Message, messageImages: replaceEmbeddedAttachments(modelMessage, Attachments), }); } } }, [pendingSave.isPending, syncedMessage.data?.ID]); // Manage initializing the message from an existing draft useEffect(() => { const firstInitialization = !modelMessage.messageDocument?.initialized && syncedMessage.messageDocument?.initialized; if (firstInitialization) { const isOpenFromUndo = syncedMessage.draftFlags?.openDraftFromUndo === true; const password = isOpenFromUndo ? // Keep password on undo {} : // Forget previously set password if kept in the cache { Password: undefined, PasswordHint: undefined }; const documentCloned = syncedMessage.messageDocument?.document?.cloneNode(true) as Element; const newModelMessage = { ...syncedMessage, ...modelMessage, data: { ...syncedMessage.data, ...password, ...modelMessage.data, Attachments: syncedMessage.data?.Attachments, } as Message, messageDocument: { ...syncedMessage.messageDocument, document: documentCloned, initialized: true, }, messageImages: syncedMessage.messageImages, }; // If the message was expanded from a quick reply, we need to save it because it might not be saved yet // and to remove the flag otherwise the element will not be displayed in the conversation view if (isComposer && newModelMessage.draftFlags?.isQuickReply) { dispatch(removeQuickReplyFlag(modelMessage.localID)); void autoSave(newModelMessage); } setModelMessage(newModelMessage); void reloadSendInfo(messageSendInfo, newModelMessage); } }, [ pendingSave.isPending, syncedMessage.messageDocument?.document, syncedMessage.messageDocument?.plainText, syncedMessage.messageDocument?.initialized, ]); const timeoutRef = useRef(0); // Manage focus at opening useEffect(() => { if (!opening && isQuickReply) { const { editorRef } = args; editorRef.current?.focus(); // In plaintext quick reply, the textarea is scrolled to bottom by default if (isPlainText) { editorRef.current?.scroll?.({ top: 0 }); } } else if (isComposer && !opening && isFocused) { const { addressesFocusRef, editorRef } = args; timeoutRef.current = window.setTimeout(() => { if (getRecipients(syncedMessage.data).length === 0) { addressesFocusRef?.current(); } else { editorRef.current?.focus(); } }); } return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, [opening, isFocused]); const handleChange: MessageChange = useHandler((update, shouldReloadSendInfo) => { setModelMessage((modelMessage) => { const messageChanges = update instanceof Function ? update(modelMessage) : update; const newModelMessage = mergeMessages(modelMessage, messageChanges); if (shouldReloadSendInfo) { void reloadSendInfo(messageSendInfo, newModelMessage); } void autoSave(newModelMessage); return newModelMessage; }); }); const handleChangeContent = useHandler( (content: string, refreshEditor: boolean = false, silent: boolean = false) => { if (isQuickReply) { const { referenceMessage, replyUpdated, setReplyUpdated, editorRef } = args; // Rooster (but not plaintext) triggers an onContentChange event when the initial content is inserted if (!isPlainText && skipNextInputRef.current) { skipNextInputRef.current = false; return; } if (!mailSettings || !referenceMessage) { return; } if (!replyUpdated) { setReplyUpdated?.(true); } setModelMessage((modelMessage) => { const newModelMessageContent = getContentWithBlockquotes( content, isPlainText, referenceMessage, mailSettings, userSettings, addresses, modelMessage.draftFlags?.action || MESSAGE_ACTIONS.REPLY ); setContent(modelMessage, newModelMessageContent); const newModelMessage = { ...modelMessage }; dispatch( updateDraftContent({ ID: newModelMessage.localID, content: newModelMessageContent, }) ); if (!silent) { void autoSave(newModelMessage); } else { // Only the first initialisation should be silent, // in that case we don't want to trigger a change and a save skipNextInputRef.current = true; } if (refreshEditor) { editorRef.current?.setContent(content); } return newModelMessage; }); } else if (isComposer) { const { editorRef } = args; setModelMessage((modelMessage) => { setContent(modelMessage, content); const newModelMessage = { ...modelMessage }; dispatch( updateDraftContent({ ID: newModelMessage.localID, content: content, }) ); if (!silent) { void autoSave(newModelMessage); } if (refreshEditor) { editorRef.current?.setContent(newModelMessage); } return newModelMessage; }); } } ); /** * In some rare situations, Squire can miss an input event. * A missed event can lead to not sending the expected content which is serious. * This function perform an ultimate content check before sending especially. */ const ensureMessageContent = () => { let actualContent; let modelContent; if (isQuickReply) { const { referenceMessage, replyUpdated, editorRef } = args; if (!editorRef.current || editorRef.current.isDisposed() || !referenceMessage || !mailSettings) { return; } const actualContentInEditor = editorRef?.current?.getContent(); // The editor does not contain the reply, so we need to add it actualContent = getContentWithBlockquotes( actualContentInEditor, isPlainText, referenceMessage, mailSettings, userSettings, addresses, modelMessage.draftFlags?.action || MESSAGE_ACTIONS.REPLY ); modelContent = getContent(modelMessage); // Do not handle change content if reply has not been updated if (actualContent.trim() !== modelContent.trim() && replyUpdated) { handleChangeContent(actualContent); } } else if (isComposer) { const { editorRef } = args; if (!editorRef.current || editorRef.current.isDisposed()) { return; } actualContent = editorRef.current.getContent(); modelContent = getContent(modelMessage); if (actualContent.trim() !== modelContent.trim()) { handleChangeContent(actualContent); } } }; /** * Ensure the draft is saved before continue */ const handleSaveNow = async () => { if (!modelMessage.data?.ID) { return saveNow(modelMessage); } }; const { pendingFiles, pendingUploads, promiseUpload, uploadInProgress, handleAddAttachmentsStart, handleAddAttachmentsUpload, handleCancelAddAttachment, handleRemoveAttachment, handleRemoveUpload, } = useAttachments({ message: modelMessage, onChange: handleChange, onSaveNow: handleSaveNow, editorActionsRef: isComposer ? args.editorRef : undefined, onMessageAlreadySent, }); // Manage opening useEffect(() => { // New attachments to upload from scratch const attachmentToUpload = !!syncedMessage.draftFlags?.initialAttachments?.length; if (attachmentToUpload) { const uploadInitialAttachments = async () => { const files = syncedMessage.draftFlags?.initialAttachments; dispatch(removeInitialAttachments(messageID)); await saveNow(syncedMessage); await handleAddAttachmentsUpload(ATTACHMENT_DISPOSITION.ATTACHMENT, files); }; void uploadInitialAttachments(); } if (editorReady && syncedMessage.messageDocument?.initialized && !attachmentToUpload) { setOpening(false); } }, [editorReady, syncedMessage.data, syncedMessage.messageDocument?.initialized]); /** * When opening a draft we also want to check that the message Sender is valid * If a message is imported through EasySwitch or the sender address has been deleted in the meantime, * we want to replace the Sender by the account default address */ const { verifyDraftSender, modal: senderVerificationModal } = useDraftSenderVerification({ onChange: handleChange, composerID: isQuickReply ? '' : args.composerID, }); useEffect(() => { const handleVerify = async () => { await verifyDraftSender(modelMessage); }; if (modelMessage.messageDocument?.initialized) { void handleVerify(); } }, [modelMessage.messageDocument?.initialized]); const handleDiscard = async (hasChanges = true) => { if (isQuickReply) { const message = getMessage(modelMessage.localID); if (message) { await deleteDraft(message); } // We can remove the draft from the state if (modelMessage.localID) { void dispatch(deleteDraftAction(modelMessage.localID)); } } else { const message = getMessage(messageID); if (message) { await deleteDraft(message); } } // Do not display the notification if the draft has no changes if (hasChanges) { createNotification({ text: c('Info').t`Draft discarded` }); } }; const handleDelete = async (hasChanges = true) => { autoSave.cancel?.(); try { onClose(); await handleDiscard(hasChanges); } catch { // Nothing } }; const { saving, handleManualSave, handleClose } = useCloseHandler({ syncedMessage, modelMessage, lock: opening, ensureMessageContent, autoSave, saveNow, onClose, onDiscard: handleDiscard, pendingAutoSave, promiseUpload, uploadInProgress, onMessageAlreadySent, hasNetworkError, }); const { innerModal, setInnerModal, attachmentsFoundKeyword, handlePassword, handleExpiration, handleCloseInnerModal, handleDeleteDraft: handleOpenDeleteDraftModal, handleNoRecipients, handleNoSubjects, handleNoAttachments, handleCloseInsertImageModal, handleSendAnyway, handleCancelSend, } = useComposerInnerModals({ pendingFiles, handleCancelAddAttachment, }); const handleSend = useSendHandler({ getModelMessage, setModelMessage, ensureMessageContent, mapSendInfo: messageSendInfo.mapSendInfo, promiseUpload, pendingSave, pendingAutoSave, autoSave, saveNow, onClose, onMessageAlreadySent, setIsSending, handleNoRecipients, handleNoSubjects, handleNoAttachments: isQuickReply ? args.onNoAttachments : handleNoAttachments, isQuickReply, hasNetworkError, }); const handleSendQuickReply = async () => { // Can send only if a modification has been made, otherwise we can send empty message with the shortcut if (isQuickReply && args.replyUpdated && !isSending) { setIsSending(true); dispatch(removeQuickReplyFlag(modelMessage.localID)); void handleSend({ sendAsScheduled: false })(); } }; const handleDeleteQuickReplyFromShortcut = async () => { void handleDelete(); onClose(); }; const handleExpandComposer = () => { autoSave.cancel?.(); onCompose({ type: ComposeTypes.fromMessage, modelMessage }); }; const lock = opening || !hasRecipients; const hasHotkeysEnabled = mailSettings.Shortcuts === SHORTCUTS.ENABLED; const composerHotkeysArgs: EditorHotkeysHandlers = isComposer ? { type: EditorTypes.composer, composerRef: composerFrameRef, handleClose, handleDelete, handleExpiration, handleManualSave, handlePassword, handleSend: handleSend({ sendAsScheduled: false }), toggleMinimized: args.toggleMinimized || noop, toggleMaximized: args.toggleMaximized || noop, lock, saving, hasHotkeysEnabled, editorRef: args.editorRef, minimizeButtonRef: args.minimizeButtonRef, } : { type: EditorTypes.quickReply, composerRef: composerFrameRef, handleDelete: handleDeleteQuickReplyFromShortcut, handleManualSave, handleSend: handleSendQuickReply, toggleMaximized: handleExpandComposer, lock, saving, hasHotkeysEnabled, editorRef: args.editorRef, }; const attachmentTriggerRef = useComposerHotkeys(composerHotkeysArgs); const handleDeleteDraft = () => { if (isQuickReply) { const { setDeleteDraftModalOpen } = args; const messageFromState = getMessage(modelMessage.localID); // If the message has no changes yet, delete it without opening the delete draft inner modal if ( messageFromState && !messageFromState.data?.ID && !pendingSave.isPending && !pendingAutoSave.isPending ) { void handleDelete(false); } else { setDeleteDraftModalOpen?.(true); } } else { // If the message has no changes yet, delete it without opening the delete draft inner modal if (!modelMessage.data?.ID && !pendingSave.isPending && !pendingAutoSave.isPending) { void handleDelete(false); } else { handleOpenDeleteDraftModal(); } } }; useReduxRefac({ composerID: editorType === EditorTypes.composer ? args.composerID : undefined, handleChange, handleChangeContent, modelMessage, }); return { modelMessage, setModelMessage, syncedMessage, date, timestamp, metadata, rightToLeft, isPlainText, isSending, opening, handleChange, handleChangeContent, handleSend, handleDeleteDraft, handleDelete, handleClose, senderVerificationModal, // Inner modals innerModal, setInnerModal, attachmentsFoundKeyword, handlePassword, handleExpiration, handleCloseInnerModal, handleNoRecipients, handleNoSubjects, handleNoAttachments, handleCloseInsertImageModal, handleSendAnyway, handleCancelSend, // Save autoSave, pendingSave, pauseAutoSave, restartAutoSave, messageSendInfo, reloadSendInfo, // Attachments attachmentTriggerRef, pendingFiles, pendingUploads, uploadInProgress, handleAddAttachmentsStart, handleAddAttachmentsUpload, handleRemoveAttachment, handleRemoveUpload, // Quick reply specific handleExpandComposer, handleSendQuickReply, }; };
3,986
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useComposerDrag.ts
import { MouseEventHandler, Reducer, useCallback, useEffect, useReducer, useRef } from 'react'; import { COMPOSER_MODE } from '@proton/shared/lib/mail/mailSettings'; import debounce from '@proton/utils/debounce'; import throttle from '@proton/utils/throttle'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { ComposerDimension, computeLeftPosition } from '../../helpers/composerPositioning'; interface Props { composerDimension: ComposerDimension; minimized: boolean; maximized: boolean; composerIndex: number; totalComposers: number; drawerOffset: number; } interface State { isDragging: boolean; initialCursorPosition: number | null; offset: number; lastOffset: number; } type Action = | { type: 'start'; payload: Pick<State, 'isDragging' | 'initialCursorPosition'> } | { type: 'stop'; payload: Pick<State, 'isDragging' | 'initialCursorPosition'> } | { type: 'move'; payload: Pick<State, 'offset'> } | { type: 'reset-offset' }; const moveReducer = (state: State, action: Action) => { switch (action.type) { case 'start': case 'move': return { ...state, ...action.payload }; case 'stop': // Add lastOffset based on reducer state because stop callback is executed // in event listener and value is not up to date when passed through the action return { ...state, lastOffset: state.offset, ...action.payload }; case 'reset-offset': return { ...state, offset: 0 }; default: throw new Error('This action does not exist'); } }; const useComposerDrag = ({ composerDimension, drawerOffset, maximized, minimized, totalComposers, composerIndex, }: Props) => { const windowWidth = window.innerWidth - drawerOffset; const mailSettings = useMailModel('MailSettings'); const prevMinimized = useRef(minimized); const prevMaximized = useRef(maximized); const composerLeftStyle = computeLeftPosition(composerDimension, composerIndex, totalComposers, windowWidth); const [{ isDragging, initialCursorPosition, offset, lastOffset }, dispatch] = useReducer<Reducer<State, Action>>( moveReducer, { isDragging: false, initialCursorPosition: null, offset: 0, lastOffset: 0, } ); const handleStartDragging: MouseEventHandler<HTMLElement> = (e) => { dispatch({ type: 'start', payload: { isDragging: true, initialCursorPosition: e.clientX } }); }; const handleStopDragging = () => { dispatch({ type: 'stop', payload: { isDragging: false, initialCursorPosition: null } }); }; const handleMouseMove = useCallback( (e: MouseEvent) => { if (!initialCursorPosition || !isDragging || (maximized && !minimized)) { return; } const prevOffset = offset; const cursorMoveOffset = e.clientX - initialCursorPosition; let finalOffset = prevOffset + cursorMoveOffset; const composerLeftCornerPos = composerLeftStyle + finalOffset; const composerRightCornerPos = composerLeftCornerPos + composerDimension.width; if (composerLeftCornerPos < composerDimension.gutter) { finalOffset = -(composerLeftStyle - composerDimension.gutter); } if (composerRightCornerPos > windowWidth - composerDimension.gutter) { const maxOffset = windowWidth - composerDimension.gutter - composerLeftStyle - composerDimension.width; finalOffset = maxOffset; } dispatch({ type: 'move', payload: { offset: finalOffset } }); }, [isDragging, initialCursorPosition, maximized] ); useEffect(() => { const throttledMouseMove = throttle(handleMouseMove, 20); const debouncedStopDragging = debounce(handleStopDragging, 50); if (isDragging) { document.addEventListener('mousemove', throttledMouseMove); document.addEventListener('mouseup', debouncedStopDragging); document.addEventListener('mouseleave', debouncedStopDragging); } return () => { document.removeEventListener('mousemove', throttledMouseMove); document.removeEventListener('mouseup', debouncedStopDragging); document.removeEventListener('mouseleave', debouncedStopDragging); }; }, [isDragging]); useEffect(() => { dispatch({ type: 'reset-offset' }); }, [composerLeftStyle, totalComposers]); useEffect(() => { if (mailSettings.ComposerMode === COMPOSER_MODE.MAXIMIZED) { dispatch({ type: 'reset-offset' }); } }, [mailSettings.ComposerMode]); useEffect(() => { if ( minimized === false && maximized === true && prevMaximized.current === true && prevMinimized.current === true ) { dispatch({ type: 'reset-offset' }); } prevMinimized.current = minimized; }, [minimized]); useEffect(() => { if ( minimized === false && maximized === false && prevMaximized.current === true && prevMinimized.current === true ) { prevMaximized.current = maximized; return; } dispatch({ type: 'reset-offset' }); prevMaximized.current = maximized; }, [maximized]); return { start: handleStartDragging, offset, // Add some boundaries in order be sure that we are dragging and not clicking isDragging: isDragging === true && (offset > lastOffset + 10 || offset < lastOffset - 10), }; }; export default useComposerDrag;
3,987
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useComposerHotkeys.tsx
import { MutableRefObject, RefObject, useRef } from 'react'; import { EditorActions, HotkeyTuple, useHotkeys } from '@proton/components'; import { isSafari as checkIsSafari } from '@proton/shared/lib/helpers/browser'; import { editorShortcuts } from '@proton/shared/lib/shortcuts/mail'; import noop from '@proton/utils/noop'; import { ExternalEditorActions } from '../../components/composer/editor/EditorWrapper'; import { EditorTypes } from './useComposerContent'; interface ComposerHotkeysHandlers { type: EditorTypes.composer; handleClose: () => Promise<void>; toggleMinimized: () => void; handlePassword: () => void; handleExpiration: () => void; editorRef: MutableRefObject<ExternalEditorActions | undefined>; minimizeButtonRef: RefObject<HTMLButtonElement>; } interface QuickReplyHotkeysHandlers { type: EditorTypes.quickReply; editorRef: MutableRefObject<EditorActions | undefined>; } export type EditorHotkeysHandlers = (ComposerHotkeysHandlers | QuickReplyHotkeysHandlers) & { composerRef: RefObject<HTMLDivElement>; handleSend: () => Promise<void>; handleDelete: () => Promise<void>; handleManualSave: () => Promise<void>; toggleMaximized: () => void; lock: boolean; saving: boolean; hasHotkeysEnabled: boolean; }; export const useComposerHotkeys = (args: EditorHotkeysHandlers) => { const { composerRef, handleSend, handleDelete, toggleMaximized, handleManualSave, lock, saving, hasHotkeysEnabled, type, } = args; const isSafari = checkIsSafari(); const isComposer = type === EditorTypes.composer; const attachmentTriggerRef = useRef<() => void>(noop); const keyHandlers = { close: async (e: KeyboardEvent) => { if (isComposer) { e.preventDefault(); e.stopPropagation(); await args.handleClose(); } }, send: async (e: KeyboardEvent) => { e.preventDefault(); e.stopPropagation(); if (!lock) { await handleSend(); } }, delete: async (e: KeyboardEvent) => { e.preventDefault(); e.stopPropagation(); await handleDelete(); }, save: async (e: KeyboardEvent) => { e.preventDefault(); e.stopPropagation(); if (!saving && !lock) { await handleManualSave(); } }, minimize: (e: KeyboardEvent) => { if (isComposer) { e.preventDefault(); e.stopPropagation(); args.toggleMinimized(); // Focus minimize button on minimize with shortcut, otherwise focus would still be on Composer, and it's still possible to edit fields args.minimizeButtonRef.current?.focus(); } }, maximize: (e: KeyboardEvent) => { e.preventDefault(); e.stopPropagation(); toggleMaximized(); }, addAttachment: (e: KeyboardEvent) => { if (attachmentTriggerRef.current) { e.preventDefault(); e.stopPropagation(); attachmentTriggerRef.current(); } }, encrypt: (e: KeyboardEvent) => { if (isComposer) { e.preventDefault(); e.stopPropagation(); args.handlePassword(); } }, addExpiration: (e: KeyboardEvent) => { if (isComposer) { e.preventDefault(); e.stopPropagation(); args.handleExpiration(); } }, linkModal: (e: KeyboardEvent) => { if (isComposer && args.editorRef?.current) { e.preventDefault(); e.stopPropagation(); args.editorRef.current?.showLinkModal?.(); } }, emojiPicker: (e: KeyboardEvent) => { if (args.editorRef?.current) { e.preventDefault(); e.stopPropagation(); args.editorRef.current?.openEmojiPicker?.(); } }, }; const hotKeysActions: HotkeyTuple[] = hasHotkeysEnabled ? [ [editorShortcuts.close, keyHandlers.close], [editorShortcuts.send, keyHandlers.send], [editorShortcuts.deleteDraft, keyHandlers.delete], [editorShortcuts.save, keyHandlers.save], [ editorShortcuts.minimize, (e) => { if (!isSafari) { keyHandlers.minimize(e); } }, ], [ editorShortcuts.maximize, (e) => { if (!isSafari) { keyHandlers.maximize(e); } }, ], [editorShortcuts.addAttachment, keyHandlers.addAttachment], [editorShortcuts.addEncryption, keyHandlers.encrypt], [editorShortcuts.addExpiration, keyHandlers.addExpiration], [editorShortcuts.addLink, keyHandlers.linkModal], [editorShortcuts.emojiPicker, keyHandlers.emojiPicker], ] : []; useHotkeys(composerRef, hotKeysActions); return attachmentTriggerRef; };
3,988
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useComposerInnerModals.tsx
import { useEffect, useState } from 'react'; import { usePromise } from '../usePromise'; export enum ComposerInnerModalStates { None, Password, Expiration, ScheduleSend, InsertImage, DeleteDraft, NoRecipients, NoSubjects, NoAttachments, } interface UseComposerInnerModals { pendingFiles?: File[]; handleCancelAddAttachment: () => void; } export const useComposerInnerModals = ({ pendingFiles, handleCancelAddAttachment }: UseComposerInnerModals) => { // Flag representing the presence of an inner modal on the composer const [innerModal, setInnerModal] = useState(ComposerInnerModalStates.None); // Keyword found in the email if the user seems to want to send an attachment but there is none const [attachmentsFoundKeyword, setAttachmentsFoundKeyword] = useState(''); const sendPromise = usePromise<void>(); useEffect(() => { if (pendingFiles && pendingFiles.length > 0) { setInnerModal(ComposerInnerModalStates.InsertImage); } if (innerModal === ComposerInnerModalStates.InsertImage && (!pendingFiles || pendingFiles.length === 0)) { setInnerModal(ComposerInnerModalStates.None); } }, [pendingFiles]); const handlePassword = () => { setInnerModal(ComposerInnerModalStates.Password); }; const handleExpiration = () => { setInnerModal(ComposerInnerModalStates.Expiration); }; const handleCloseInnerModal = () => { setInnerModal(ComposerInnerModalStates.None); }; const handleDeleteDraft = () => { setInnerModal(ComposerInnerModalStates.DeleteDraft); }; const handleNoRecipients = () => { setInnerModal(ComposerInnerModalStates.NoRecipients); return sendPromise.renew(); }; const handleNoSubjects = () => { setInnerModal(ComposerInnerModalStates.NoSubjects); return sendPromise.renew(); }; const handleNoAttachments = (keyword: string) => { setInnerModal(ComposerInnerModalStates.NoAttachments); setAttachmentsFoundKeyword(keyword); return sendPromise.renew(); }; const handleCloseInsertImageModal = () => { handleCancelAddAttachment(); handleCloseInnerModal(); }; const handleSendAnyway = () => { sendPromise.resolver(); handleCloseInnerModal(); }; const handleCancelSend = (error: string) => { sendPromise.rejecter(error); handleCloseInnerModal(); }; return { innerModal, setInnerModal, attachmentsFoundKeyword, handlePassword, handleExpiration, handleCloseInnerModal, handleDeleteDraft, handleNoRecipients, handleNoSubjects, handleNoAttachments, handleCloseInsertImageModal, handleSendAnyway, handleCancelSend, }; };
3,989
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useDraftSenderVerification.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Prompt, useAddresses, useModalState } from '@proton/components'; import { getIsAddressActive } from '@proton/shared/lib/helpers/address'; import { Address } from '@proton/shared/lib/interfaces'; import { MessageChange } from '../../components/composer/Composer'; import { getAddressFromEmail, getFromAddress } from '../../helpers/addresses'; import { composerActions } from '../../logic/composers/composersSlice'; import { MessageState } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; interface Props { onChange: MessageChange; composerID: string; } export const useDraftSenderVerification = ({ composerID }: Props) => { const [addresses] = useAddresses(); const [defaultEmail, setDefaultEmail] = useState<string>(''); const dispatch = useAppDispatch(); const [senderChangedModalProps, setSenderChangedModalOpen, render] = useModalState(); const modal = render && ( <Prompt title={c('Title').t`Sender changed`} buttons={[<Button color="norm" onClick={senderChangedModalProps.onClose}>{c('Action').t`OK`}</Button>]} {...senderChangedModalProps} > {c('Info') .t`The original sender of this message is no longer valid. Your message will be sent from your default address ${defaultEmail}.`} </Prompt> ); const verifyDraftSender = async (message: MessageState) => { const currentSender = message.data?.Sender; const actualAddress: Address | undefined = getAddressFromEmail(addresses, currentSender?.Address); if (!actualAddress || !getIsAddressActive(actualAddress)) { const defaultAddress = getFromAddress(addresses, '', undefined); setDefaultEmail(defaultAddress?.Email); if (defaultAddress) { dispatch( composerActions.setSender({ ID: composerID, emailAddress: defaultAddress.Email, }) ); setSenderChangedModalOpen(true); } } }; return { verifyDraftSender, modal }; };
3,990
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useExternalExpiration.ts
import { useState } from 'react'; import { useFormErrors } from '@proton/components'; import { MessageState } from '../../logic/messages/messagesTypes'; export const useExternalExpiration = (message?: MessageState) => { const [password, setPassword] = useState(message?.data?.Password || ''); const [passwordHint, setPasswordHint] = useState(message?.data?.PasswordHint || ''); const { validator, onFormSubmit } = useFormErrors(); return { password, setPassword, passwordHint, setPasswordHint, validator, onFormSubmit, }; };
3,991
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useHandleMessageAlreadySent.tsx
import { c } from 'ttag'; import { useHandler, useNotifications } from '@proton/components'; import { deleteDraft } from '../../logic/messages/draft/messagesDraftActions'; import { MessageState, MessageStateWithData } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; import { useGetMessage } from '../message/useMessage'; import { useCreateDraft } from '../message/useSaveDraft'; interface UseHandleMessageAlreadySentParameters { modelMessage: MessageState; onClose: () => void; } export const useHandleMessageAlreadySent = ({ modelMessage, onClose }: UseHandleMessageAlreadySentParameters) => { const { createNotification } = useNotifications(); const createDraft = useCreateDraft(); const getMessage = useGetMessage(); const dispatch = useAppDispatch(); const duplicateDraft = useHandler(() => { const messageFromCache = getMessage(modelMessage.localID) as MessageStateWithData; void createDraft({ ...messageFromCache, localID: '', data: { ...messageFromCache.data, ID: '', }, }); // remove the old draft from message cache (which will close the composer) dispatch(deleteDraft(modelMessage.localID)); }); const handleMessageAlreadySent = () => { duplicateDraft(); createNotification({ text: c('Error').t`This message has already been sent. A new draft has been saved.`, type: 'error', }); onClose(); }; return handleMessageAlreadySent; };
3,992
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useQuickReplyFocus.tsx
import { useEffect, useState } from 'react'; export const useQuickReplyFocus = () => { const [hasFocus, setHasFocus] = useState(false); useEffect(() => { const clickCallback = (event: MouseEvent) => { try { if (!event.composed) { return false; } const clickedInside = event .composedPath() .some( (element) => element instanceof HTMLElement && 'quick-reply-container' === element.dataset.shortcutTarget ); if (!clickedInside) { setHasFocus(false); } } catch (e) {} }; document.addEventListener('click', clickCallback); return () => { document.removeEventListener('click', clickCallback); }; }, []); return { hasFocus, setHasFocus }; };
3,993
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useReduxRefac.ts
import { useEffect } from 'react'; import { defaultFontStyle } from '@proton/components/components/editor/helpers'; import { useAddresses, useUserSettings } from '@proton/components/hooks'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { MessageChange } from '../../components/composer/Composer'; import { getAddressFromEmail } from '../../helpers/addresses'; import { changeSignature } from '../../helpers/message/messageSignature'; import { selectComposer } from '../../logic/composers/composerSelectors'; import { ComposerID } from '../../logic/composers/composerTypes'; import { MessageState } from '../../logic/messages/messagesTypes'; import { useAppSelector } from '../../logic/store'; import { RecipientType } from '../../models/address'; interface Props { composerID?: ComposerID; modelMessage: MessageState; handleChange: MessageChange; handleChangeContent: (content: string, refreshEditor?: boolean, silent?: boolean) => void; } const useReduxRefac = ({ composerID, modelMessage, handleChange, handleChangeContent }: Props) => { const mailSettings = useMailModel('MailSettings'); const [userSettings] = useUserSettings(); const [addresses = []] = useAddresses(); const composer = useAppSelector((state) => selectComposer(state, composerID || '')); useEffect(() => { if (!composer || composer.changesCount === 0) { return; } if (composer.senderEmailAddress !== modelMessage.data?.Sender.Address) { const prevAddress = getAddressFromEmail(addresses, modelMessage.data?.Sender.Address); const newAddress = getAddressFromEmail(addresses, composer.senderEmailAddress); if (!newAddress || !composer.senderEmailAddress) { return; } const Sender = newAddress ? { Name: newAddress.DisplayName, Address: composer.senderEmailAddress } : undefined; handleChange({ data: { AddressID: newAddress.ID, Sender } }); const fontStyle = defaultFontStyle(mailSettings); handleChangeContent( changeSignature( modelMessage, mailSettings, userSettings, fontStyle, prevAddress?.Signature || '', newAddress?.Signature || '' ), true ); } const recipientTypes = ['ToList', 'CCList', 'BCCList'] as RecipientType[]; for (const type of recipientTypes) { if (composer.recipients[type] !== modelMessage.data?.[type]) { handleChange({ data: { [type]: composer.recipients[type] } }); } } }, [composer?.changesCount]); }; export default useReduxRefac;
3,994
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useScheduleSend.tsx
import { Dispatch, SetStateAction } from 'react'; import { useLocation } from 'react-router-dom'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Prompt, useModalState } from '@proton/components'; import { useConversationCounts, useMessageCounts } from '@proton/components/hooks'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { toMap } from '@proton/shared/lib/helpers/object'; import { LabelCount } from '@proton/shared/lib/interfaces'; import useMailModel from 'proton-mail/hooks/useMailModel'; import useScheduleSendFeature from '../../components/composer/actions/scheduleSend/useScheduleSendFeature'; import { SCHEDULED_MESSAGES_LIMIT } from '../../constants'; import { isConversationMode } from '../../helpers/mailSettings'; import { MessageState, MessageStateWithData } from '../../logic/messages/messagesTypes'; import { updateScheduled } from '../../logic/messages/scheduled/scheduledActions'; import { useAppDispatch } from '../../logic/store'; import { useSendVerifications } from './useSendVerifications'; interface Props { modelMessage: MessageStateWithData; setInnerModal: Dispatch<SetStateAction<any>>; ComposerInnerModal: any; setModelMessage: Dispatch<SetStateAction<MessageState>>; handleSend: () => void; handleNoRecipients?: () => void; handleNoSubjects?: () => void; handleNoAttachments?: (keyword: string) => void; } export const useScheduleSend = ({ modelMessage, setInnerModal, ComposerInnerModal, setModelMessage, handleSend, handleNoRecipients, handleNoSubjects, handleNoAttachments, }: Props) => { const { canScheduleSend } = useScheduleSendFeature(); const location = useLocation(); const dispatch = useAppDispatch(); const [waitBeforeScheduleModalProps, setWaitBeforeScheduleModalOpen] = useModalState(); const mailSettings = useMailModel('MailSettings'); const [conversationCounts, loadingConversationCounts] = useConversationCounts(); const [messageCounts, loadingMessageCounts] = useMessageCounts(); const { preliminaryVerifications } = useSendVerifications( handleNoRecipients, handleNoSubjects, handleNoAttachments ); const referenceCount = toMap( isConversationMode(MAILBOX_LABEL_IDS.SCHEDULED, mailSettings, location) ? conversationCounts : messageCounts, 'LabelID' ) as { [labelID: string]: LabelCount }; const scheduleCount = referenceCount[MAILBOX_LABEL_IDS.SCHEDULED]; const loadingScheduleCount = loadingConversationCounts || loadingMessageCounts; const modal = ( <Prompt title={c('Confirm modal title').t`Message saved to Drafts`} buttons={[ <Button color="norm" onClick={waitBeforeScheduleModalProps.onClose}>{c('Action').t`Got it`}</Button>, ]} data-testid="composer:schedule-send:schedule-limit-reached" {...waitBeforeScheduleModalProps} > {c('Info') .t`Too many messages waiting to be sent. Please wait until another message has been sent to schedule this one.`} </Prompt> ); const handleScheduleSendModal = async () => { if (scheduleCount.Total && scheduleCount.Total >= SCHEDULED_MESSAGES_LIMIT) { setWaitBeforeScheduleModalOpen(true); } else { try { await preliminaryVerifications(modelMessage); setInnerModal(ComposerInnerModal.ScheduleSend); } catch { /* Nothing to do but an error is expected if preliminaryVerifications fails Catching the error is mandatory to make testing pass for some jest sorcery */ } } }; const handleScheduleSend = async (scheduledAt: number) => { if (scheduleCount.Total && scheduleCount.Total >= SCHEDULED_MESSAGES_LIMIT) { setWaitBeforeScheduleModalOpen(true); } else { try { // check if all needed composer fields are filled await preliminaryVerifications(modelMessage); // Save scheduled at in store dispatch(updateScheduled({ ID: modelMessage.localID, scheduledAt })); // Save scheduled at in message model setModelMessage({ ...modelMessage, draftFlags: { ...modelMessage.draftFlags, scheduledAt, }, }); // Handle send setTimeout(handleSend); } catch {} } }; return { canScheduleSend: canScheduleSend && !modelMessage.draftFlags?.expiresIn && !modelMessage.data?.ExpirationTime, scheduleCount, loadingScheduleCount, handleScheduleSendModal, handleScheduleSend, modal, }; };
3,995
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useSendHandler.tsx
import { Dispatch, SetStateAction } from 'react'; import { c } from 'ttag'; import { useEventManager, useHandler, useNotifications } from '@proton/components'; import { Cancellable } from '@proton/components/hooks/useHandler'; import { getOnlineStatus } from '@proton/components/hooks/useOnline'; import SendingMessageNotification, { SendingMessageNotificationManager, createSendingMessageNotificationManager, } from '../../components/notifications/SendingMessageNotification'; import { MESSAGE_ALREADY_SENT_INTERNAL_ERROR, SAVE_DRAFT_ERROR_CODES, SEND_EMAIL_ERROR_CODES } from '../../constants'; import { useOnCompose } from '../../containers/ComposeProvider'; import { endSending, startSending } from '../../logic/messages/draft/messagesDraftActions'; import { MessageState, MessageStateWithData } from '../../logic/messages/messagesTypes'; import { cancelScheduled } from '../../logic/messages/scheduled/scheduledActions'; import { useAppDispatch } from '../../logic/store'; import { MapSendInfo } from '../../models/crypto'; import { useGetMessage } from '../message/useMessage'; import { PromiseHandlers } from '../usePromise'; import { ComposeTypes } from './useCompose'; import { useSendMessage } from './useSendMessage'; import { useSendVerifications } from './useSendVerifications'; export interface UseSendHandlerParameters { // Composer will be unmounted and modelMessage will continue changing after sending start getModelMessage: () => MessageState; setModelMessage: (message: MessageState) => void; ensureMessageContent: () => void; mapSendInfo: MapSendInfo; promiseUpload?: Promise<void>; pendingSave: PromiseHandlers<void>; pendingAutoSave: PromiseHandlers<void>; autoSave: ((message: MessageState) => Promise<void>) & Cancellable; saveNow: (message: MessageState) => Promise<void>; onClose: () => void; onMessageAlreadySent: () => void; handleNoRecipients?: () => void; handleNoSubjects?: () => void; handleNoAttachments?: (keyword: string) => void; setIsSending?: Dispatch<SetStateAction<boolean>>; isQuickReply?: boolean; hasNetworkError: boolean; } export const useSendHandler = ({ getModelMessage, setModelMessage, ensureMessageContent, mapSendInfo, promiseUpload, pendingSave, pendingAutoSave, autoSave, saveNow, onClose, onMessageAlreadySent, handleNoRecipients, handleNoSubjects, handleNoAttachments, setIsSending, isQuickReply, hasNetworkError, }: UseSendHandlerParameters) => { const { createNotification, hideNotification } = useNotifications(); const { call } = useEventManager(); const dispatch = useAppDispatch(); const getMessage = useGetMessage(); const { preliminaryVerifications, extendedVerifications } = useSendVerifications( handleNoRecipients, handleNoSubjects, handleNoAttachments ); const sendMessage = useSendMessage(); const onCompose = useOnCompose(); const handleSendAfterUploads = useHandler(async (notifManager: SendingMessageNotificationManager) => { let verificationResults; let inputMessage; let mapSendPrefs; let alreadySaved; try { await pendingSave.promise; // Wait for potential ongoing save request verificationResults = await extendedVerifications(getModelMessage() as MessageStateWithData, mapSendInfo); mapSendPrefs = verificationResults.mapSendPrefs; inputMessage = verificationResults.cleanMessage; alreadySaved = !!getMessage(inputMessage.localID)?.data?.ID && !pendingAutoSave.isPending && !verificationResults.hasChanged && !hasNetworkError; // If the last save failed because of no internet connection, we want to force saving before sending // Don't abort before pendingAutoSave is checked autoSave.cancel?.(); // sendMessage expect a saved and up to date message // If there is anything new or pending, we have to make a last save if (!alreadySaved) { await saveNow(inputMessage); await call(); } // Document is frequently reset in the state, keeping the one from the model // Rest is more up to date in the state, several changes could have happen since capturing the model inputMessage = { ...getModelMessage(), data: (getMessage(inputMessage.localID) as MessageStateWithData).data, }; } catch { hideNotification(notifManager.ID); onCompose({ type: ComposeTypes.existingDraft, existingDraft: getModelMessage(), fromUndo: true }); return; } try { await sendMessage({ inputMessage, mapSendPrefs, onCompose, alreadySaved, sendingMessageNotificationManager: notifManager, useSilentApi: true, sendingFrom: isQuickReply ? 'quick-reply' : 'composer', }); } catch (error: any) { hideNotification(notifManager.ID); if ( [SAVE_DRAFT_ERROR_CODES.MESSAGE_ALREADY_SENT, SEND_EMAIL_ERROR_CODES.MESSAGE_ALREADY_SENT].includes( error.data?.Code ) ) { onMessageAlreadySent(); throw error; } if (error.data?.Error) { createNotification({ text: error.data?.Error, type: 'error', }); throw error; } createNotification({ text: c('Error').t`Error while sending the message. Message is not sent.`, type: 'error', }); console.error('Error while sending the message.', error); throw error; } }); type HandleSendOptions = { /** * If true will send message with its scheduled flag if there's one * If false will reset message scheduled flag then send it */ sendAsScheduled?: boolean; }; const handleSend = useHandler(({ sendAsScheduled = false }: HandleSendOptions = {}) => async () => { const { localID, draftFlags } = getModelMessage(); const scheduledAt = (() => { if (!draftFlags?.scheduledAt) { return undefined; } if (sendAsScheduled) { return draftFlags.scheduledAt; } else { dispatch(cancelScheduled({ ID: localID })); const modelMsg = getModelMessage(); setModelMessage({ ...modelMsg, draftFlags: { ...modelMsg.draftFlags, scheduledAt: undefined, }, }); return undefined; } })(); const notifManager = createSendingMessageNotificationManager(); // If scheduledAt is set we already performed the preliminary verifications if (!scheduledAt) { try { await preliminaryVerifications(getModelMessage() as MessageStateWithData); } catch (error: any) { if (error?.message === MESSAGE_ALREADY_SENT_INTERNAL_ERROR) { onMessageAlreadySent(); } throw error; } } // Display growler to receive direct feedback (UX) since sendMessage function is added to queue (and other async process could need to complete first) notifManager.ID = createNotification({ text: <SendingMessageNotification scheduledAt={scheduledAt} manager={notifManager} />, expiration: -1, showCloseButton: false, }); ensureMessageContent(); try { setIsSending?.(true); dispatch(startSending(localID)); // If the user has no internet connection, do not close the composer on send, or we will lose last updates made on the draft const isOnline = getOnlineStatus(); // Closing the composer instantly, all the send process will be in background // In quick reply however, we want to keep the editor opened while saving if (!isQuickReply && isOnline) { onClose(); } try { await promiseUpload; } catch (error: any) { hideNotification(notifManager.ID); createNotification({ text: c('Error').t`Error while uploading attachments. Message is not sent.`, type: 'error', }); console.error('Error while uploading attachments.', error); onCompose({ type: ComposeTypes.existingDraft, existingDraft: getModelMessage(), fromUndo: true }); throw error; } // Split handlers to have the updated version of the message await handleSendAfterUploads(notifManager); } finally { const asyncFinally = async () => { // Receive all updates about the current message before "releasing" it to prevent any flickering await call(); // Whatever happens once the composer is closed, the sending flag is reset when finished dispatch(endSending(localID)); setIsSending?.(false); // If quick reply we can close the editor if (isQuickReply) { onClose(); } }; void asyncFinally(); } }); return handleSend; };
3,996
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useSendMessage.tsx
import { useCallback } from 'react'; import { useHistory } from 'react-router'; import { c } from 'ttag'; import { useApi, useEventManager, useNotifications } from '@proton/components'; import { WorkerDecryptionResult } from '@proton/crypto'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { SendPreferences } from '@proton/shared/lib/interfaces/mail/crypto'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { getRecipientsAddresses } from '@proton/shared/lib/mail/messages'; import unique from '@proton/utils/unique'; import LoadingNotificationContent from '../../components/notifications/LoadingNotificationContent'; import { SendingMessageNotificationManager } from '../../components/notifications/SendingMessageNotification'; import { MIN_DELAY_SENT_NOTIFICATION, SAVE_DRAFT_ERROR_CODES, SEND_EMAIL_ERROR_CODES } from '../../constants'; import { pickMessageInfosForSentry } from '../../helpers/errors'; import { getParamsFromPathname, setParamsInLocation } from '../../helpers/mailboxUrl'; import { encryptPackages } from '../../helpers/send/sendEncrypt'; import { sendFormatter } from '../../helpers/send/sendFormatter'; import { attachSubPackages } from '../../helpers/send/sendSubPackages'; import { generateTopPackages } from '../../helpers/send/sendTopPackages'; import { updateAttachment } from '../../logic/attachments/attachmentsActions'; import { cancelSendMessage, endUndo, sent, updateExpires } from '../../logic/messages/draft/messagesDraftActions'; import { MessageStateWithData, MessageStateWithDataFull } from '../../logic/messages/messagesTypes'; import { cancelScheduled } from '../../logic/messages/scheduled/scheduledActions'; import { useAppDispatch } from '../../logic/store'; import { useGetMessageKeys } from '../message/useGetMessageKeys'; import { useGetMessage } from '../message/useMessage'; import { useGetAttachment } from '../attachments/useAttachment'; import useDelaySendSeconds from '../useDelaySendSeconds'; import { ComposeTypes, OnCompose } from './useCompose'; import { useSendModifications } from './useSendModifications'; // Reference: Angular/src/app/composer/services/sendMessage.js interface UseSendMessageParameters { inputMessage: MessageStateWithData; mapSendPrefs: SimpleMap<SendPreferences>; onCompose: OnCompose; alreadySaved?: boolean; sendingMessageNotificationManager?: SendingMessageNotificationManager; useSilentApi?: boolean; sendingFrom?: string; } export const useSendMessage = () => { const api = useApi(); const getMessageKeys = useGetMessageKeys(); const getAttachment = useGetAttachment(); const dispatch = useAppDispatch(); const { call } = useEventManager(); const getMessage = useGetMessage(); const history = useHistory<any>(); const delaySendSeconds = useDelaySendSeconds(); const { createNotification, hideNotification } = useNotifications(); const sendModification = useSendModifications(); const onUpdateAttachment = (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => { dispatch(updateAttachment({ ID, attachment })); }; return useCallback( async ({ inputMessage, mapSendPrefs, onCompose, sendingMessageNotificationManager, useSilentApi = false, sendingFrom, }: UseSendMessageParameters) => { const { localID, data } = inputMessage; const hasUndo = !!delaySendSeconds; let hasClickedUndoSend = false; const handleUndo = async () => { hasClickedUndoSend = true; if (sendingMessageNotificationManager) { hideNotification(sendingMessageNotificationManager.ID); } const savedMessage = getMessage(localID) as MessageStateWithData; const isScheduledMessage = savedMessage.draftFlags?.scheduledAt; const request = async () => { if (isScheduledMessage) { await dispatch(cancelScheduled({ ID: savedMessage.localID })); await dispatch(cancelSendMessage({ messageID: savedMessage.data.ID })).unwrap(); } else { await dispatch(cancelSendMessage({ messageID: savedMessage.data.ID })).unwrap(); } await call(); }; const promise = request(); const undoingSendNotification = createNotification({ text: ( <LoadingNotificationContent loadingText={c('Message notification').t`Undoing send...`} loadedText={ isScheduledMessage ? c('Message notification').t`Scheduled sending undone` : c('Message notification').t`Sending undone` } promise={promise} /> ), expiration: -1, showCloseButton: false, }); const startTime = performance.now(); try { await promise; const endTime = performance.now(); // Display the notification at least 1,5 second to let the user read it setTimeout( () => { hideNotification(undoingSendNotification); }, endTime - startTime > 2000 ? 0 : 1500 ); } catch (error: any) { hideNotification(undoingSendNotification); throw error; } // Re-open draft onCompose({ type: ComposeTypes.existingDraft, existingDraft: { localID, data, }, fromUndo: true, }); }; const prepareMessageToSend = async () => { const messageKeys = await getMessageKeys(inputMessage.data); // Last minute modifications on the message before sending const message = (await sendModification(inputMessage)) as MessageStateWithDataFull; const emails = unique(getRecipientsAddresses(inputMessage.data)); const hasHtml = Object.values(mapSendPrefs).some( (sendPref) => sendPref?.mimeType === MIME_TYPES.DEFAULT ); if (hasHtml && message.messageDocument?.document === undefined) { const errorMessage = 'Sending with missing document error'; captureMessage(errorMessage, { extra: { message: pickMessageInfosForSentry(message) } }); throw new Error(errorMessage); } let packages = await generateTopPackages( message, messageKeys, mapSendPrefs, getAttachment, onUpdateAttachment, api ); packages = await attachSubPackages(packages, message.data, emails, mapSendPrefs, api); packages = await encryptPackages(message, messageKeys, packages); // expiresIn is not saved on the API and then empty in `message`, we need to refer to `inputMessage` const { expiresIn, autoSaveContacts, scheduledAt } = inputMessage.draftFlags || {}; // Scheduled messages cannot expire, the expiration is not added on the BE side // We need to remove the expiration also on FE side otherwise we will see on the UI that the message // can expire (icon + banner) when it's not possible. if (scheduledAt && expiresIn) { await dispatch(updateExpires({ ID: message.localID, expiresIn: undefined })); } const payload = sendFormatter({ ID: message.data?.ID, packages, expiresIn, delaySendSeconds, autoSaveContacts, scheduledAt, sendingFrom, }); return api<{ Sent: Message }>({ ...payload, silence: useSilentApi, timeout: 60000, }); }; const promise = prepareMessageToSend().then((result) => { const now = Date.now(); const delay = now + delaySendSeconds * 1000; const delta = delay - now; const undoTimeout = delta > 0 ? delta : 0; return { ...result, undoTimeout }; }); sendingMessageNotificationManager?.setProperties(promise, handleUndo); try { const { Sent, undoTimeout } = await promise; const endSending = async () => { await wait(Math.max(undoTimeout, MIN_DELAY_SENT_NOTIFICATION)); if (sendingMessageNotificationManager) { hideNotification(sendingMessageNotificationManager.ID); } if (hasUndo) { // When we close the notification, we consider the message as sent // It's a bit more complicated in reality, the server will take a few more seconds to actually send the message // It creates a small window of time during which the UI allow to reply to message in the outbox // This should be handled by the backend dispatch(endUndo({ messageID: localID, hasClickedUndo: hasClickedUndoSend })); } hasClickedUndoSend = false; }; void endSending(); dispatch(sent(Sent)); // Navigation to the sent message const { params: { labelID, elementID }, } = getParamsFromPathname(history.location.pathname); if (elementID === Sent.ConversationID) { history.push( setParamsInLocation(history.location, { labelID, elementID: Sent.ConversationID, messageID: Sent.ID, }) ); } } catch (error: any) { if ( ![ SAVE_DRAFT_ERROR_CODES.MESSAGE_ALREADY_SENT, SEND_EMAIL_ERROR_CODES.MESSAGE_ALREADY_SENT, SAVE_DRAFT_ERROR_CODES.DRAFT_DOES_NOT_EXIST, ].includes(error?.data?.Code) ) { hasClickedUndoSend = false; onCompose({ type: ComposeTypes.existingDraft, existingDraft: { localID, data, }, fromUndo: true, }); } throw error; } }, [delaySendSeconds] ); };
3,997
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useSendModifications.tsx
import { useCallback } from 'react'; import { useAuthentication } from '@proton/components'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants'; import { isAttachPublicKey, isPlainText } from '@proton/shared/lib/mail/messages'; import { upload } from '../../helpers/attachment/attachmentUploader'; import { attachPublicKey } from '../../helpers/message/messageAttachPublicKey'; import { replaceDataUrl } from '../../helpers/message/messageDataUrl'; import { createEmbeddedImageFromUpload } from '../../helpers/message/messageEmbeddeds'; import { sendModifications } from '../../logic/messages/draft/messagesDraftActions'; import { MessageEmbeddedImage, MessageStateWithData } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; import { useGetMessageKeys } from '../message/useGetMessageKeys'; import { useGetMessage } from '../message/useMessage'; export const useSendModifications = () => { const getMessage = useGetMessage(); const dispatch = useAppDispatch(); const getMessageKeys = useGetMessageKeys(); const auth = useAuthentication(); return useCallback(async (inputMessage: MessageStateWithData) => { const message = { ...(getMessage(inputMessage.localID) as MessageStateWithData), messageDocument: inputMessage.messageDocument, }; const messageKeys = await getMessageKeys(message.data); const attachments: Attachment[] = []; const images: MessageEmbeddedImage[] = []; const isPlainTextMessage = isPlainText(message.data); // Add public key if selected if (isAttachPublicKey(message.data)) { const attachment = await attachPublicKey(message, messageKeys, auth.UID); if (attachment) { attachments.push(attachment); } } // Replace data url images by embedded images const replacedImages = replaceDataUrl(message); if (replacedImages.length) { for (const { cid, file } of replacedImages) { const [uploadInfo] = upload( [file], message, messageKeys, isPlainTextMessage ? ATTACHMENT_DISPOSITION.ATTACHMENT : ATTACHMENT_DISPOSITION.INLINE, auth.UID, cid ); const uploadResult = await uploadInfo.resultPromise; attachments.push(uploadResult.attachment); if (!isPlainTextMessage) { images.push(createEmbeddedImageFromUpload(uploadResult.attachment)); } } } // Centralized update cache after modifications // Theses changes are willingly not saved to the draft dispatch(sendModifications({ ID: inputMessage.localID, attachments, images })); // Applying modifications on the model message to be sent // But keeping the document from the model return { ...getMessage(inputMessage.localID), messageDocument: inputMessage.messageDocument, }; }, []); };
3,998
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/hooks/composer/useSendVerifications.test.ts
import loudRejection from 'loud-rejection'; import { MIME_TYPES, MIME_TYPES_MORE, PGP_SCHEMES } from '@proton/shared/lib/constants'; import { EncryptionPreferences } from '@proton/shared/lib/mail/encryptionPreferences'; import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import getSendPreferences from '@proton/shared/lib/mail/send/getSendPreferences'; import { clearAll, renderHook } from '../../helpers/test/helper'; import { SendInfo } from '../../models/crypto'; import { useSendVerifications } from './useSendVerifications'; loudRejection(); const createMessage: (emailAddress: string) => {} = (emailAddress) => ({ data: { ToList: [{ Address: emailAddress, Name: 'test' }], CCList: [], BCCList: [], }, }); const mockEncryptionPreferences: { [email: string]: EncryptionPreferences } = { 'internal.pinned@test.email': { sign: true, encrypt: true, isSendKeyPinned: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: true, isContact: true, isInternalWithDisabledE2EEForMail: false, }, 'internal.deleted@test.email': { sign: true, encrypt: true, isSendKeyPinned: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: false, isContact: true, isInternalWithDisabledE2EEForMail: false, }, 'internal.unpinned@test.email': { sign: true, encrypt: true, isSendKeyPinned: false, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: false, isContact: true, isInternalWithDisabledE2EEForMail: false, }, 'internal.pinned.e2eedisabled@test.email': { sign: true, encrypt: true, isSendKeyPinned: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: true, isContact: true, isInternalWithDisabledE2EEForMail: true, }, 'external.encryptsign@test.email': { sign: true, encrypt: true, isSendKeyPinned: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: false, hasApiKeys: false, hasPinnedKeys: true, isContact: true, isInternalWithDisabledE2EEForMail: false, }, 'external.deleted@test.email': { sign: true, encrypt: false, isSendKeyPinned: false, isContactSignatureVerified: undefined, contactSignatureTimestamp: undefined, // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: false, hasApiKeys: false, hasPinnedKeys: false, isContact: true, isInternalWithDisabledE2EEForMail: false, }, 'external.signonly@test.email': { sign: true, encrypt: false, isSendKeyPinned: true, isContactSignatureVerified: true, contactSignatureTimestamp: new Date(), // irrelevant fields scheme: PGP_SCHEMES.PGP_MIME, mimeType: MIME_TYPES_MORE.AUTOMATIC, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: false, hasApiKeys: false, hasPinnedKeys: true, isContact: true, isInternalWithDisabledE2EEForMail: false, }, }; const mockCreateModalSpy = jest.fn(({ ...props }) => { props.props.onSubmit(); }); jest.mock('@proton/components', () => { const componentsMock = jest.requireActual('@proton/components'); const useGetEncryptionPreferences = () => { const getEncryptionPreferences: ({ email }: { email: string }) => EncryptionPreferences = ({ email }) => mockEncryptionPreferences[email]; return getEncryptionPreferences; }; return { __esModule: true, ...componentsMock, useModals: function () { return { createModal: mockCreateModalSpy, }; }, useGetEncryptionPreferences, }; }); const originalResizeObserver = window.ResizeObserver; const ResizeObserverMock = jest.fn(() => ({ disconnect: jest.fn(), observe: jest.fn(), unobserve: jest.fn(), })); beforeAll(() => { window.ResizeObserver = ResizeObserverMock; }); afterAll(() => { window.ResizeObserver = originalResizeObserver; }); describe('useSendVerifications', () => { const setup = async () => { const result = await renderHook(() => useSendVerifications()); return result.result.current.extendedVerifications as any; }; afterEach(clearAll); describe('extended verifications of last-minute preferences', () => { // eslint-disable-next-line no-only-tests/no-only-tests it('should warn user on deletion of contact with pinned keys (internal)', async () => { const recipient = 'internal.deleted@test.email'; const cachedPreferences: SendInfo = { sendPreferences: { encrypt: true, sign: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).toHaveBeenCalled(); // user was warned const lastMinutePreferences = mockEncryptionPreferences[recipient]; expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should warn user on deletion of contact with pinned keys (external)', async () => { const recipient = 'external.deleted@test.email'; const cachedPreferences: SendInfo = { sendPreferences: { encrypt: true, sign: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).toHaveBeenCalled(); // user was warned const lastMinutePreferences = mockEncryptionPreferences[recipient]; expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should warn user on encryption disabled with contact with pinned keys (internal case only)', async () => { const recipient = 'internal.pinned.e2eedisabled@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { encrypt: true, sign: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp!), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).toHaveBeenCalled(); // user was warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with last-minute prefs on contact deletion with encryption disabled (external)', async () => { const recipient = 'external.deleted@test.email'; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: false, isPublicKeyPinned: true, hasApiKeys: false, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned const lastMinutePreferences = mockEncryptionPreferences[recipient]; expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should silently send with last-minute prefs on last-minute unpinning via new signature (internal)', async () => { const recipient = 'internal.unpinned@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! - 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should silently send with last-minute prefs on last-minute encryption disabling via new signature (external)', async () => { const recipient = 'external.signonly@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: true, hasApiKeys: false, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! - 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with cached prefs on last-minute unpinning via old signature (internal)', async () => { const recipient = 'internal.unpinned@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: true, hasApiKeys: true, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! + 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(cachedPreferences.sendPreferences); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with cached prefs on last-minute encryption disabling via old signature (external)', async () => { const recipient = 'external.signonly@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: true, hasApiKeys: false, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! + 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(cachedPreferences.sendPreferences); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with last-minute prefs on last-minute key pinning (internal)', async () => { const recipient = 'internal.pinned@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: false, hasApiKeys: true, hasPinnedKeys: false, pgpScheme: PACKAGE_TYPE.SEND_PM, mimeType: MIME_TYPES.DEFAULT, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: undefined, creationTime: undefined, }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with last-minute prefs on encryption enabled last-minute (external)', async () => { const recipient = 'external.encryptsign@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: false, isPublicKeyPinned: true, hasApiKeys: false, hasPinnedKeys: true, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: true, creationTime: new Date(+lastMinutePreferences.contactSignatureTimestamp! - 1), }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); it('should silently send with last-minute prefs for non-contacts (internal)', async () => { const recipient = 'internal.deleted@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: true, isPublicKeyPinned: false, hasApiKeys: true, hasPinnedKeys: false, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: undefined, creationTime: undefined, }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should silently send with last-minute prefs for non-contacts (external)', async () => { const recipient = 'external.deleted@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const cachedPreferences: SendInfo = { sendPreferences: { sign: true, encrypt: false, isPublicKeyPinned: false, hasApiKeys: false, hasPinnedKeys: false, pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME, mimeType: MIME_TYPES.MIME, encryptionDisabled: false, }, contactSignatureInfo: { isVerified: undefined, creationTime: undefined, }, loading: false, emailValidation: true, }; const extendedVerifications = await setup(); const message = createMessage(recipient); const mapSendInfo = { [recipient]: cachedPreferences }; const { mapSendPrefs } = await extendedVerifications(message, mapSendInfo); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(false); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(false); }); it('should silently send with last-minute prefs if no trusted send prefs are given', async () => { const recipient = 'internal.pinned@test.email'; const lastMinutePreferences = mockEncryptionPreferences[recipient]; const extendedVerifications = await setup(); const message = createMessage(recipient); const { mapSendPrefs } = await extendedVerifications(message, {}); expect(mockCreateModalSpy).not.toHaveBeenCalled(); // user was not warned expect(mapSendPrefs[recipient]).toStrictEqual(getSendPreferences(lastMinutePreferences, message)); // sanity checks expect(mapSendPrefs[recipient].encrypt).toBe(true); expect(mapSendPrefs[recipient].isPublicKeyPinned).toBe(true); }); }); });
3,999