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
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/elements.test.ts
|
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { Conversation, ConversationLabel } from '../models/conversation';
import { getCounterMap, getDate, isConversation, isMessage, isUnread, sort } from './elements';
describe('elements', () => {
describe('isConversation / isMessage', () => {
it('should return conversation when there is no conversationID in message', () => {
const element: Conversation = { ID: 'conversationID' };
expect(isConversation(element)).toBe(true);
expect(isMessage(element)).toBe(false);
});
it('should return message when there is a conversationID in message', () => {
const element = { ConversationID: 'something' } as Message;
expect(isConversation(element)).toBe(false);
expect(isMessage(element)).toBe(true);
});
});
describe('sort', () => {
it('should sort by time', () => {
const elements = [
{ Time: 1, ID: '1' },
{ Time: 2, ID: '2' },
{ Time: 3, ID: '3' },
];
expect(sort(elements, { sort: 'Time', desc: false }, 'labelID')).toEqual(elements);
});
it('should sort by time desc', () => {
const elements = [
{ Time: 1, ID: '1' },
{ Time: 2, ID: '2' },
{ Time: 3, ID: '3' },
];
expect(sort(elements, { sort: 'Time', desc: true }, 'labelID')).toEqual([...elements].reverse());
});
it('should fallback on order', () => {
const elements = [
{ ID: '1', Time: 1, Order: 3 },
{ ID: '2', Time: 1, Order: 2 },
{ ID: '3', Time: 1, Order: 1 },
];
expect(sort(elements, { sort: 'Time', desc: true }, 'labelID')).toEqual([...elements]);
});
it('should sort by order reversed for time asc', () => {
const elements = [
{ ID: '1', Time: 1, Order: 3 },
{ ID: '2', Time: 1, Order: 2 },
{ ID: '3', Time: 1, Order: 1 },
];
expect(sort(elements, { sort: 'Time', desc: false }, 'labelID')).toEqual([...elements].reverse());
});
it('should sort by size', () => {
const elements = [
{ ID: '1', Size: 1 },
{ ID: '2', Size: 2 },
{ ID: '3', Size: 3 },
];
expect(sort(elements, { sort: 'Size', desc: false }, 'labelID')).toEqual(elements);
});
});
describe('getCounterMap', () => {
it('should use conversation or message count depending the label type', () => {
const inboxCount = { LabelID: MAILBOX_LABEL_IDS.INBOX, Unread: 5 };
const sentConversationCount = { LabelID: MAILBOX_LABEL_IDS.SENT, Unread: 5 };
const sentMessageCount = { LabelID: MAILBOX_LABEL_IDS.SENT, Unread: 10 };
const result = getCounterMap(
[],
[inboxCount, sentConversationCount],
[sentMessageCount],
{} as MailSettings
);
expect(result[MAILBOX_LABEL_IDS.INBOX]?.Unread).toBe(inboxCount.Unread);
expect(result[MAILBOX_LABEL_IDS.SENT]?.Unread).toBe(sentMessageCount.Unread);
expect(result[MAILBOX_LABEL_IDS.STARRED]).toBeUndefined();
});
});
describe('getDate', () => {
const Time = 42;
const WrongTime = 43;
const expected = new Date(Time * 1000);
it('should not fail for an undefined element', () => {
expect(getDate(undefined, '') instanceof Date).toBe(true);
});
it('should take the Time property of a message', () => {
const message = { ConversationID: '', Time } as Message;
expect(getDate(message, '')).toEqual(expected);
});
it('should take the right label ContextTime of a conversation', () => {
const LabelID = 'LabelID';
const conversation = {
ID: 'conversationID',
Labels: [
{ ID: 'something', ContextTime: WrongTime } as ConversationLabel,
{ ID: LabelID, ContextTime: Time } as ConversationLabel,
],
};
expect(getDate(conversation, LabelID)).toEqual(expected);
});
it('should take the Time property of a conversation', () => {
const conversation = { Time, ID: 'conversationID' };
expect(getDate(conversation, '')).toEqual(expected);
});
it('should take the label time in priority for a conversation', () => {
const LabelID = 'LabelID';
const conversation = {
ID: 'conversationID',
Time: WrongTime,
Labels: [{ ID: LabelID, ContextTime: Time } as ConversationLabel],
};
expect(getDate(conversation, LabelID)).toEqual(expected);
});
});
describe('isUnread', () => {
it('should not fail for an undefined element', () => {
expect(isUnread(undefined, '')).toBe(false);
});
it('should take the Unread property of a message', () => {
const message = { ConversationID: '', Unread: 0 } as Message;
expect(isUnread(message, '')).toBe(false);
});
it('should take the right label ContextNumUnread of a conversation', () => {
const LabelID = 'LabelID';
const conversation = {
ID: 'conversationID',
Labels: [
{ ID: 'something', ContextNumUnread: 1 } as ConversationLabel,
{ ID: LabelID, ContextNumUnread: 0 } as ConversationLabel,
],
};
expect(isUnread(conversation, LabelID)).toBe(false);
});
it('should take the ContextNumUnread property of a conversation', () => {
const conversation = { ContextNumUnread: 0, ID: 'conversationID' };
expect(isUnread(conversation, '')).toBe(false);
});
it('should take the NumUnread property of a conversation', () => {
const conversation = { NumUnread: 0, ID: 'conversationID' };
expect(isUnread(conversation, '')).toBe(false);
});
it('should take the value when all are present for a conversation', () => {
const LabelID = 'LabelID';
const conversation = {
ID: 'conversationID',
ContextNumUnread: 1,
NumUnread: 1,
Labels: [{ ID: LabelID, ContextNumUnread: 0 } as ConversationLabel],
};
expect(isUnread(conversation, LabelID)).toBe(false);
});
});
});
| 3,800
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/elements.ts
|
import { format, formatRelative } from 'date-fns';
import { Location } from 'history';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { omit, toMap } from '@proton/shared/lib/helpers/object';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { Folder } from '@proton/shared/lib/interfaces/Folder';
import { Label, LabelCount } from '@proton/shared/lib/interfaces/Label';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { getSender, hasAttachments as messageHasAttachments } from '@proton/shared/lib/mail/messages';
import diff from '@proton/utils/diff';
import unique from '@proton/utils/unique';
import { ELEMENT_TYPES } from '../constants';
import { getSnoozeDate } from '../logic/snoozehelpers';
import { Conversation } from '../models/conversation';
import { Element } from '../models/element';
import { LabelIDsChanges } from '../models/event';
import { Filter, SearchParameters, Sort } from '../models/tools';
import {
getLabelIDs as conversationGetLabelIDs,
getSenders as conversationGetSenders,
getTime as conversationGetTime,
hasAttachments as conversationHasAttachments,
isUnread as conversationIsUnread,
getNumAttachments as conversationNumAttachments,
} from './conversation';
import { isConversationMode } from './mailSettings';
const { INBOX, TRASH, SPAM, ARCHIVE, SCHEDULED, SNOOZED } = MAILBOX_LABEL_IDS;
export interface TypeParams {
labelID?: string;
mailSettings: any;
location: Location;
}
export const getCurrentType = ({ labelID, mailSettings, location }: TypeParams) =>
isConversationMode(labelID, mailSettings, location) ? ELEMENT_TYPES.CONVERSATION : ELEMENT_TYPES.MESSAGE;
export const isMessage = (element: Element | undefined): boolean =>
typeof (element as Message)?.ConversationID === 'string';
export const isConversation = (element: Element | undefined): boolean => !isMessage(element);
/**
* Get the date of an element.
* @param element
* @param labelID is only used for a conversation. Yet mandatory not to forget to consider its use.
*/
export const getDate = (element: Element | undefined, labelID: string | undefined) => {
if (!element) {
return new Date();
}
const time = isMessage(element) ? element.Time : conversationGetTime(element, labelID);
return new Date((time || 0) * 1000);
};
/**
* Get readable time to display from message / conversation
* @param element.Time
* @return Jan 17, 2016
*/
export const getReadableTime = (element: Element | undefined, labelID: string | undefined) =>
formatRelative(getDate(element, labelID), new Date());
export const getReadableFullTime = (element: Element | undefined, labelID: string | undefined) =>
format(getDate(element, labelID), 'Ppp');
/**
* Return if the element is to be considered in read or unread status
* @param element
* @param labelID is only used for a conversation. Yet mandatory not to forget to consider its use.
*/
export const isUnread = (element: Element | undefined, labelID: string | undefined) => {
if (!element) {
return false;
}
if (isMessage(element)) {
return (element as Message).Unread !== 0;
}
return conversationIsUnread(element as Conversation, labelID);
};
export const isUnreadMessage = (message: Message) => isUnread(message, undefined);
export const getLabelIDs = (element: Element | undefined, contextLabelID: string | undefined) =>
isMessage(element)
? (element as Message | undefined)?.LabelIDs?.reduce<{ [labelID: string]: boolean | undefined }>(
(acc, labelID) => {
acc[labelID] = true;
return acc;
},
{}
) || {}
: conversationGetLabelIDs(element, contextLabelID);
export const hasLabel = (element: Element | undefined, labelID: string) =>
getLabelIDs(element, undefined)[labelID] !== undefined;
export const isStarred = (element: Element) => hasLabel(element, MAILBOX_LABEL_IDS.STARRED);
export const getSize = (element: Element) => element.Size || 0;
export const sort = (elements: Element[], sort: Sort, labelID: string) => {
const getValue = {
Time: (element: Element, labelID: string) => getDate(element, labelID).getTime(),
Size: getSize,
SnoozeTime: (element: Element) => getSnoozeDate(element, labelID).getTime(),
}[sort.sort] as any;
const compare = (a: Element, b: Element) => {
let valueA = getValue(a, labelID);
let valueB = getValue(b, labelID);
if (valueA === valueB && sort.sort === 'Time') {
valueA = a.Order || 0;
valueB = b.Order || 0;
}
return sort.desc ? valueB - valueA : valueA - valueB;
};
return [...elements].sort((e1, e2) => compare(e1, e2));
};
export const getCounterMap = (
labels: Label[],
conversationCounters: LabelCount[],
messageCounters: LabelCount[],
mailSettings: MailSettings
) => {
const labelIDs = [...Object.values(MAILBOX_LABEL_IDS), ...labels.map((label) => label.ID || '')];
const conversationCountersMap = toMap(conversationCounters, 'LabelID') as { [labelID: string]: LabelCount };
const messageCountersMap = toMap(messageCounters, 'LabelID') as { [labelID: string]: LabelCount };
return labelIDs.reduce<{ [labelID: string]: LabelCount | undefined }>((acc, labelID) => {
const conversationMode = isConversationMode(labelID, mailSettings);
const countersMap = conversationMode ? conversationCountersMap : messageCountersMap;
acc[labelID] = countersMap[labelID];
return acc;
}, {});
};
export const hasAttachments = (element: Element) =>
isMessage(element) ? messageHasAttachments(element as Message) : conversationHasAttachments(element);
export const getNumAttachments = (element: Element) =>
isMessage(element) ? (element as Message)?.NumAttachments || 0 : conversationNumAttachments(element);
/**
* Starting from the element LabelIDs list, add and remove labels from an event manager event
*/
export const parseLabelIDsInEvent = <T extends Element>(element: T, changes: T & LabelIDsChanges): T => {
const omitted = omit(changes, ['LabelIDsRemoved', 'LabelIDsAdded']);
if (isMessage(element)) {
if (omitted?.LabelIDs) {
return { ...element, ...omitted };
}
const LabelIDs = unique(
diff((element as Message).LabelIDs || [], changes.LabelIDsRemoved || []).concat(changes.LabelIDsAdded || [])
);
return { ...element, ...omitted, LabelIDs };
}
// Conversation don't use LabelIDs even if these properties are still present in update events
// The conversation.Labels object is fully updated each time so we can safely ignore them
return { ...element, ...omitted };
};
export const isSearch = (searchParams: SearchParameters) =>
!!searchParams.address ||
!!searchParams.begin ||
!!searchParams.end ||
!!searchParams.from ||
!!searchParams.keyword ||
!!searchParams.to ||
!!searchParams.wildcard;
export const isFilter = (filter: Filter) => Object.keys(filter).length > 0;
export const hasAttachmentsFilter = (filter?: Filter) => filter?.Attachments === 1;
/**
* Get the IDs of the folder where the element is currently located
*/
export const getCurrentFolderIDs = (element: Element | undefined, customFoldersList: Folder[]): string[] => {
const labelIDs = getLabelIDs(element, undefined);
const standardFolders: { [labelID: string]: boolean } = {
[INBOX]: true,
[TRASH]: true,
[SPAM]: true,
[ARCHIVE]: true,
[SCHEDULED]: true,
[SNOOZED]: true,
};
const customFolders = toMap(customFoldersList, 'ID');
return Object.keys(labelIDs).filter((labelID) => standardFolders[labelID] || customFolders[labelID]) || '';
};
export const getSenders = (element: Element) => {
if (isMessage(element)) {
return [getSender(element as Message)];
}
return conversationGetSenders(element as Conversation);
};
export const getFirstSenderAddress = (element: Element) => {
const senders = getSenders(element);
const [sender] = senders;
const { Address = '' } = sender || {};
return Address;
};
| 3,801
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptionType.js
|
import { c } from 'ttag';
import { MAIL_APP_NAME } from '@proton/shared/lib/constants';
import {
inSigningPeriod,
isAuto,
isDraft,
isExternalEncrypted,
isImported,
isInternalEncrypted,
isSent,
isSentEncrypted,
} from '@proton/shared/lib/mail/messages';
export const I18N = {
pm: [
c('Message encryption status').t`End-to-end encrypted message`,
c('Message encryption status').t`End-to-end encrypted message from verified address`,
c('Message encryption status').t`Sender verification failed`,
],
pgp: [
c('Message encryption status').t`PGP-encrypted message`,
c('Message encryption status').t`PGP-encrypted message from verified address`,
c('Message encryption status').t`Sender verification failed`,
],
clear: [
c('Message encryption status').t`Stored with zero access encryption`,
c('Message encryption status').t`PGP-signed message from verified address`,
c('Message encryption status').t`Sender verification failed`,
],
sentEncrypted: [
c('Message encryption status').t`Sent by you with end-to-end encryption`,
c('Message encryption status').t`Sent by you with end-to-end encryption`,
c('Message encryption status').t`Sender verification failed`,
],
auto: [c('Message encryption status').t`Sent by ${MAIL_APP_NAME} with zero access encryption`],
sentClear: [
c('Message encryption status').t`Stored with zero access encryption`,
c('Message encryption status').t`Stored with zero access encryption`,
c('Message encryption status').t`Sender verification failed`,
],
draft: [c('Message encryption status').t`Encrypted message`],
};
export const getFromType = (message) => {
if (isSentEncrypted(message)) {
return I18N.sentEncrypted;
}
if (isAuto(message)) {
return I18N.auto;
}
if (isSent(message)) {
return I18N.sentClear;
}
if (isDraft(message)) {
return I18N.draft;
}
if (isInternalEncrypted(message)) {
return I18N.pm;
}
if (isExternalEncrypted(message)) {
return I18N.pgp;
}
return I18N.clear;
};
export const getEncryptionType = ({ data: message = {}, verified = 0 }) => {
const encType = getFromType(message);
if (encType.length > verified) {
// Old messages are not signed, so missing sender signatures should be treated like external missing signatures, no warning
if (!inSigningPeriod(message) && isSentEncrypted(message) && !isImported(message)) {
return encType[0];
}
return encType[verified];
}
return encType[0];
};
| 3,802
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptionType.test.ts
|
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { I18N, getEncryptionType, getFromType } from './encryptionType';
describe('getFromType', () => {
it('should be sent encrypted', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_E2E | MESSAGE_FLAGS.FLAG_SENT,
} as Message;
expect(getFromType(message)).toEqual(I18N.sentEncrypted);
});
it('should be auto', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_AUTO,
} as Message;
expect(getFromType(message)).toEqual(I18N.auto);
});
it('should be sent', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_SENT,
} as Message;
expect(getFromType(message)).toEqual(I18N.sentClear);
});
it('should be a draft', () => {
const message = {
Flags: 0,
} as Message;
expect(getFromType(message)).toEqual(I18N.draft);
});
it('should be internal encrypted', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_E2E | MESSAGE_FLAGS.FLAG_INTERNAL | MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getFromType(message)).toEqual(I18N.pm);
});
it('should be external encrypted', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_E2E | MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getFromType(message)).toEqual(I18N.pgp);
});
it('should be clear', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getFromType(message)).toEqual(I18N.clear);
});
});
describe('getEncryptionType', () => {
it('should return the encryption type', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getEncryptionType({ data: message, verified: 1 })).toEqual(I18N.clear[1]);
});
it('should return encryption type for old messages', () => {
const message = {
Time: 0,
Flags: MESSAGE_FLAGS.FLAG_E2E | MESSAGE_FLAGS.FLAG_SENT,
} as Message;
expect(getEncryptionType({ data: message, verified: 2 })).toEqual(I18N.sentEncrypted[0]);
});
it('should return default encryption type when verified is to big', () => {
const message = {
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
} as Message;
expect(getEncryptionType({ data: message, verified: 10 })).toEqual(I18N.clear[0]);
});
});
| 3,803
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/errors.test.ts
|
import { ConversationErrors } from '../logic/conversations/conversationsTypes';
import { MessageErrors, MessageState } from '../logic/messages/messagesTypes';
import { hasError, hasErrorType, isDecryptionError, isNetworkError, pickMessageInfosForSentry } from './errors';
import { createDocument } from './test/message';
describe('isNetworkError', () => {
it('should be a network error', () => {
const error1 = {
name: 'NetworkError',
};
const error2 = {
name: 'OfflineError',
};
const error3 = {
name: 'TimeoutError',
};
expect(isNetworkError(error1)).toBeTruthy();
expect(isNetworkError(error2)).toBeTruthy();
expect(isNetworkError(error3)).toBeTruthy();
});
it('should not be a network error', () => {
const error1 = {};
const error2 = {
name: 'Something else',
};
expect(isNetworkError(error1)).toBeFalsy();
expect(isNetworkError(error2)).toBeFalsy();
});
});
describe('isDecryptionError', () => {
it('should be a decryption error', function () {
const error = {
message: 'Error decrypting something',
};
expect(isDecryptionError(error)).toBeTruthy();
});
it('should not be a decryption error', function () {
const error1 = {
message: 'something Error decrypting something',
};
const error2 = {
message: 'something else',
};
const error3 = {};
expect(isDecryptionError(error1)).toBeFalsy();
expect(isDecryptionError(error2)).toBeFalsy();
expect(isDecryptionError(error3)).toBeFalsy();
});
});
describe('hasError', () => {
it('should have errors', function () {
const messageErrors = {
network: [{ message: 'something failed' }],
} as MessageErrors;
const conversationErrors = {
network: [{ message: 'something failed' }],
} as ConversationErrors;
expect(hasError(messageErrors)).toBeTruthy();
expect(hasError(conversationErrors)).toBeTruthy();
});
it('should not have errors', () => {
const messageErrors1 = {
network: [],
} as MessageErrors;
const messageErrors2 = {} as MessageErrors;
const conversationErrors1 = {
network: [],
} as ConversationErrors;
const conversationErrors2 = {} as ConversationErrors;
expect(hasError(messageErrors1)).toBeFalsy();
expect(hasError(messageErrors2)).toBeFalsy();
expect(hasError(conversationErrors1)).toBeFalsy();
expect(hasError(conversationErrors2)).toBeFalsy();
expect(hasError(undefined)).toBeFalsy();
});
});
describe('hasErrorType', () => {
it('should have error from type network', function () {
const messageErrors = {
network: [{ message: 'something failed' }],
} as MessageErrors;
const conversationErrors = {
network: [{ message: 'something failed' }],
} as ConversationErrors;
expect(hasErrorType(messageErrors, 'network')).toBeTruthy();
expect(hasErrorType(conversationErrors, 'network')).toBeTruthy();
});
it('should not have error from type network', function () {
const messageErrors1 = {
decryption: [{ message: 'something failed' }],
} as MessageErrors;
const messageErrors2 = {} as MessageErrors;
const conversationErrors1 = {
notExist: [{ message: 'something failed' }],
} as ConversationErrors;
const conversationErrors2 = {} as ConversationErrors;
expect(hasErrorType(messageErrors1, 'network')).toBeFalsy();
expect(hasErrorType(messageErrors2, 'network')).toBeFalsy();
expect(hasErrorType(conversationErrors1, 'network')).toBeFalsy();
expect(hasErrorType(conversationErrors2, 'network')).toBeFalsy();
expect(hasErrorType(undefined, 'network')).toBeFalsy();
});
});
describe('pickMessageInfosForSentry', () => {
it('should not send sensitive infos to Sentry', () => {
const message = {
localID: 'localID',
loadRetry: 2,
errors: {
network: [{ message: 'something failed' }],
},
data: {
Subject: 'Mail subject',
ToList: [{ Name: 'Name', Address: 'address@pm.me' }],
},
decryption: {
decryptedBody: 'Message body',
},
messageDocument: {
document: createDocument('Message body'),
},
} as MessageState;
const expected = {
localID: 'localID',
loadRetry: 2,
errors: {
network: [{ message: 'something failed' }],
},
};
expect(pickMessageInfosForSentry(message)).toEqual(expected);
});
});
| 3,804
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/errors.ts
|
import { ConversationErrors } from '../logic/conversations/conversationsTypes';
import { MessageErrors, MessageState } from '../logic/messages/messagesTypes';
/**
* Define wether or not the error comes from a network error
* We have the ApiError type but we can miss some native connection errors
* So (unless proven otherwise) the most reliable is to refer on error names
* Knowing that ApiError also use error names
*/
export const isNetworkError = (error: any) =>
error.name === 'NetworkError' || error.name === 'OfflineError' || error.name === 'TimeoutError';
/**
* It's an error from OpenPGP about decryption
* Most of the time decryption errors are user key management pbs we have to ignore
*/
export const isDecryptionError = (error: any) => error.message && error.message.startsWith('Error decrypting');
export const hasError = (errors: MessageErrors | ConversationErrors | undefined = {}) =>
!!Object.values(errors).flat().length;
export const hasErrorType = (
errors: MessageErrors | ConversationErrors | undefined = {},
errorType: keyof MessageErrors | keyof ConversationErrors
) => ((errors as any)?.[errorType]?.length || 0) > 0;
export const pickMessageInfosForSentry = ({ localID, loadRetry, errors }: MessageState) => {
// We don't want to send everything to Sentry, we need to remove sensitive information
// e.g. messageDocument, decryption, errors.decryption, etc...
return {
localID,
loadRetry,
errors: {
network: errors?.network,
processing: errors?.processing,
signature: errors?.signature,
unknown: errors?.unknown,
},
};
};
| 3,805
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/expiration.test.ts
|
import { add, addDays, differenceInMinutes, getUnixTime, sub } from 'date-fns';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { UserModel } from '@proton/shared/lib/interfaces';
import { MessageState } from '../logic/messages/messagesTypes';
import { canSetExpiration, getExpirationTime, getMinExpirationTime, isExpired } from './expiration';
describe('canSetExpiration', () => {
const messageState = {
data: {
LabelIDs: ['label1', 'label2'],
},
} as MessageState;
const incorrectMessageState = {
data: {
LabelIDs: [MAILBOX_LABEL_IDS.SPAM, MAILBOX_LABEL_IDS.TRASH],
},
} as MessageState;
it('should return false if feature flag is false', () => {
expect(canSetExpiration(false, { hasPaidMail: true } as UserModel, messageState)).toBe(false);
});
it('should return false if user is free', () => {
expect(canSetExpiration(true, { isFree: true } as UserModel, messageState)).toBe(false);
});
it('should return false if user is paid but not paid mail', () => {
expect(canSetExpiration(true, { isPaid: true, hasPaidMail: false } as UserModel, messageState)).toBe(false);
});
it('should return true if feature flag is true and user is paid mail', () => {
expect(canSetExpiration(true, { hasPaidMail: true } as UserModel, messageState)).toBe(true);
});
it('should return false if labelIDs contains spam or trash', () => {
expect(canSetExpiration(true, { hasPaidMail: true } as UserModel, incorrectMessageState)).toBe(false);
});
});
describe('getExpirationTime', () => {
it('should return null if days is undefined', () => {
expect(getExpirationTime(undefined)).toBe(null);
});
it('should return a Unix timestamp if days is > 0', () => {
expect(getExpirationTime(addDays(new Date(), 1))).toBeGreaterThan(0);
});
});
describe('isExpired', () => {
it('should return false', () => {
expect(isExpired({ ExpirationTime: getUnixTime(add(new Date(), { hours: 1 })) })).toBeFalsy();
});
describe('when message expiration is before now', () => {
it('should return true', () => {
expect(isExpired({ ExpirationTime: getUnixTime(sub(new Date(), { hours: 1 })) })).toBeTruthy();
});
});
describe('when date is provided', () => {
const timestamp = getUnixTime(new Date(2023, 7, 27, 0, 0, 0, 0));
describe('when message expiration is after provided date', () => {
it('should return false', () => {
expect(
isExpired({ ExpirationTime: getUnixTime(sub(new Date(), { hours: 1 })) }, timestamp)
).toBeFalsy();
});
});
describe('when message expiration is before provided date', () => {
it('should return true', () => {
expect(
isExpired({ ExpirationTime: getUnixTime(sub(new Date(timestamp), { hours: 1 })) }, timestamp)
).toBeTruthy();
});
});
});
});
describe('getMinExpirationTime', () => {
it('should return undefined if date is not today', () => {
expect(getMinExpirationTime(addDays(new Date(), 1))).toBe(undefined);
});
it('should return a Date if date is today', () => {
expect(getMinExpirationTime(new Date())).toBeInstanceOf(Date);
});
it('should return a Date with minutes set to 0 or 30', () => {
const date = getMinExpirationTime(new Date());
const minutes = date?.getMinutes();
expect(minutes === 0 || minutes === 30).toBe(true);
});
it('should return a older next interval from now with a difference of at least 15 minutes', () => {
const now = new Date();
const interval = getMinExpirationTime(now);
if (!interval) {
throw new Error('Interval is undefined');
}
expect(interval > now).toBe(true);
expect(differenceInMinutes(interval, now)).toBeGreaterThanOrEqual(15);
});
});
| 3,806
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/expiration.ts
|
import { addMinutes, differenceInMinutes, getUnixTime, isToday } from 'date-fns';
import { serverTime } from 'pmcrypto';
import { UserModel } from '@proton/shared/lib/interfaces';
import { isFrozenExpiration } from '@proton/shared/lib/mail/messages';
import { MessageState } from '../logic/messages/messagesTypes';
import { isAllowedAutoDeleteLabelID } from './autoDelete';
export const canSetExpiration = (featureFlagValue: boolean, user: UserModel, messageState?: MessageState) => {
const hasFrozenExpiration = isFrozenExpiration(messageState?.data);
const { LabelIDs = [] } = messageState?.data || {};
if (hasFrozenExpiration) {
return false;
}
if (!featureFlagValue) {
return false;
}
if (!user.hasPaidMail) {
return false;
}
if (!LabelIDs.length || LabelIDs.some((labelID) => isAllowedAutoDeleteLabelID(labelID))) {
return false;
}
return true;
};
export const getExpirationTime = (date?: Date) => {
return date ? getUnixTime(date) : null;
};
export const isExpired = <T extends { ExpirationTime?: number }>(element: T, timestamp?: number) => {
const { ExpirationTime } = element;
return Boolean(ExpirationTime && ExpirationTime < getUnixTime(timestamp ?? (+serverTime())));
};
// Return the correct min interval to display in the time input for expiration (self-destruct)
export const getMinExpirationTime = (date: Date) => {
// If date is not today, there is no min time because we want to display all intervals
if (!isToday(date)) {
return undefined;
}
// Date that will be used for intervals, we don't want it to have minutes or seconds set in intervals
// Intervals needs to be XX:00 AM/PM or XX:30 AM/PM
const nowForInterval = new Date();
nowForInterval.setMinutes(0, 0);
// Current date used to get the correct min interval to display to the user
const now = new Date();
// Calculate intervals
// If it's 9:50 AM/PM, we should get
// 9:30, 10:00, 10:30
const nextIntervals = Array.from(Array(3)).map((_, i) => addMinutes(nowForInterval, 30 * (i + 1)));
return nextIntervals.find((interval) => interval > now && differenceInMinutes(interval, now) >= 15);
};
| 3,807
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/labels.test.ts
|
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { MessageWithOptionalBody } from '../logic/messages/messagesTypes';
import { Conversation } from '../models/conversation';
import {
applyLabelChangesOnConversation,
applyLabelChangesOnMessage,
applyLabelChangesOnOneMessageOfAConversation,
canMoveAll,
shouldDisplayTotal,
} from './labels';
const { INBOX, TRASH, SPAM, ARCHIVE, SENT, ALL_SENT, DRAFTS, ALL_DRAFTS, SCHEDULED, ALL_MAIL } = MAILBOX_LABEL_IDS;
const labelID = 'LabelID';
describe('labels', () => {
describe('applyLabelChangesOnMessage', () => {
it('should remove a label from a message', () => {
const input = {
LabelIDs: [labelID],
} as unknown as MessageWithOptionalBody;
const changes = { [labelID]: false };
const message = applyLabelChangesOnMessage(input, changes);
expect(message.LabelIDs?.length).toBe(0);
});
it('should add a label for a message', () => {
const input = {
LabelIDs: [],
} as unknown as MessageWithOptionalBody;
const changes = { [labelID]: true };
const message = applyLabelChangesOnMessage(input, changes);
expect(message.LabelIDs?.length).toBe(1);
expect(message.LabelIDs[0]).toBe(labelID);
});
});
describe('applyLabelChangesOnConversation', () => {
it('should remove a label from a conversation', () => {
const input = {
Labels: [{ ID: labelID, ContextNumMessages: 5 }],
} as Conversation;
const changes = { [labelID]: false };
const conversation = applyLabelChangesOnConversation(input, changes);
expect(conversation.Labels?.length).toBe(0);
});
it('should add a label for a conversation', () => {
const input = {
ID: 'conversationID',
Labels: [],
} as Conversation;
const changes = { [labelID]: true };
const conversation = applyLabelChangesOnConversation(input, changes);
expect(conversation.Labels?.length).toBe(1);
});
});
describe('applyLabelChangesOnOneMessageOfAConversation', () => {
it('should remove a label from a conversation when remove the label on the last message having it', () => {
const input = {
Labels: [{ ID: labelID, ContextNumMessages: 1 }],
} as Conversation;
const changes = { [labelID]: false };
const { updatedConversation } = applyLabelChangesOnOneMessageOfAConversation(input, changes);
expect(updatedConversation.Labels?.length).toBe(0);
});
it('should keep a label from a conversation when remove the label on a message but not the last having it', () => {
const numMessages = 3;
const input = {
Labels: [{ ID: labelID, ContextNumMessages: numMessages }],
} as Conversation;
const changes = { [labelID]: false };
const { updatedConversation } = applyLabelChangesOnOneMessageOfAConversation(input, changes);
expect(updatedConversation.Labels?.length).toBe(1);
expect(updatedConversation.Labels?.[0].ContextNumMessages).toBe(numMessages - 1);
});
it('should add a label to a conversation when adding the label to the first message having it', () => {
const input = {
ID: 'conversationID',
Labels: [],
} as Conversation;
const changes = { [labelID]: true };
const { updatedConversation } = applyLabelChangesOnOneMessageOfAConversation(input, changes);
expect(updatedConversation.Labels?.length).toBe(1);
expect(updatedConversation.Labels?.[0].ContextNumMessages).toBe(1);
});
it('should keep a label to a conversation when adding the label to a message but not the first having it', () => {
const numMessages = 3;
const input = {
Labels: [{ ID: labelID, ContextNumMessages: numMessages }],
} as Conversation;
const changes = { [labelID]: true };
const { updatedConversation } = applyLabelChangesOnOneMessageOfAConversation(input, changes);
expect(updatedConversation.Labels?.length).toBe(1);
expect(updatedConversation.Labels?.[0].ContextNumMessages).toBe(numMessages + 1);
});
});
describe('shouldDisplayTotal', () => {
it.each`
label | expectedShouldDisplayTotal
${SCHEDULED} | ${true}
${INBOX} | ${false}
${TRASH} | ${false}
${SPAM} | ${false}
${ARCHIVE} | ${false}
${SENT} | ${false}
${ALL_SENT} | ${false}
${DRAFTS} | ${false}
${ALL_DRAFTS} | ${false}
`(
'should display the total: [$expectedShouldDisplayTotal] in [$label]',
async ({ label, expectedShouldDisplayTotal }) => {
const needsToDisplayTotal = shouldDisplayTotal(label);
expect(expectedShouldDisplayTotal).toEqual(needsToDisplayTotal);
}
);
});
describe('canMoveAll', () => {
it('should not be possible to move all from some locations', () => {
const locations = [ALL_MAIL, SCHEDULED, ALL_DRAFTS, ALL_SENT];
locations.forEach((location) => {
expect(canMoveAll(location, TRASH, ['elementID'], [], false));
});
});
it('should not be possible to move all when no elements in location', () => {
expect(canMoveAll(SENT, TRASH, [], [], false));
});
it('should not be possible to move all when some elements are selected', () => {
expect(canMoveAll(SENT, TRASH, ['elementID'], ['elementID'], false));
});
it('should be possible to move all', () => {
expect(canMoveAll(SENT, TRASH, ['elementID'], [], false));
});
});
});
| 3,808
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/labels.ts
|
import { c } from 'ttag';
import { IconName } from '@proton/components';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { hasBit } from '@proton/shared/lib/helpers/bitset';
import { toMap } from '@proton/shared/lib/helpers/object';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { Folder } from '@proton/shared/lib/interfaces/Folder';
import { Label } from '@proton/shared/lib/interfaces/Label';
import { SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings';
import { LABELS_AUTO_READ, LABELS_UNMODIFIABLE_BY_USER, LABEL_IDS_TO_HUMAN } from '../constants';
import { MessageWithOptionalBody } from '../logic/messages/messagesTypes';
import { Conversation } from '../models/conversation';
import { Element } from '../models/element';
import { getLabelIDs } from './elements';
const {
INBOX,
TRASH,
SPAM,
ARCHIVE,
SENT,
DRAFTS,
ALL_SENT,
ALL_DRAFTS,
SCHEDULED,
OUTBOX,
STARRED,
ALL_MAIL,
SNOOZED,
ALMOST_ALL_MAIL,
} = MAILBOX_LABEL_IDS;
const DEFAULT_FOLDERS = [INBOX, TRASH, SPAM, ARCHIVE, SENT, DRAFTS, SCHEDULED, OUTBOX];
export type LabelChanges = { [labelID: string]: boolean };
export interface FolderInfo {
icon: IconName;
name: string;
to: string;
color?: string;
parentID?: string | number;
}
interface FolderMap {
[id: string]: FolderInfo;
}
const alwaysMessageLabels = [DRAFTS, ALL_DRAFTS, SENT, ALL_SENT];
export const getHumanLabelID = (labelID: string) => LABEL_IDS_TO_HUMAN[labelID as MAILBOX_LABEL_IDS] || labelID;
export const isCustomLabelOrFolder = (labelID: string) =>
!Object.values(MAILBOX_LABEL_IDS).includes(labelID as MAILBOX_LABEL_IDS);
export const isAlwaysMessageLabels = (labelID: string) => alwaysMessageLabels.includes(labelID as MAILBOX_LABEL_IDS);
export const labelIncludes = (labelID: string, ...labels: (MAILBOX_LABEL_IDS | string)[]) =>
labels.includes(labelID as MAILBOX_LABEL_IDS);
export const isCustomLabel = (labelID: string, labels: Label[] = []) => labels.some((label) => label.ID === labelID);
export const isLabel = (labelID: string, labels: Label[] = []) =>
labelIncludes(labelID, STARRED) || isCustomLabel(labelID, labels);
export const isCustomFolder = (labelID: string, folders: Folder[] = []) =>
folders.some((folder) => folder.ID === labelID);
export const getStandardFolders = (): FolderMap => ({
[INBOX]: {
icon: 'inbox',
name: c('Link').t`Inbox`,
to: '/inbox',
},
[TRASH]: {
icon: 'trash',
name: c('Link').t`Trash`,
to: '/trash',
},
[SPAM]: {
icon: 'fire',
name: c('Link').t`Spam`,
to: '/spam',
},
[ARCHIVE]: {
icon: 'archive-box',
name: c('Link').t`Archive`,
to: '/archive',
},
[SENT]: {
icon: 'paper-plane-horizontal',
name: c('Link').t`Sent`,
to: `/${LABEL_IDS_TO_HUMAN[SENT]}`,
},
[ALL_SENT]: {
icon: 'paper-plane-horizontal',
name: c('Link').t`Sent`,
to: `/${LABEL_IDS_TO_HUMAN[ALL_SENT]}`,
},
[DRAFTS]: {
icon: 'file-lines',
name: c('Link').t`Drafts`,
to: `/${LABEL_IDS_TO_HUMAN[DRAFTS]}`,
},
[ALL_DRAFTS]: {
icon: 'file-lines',
name: c('Link').t`Drafts`,
to: `/${LABEL_IDS_TO_HUMAN[ALL_DRAFTS]}`,
},
[SCHEDULED]: {
icon: 'paper-plane-horizontal-clock',
name: c('Link').t`Scheduled`,
to: `/${LABEL_IDS_TO_HUMAN[SCHEDULED]}`,
},
[STARRED]: {
icon: 'star',
name: c('Link').t`Starred`,
to: `/${LABEL_IDS_TO_HUMAN[STARRED]}`,
},
[SNOOZED]: {
icon: 'clock',
name: c('Link').t`Snooze`,
to: `/${LABEL_IDS_TO_HUMAN[SNOOZED]}`,
},
[ALL_MAIL]: {
icon: 'envelopes',
name: c('Link').t`All mail`,
to: `/${LABEL_IDS_TO_HUMAN[ALL_MAIL]}`,
},
[ALMOST_ALL_MAIL]: {
icon: 'envelopes',
name: c('Link').t`All mail`,
to: `/${LABEL_IDS_TO_HUMAN[ALMOST_ALL_MAIL]}`,
},
// [OUTBOX]: {
// icon: 'inbox-out',
// name: c('Mailbox').t`Outbox`,
// to: `/${LABEL_IDS_TO_HUMAN[OUTBOX]}`,
// },
});
const STANDARD_FOLDERS = getStandardFolders();
export const getI18nLabelID = (labelID: string) =>
STANDARD_FOLDERS[labelID as MAILBOX_LABEL_IDS]?.name || getHumanLabelID(labelID);
export const getLabelName = (labelID: string, labels: Label[] = [], folders: Folder[] = []): string => {
if (labelID in LABEL_IDS_TO_HUMAN) {
return getI18nLabelID(labelID);
}
const labelsMap = toMap(labels, 'ID');
if (labelID in labelsMap) {
return labelsMap[labelID]?.Name || labelID;
}
const foldersMap = toMap(folders, 'ID');
if (labelID in foldersMap) {
return foldersMap[labelID]?.Name || labelID;
}
return labelID;
};
export const getCurrentFolders = (
element: Element | undefined,
labelID: string,
customFoldersList: Folder[],
mailSettings: MailSettings
): FolderInfo[] => {
const { ShowMoved } = mailSettings;
const labelIDs = Object.keys(getLabelIDs(element, labelID));
const standardFolders = getStandardFolders();
const customFolders = toMap(customFoldersList, 'ID');
return labelIDs
.filter((labelID) => {
if ([SENT, ALL_SENT].includes(labelID as MAILBOX_LABEL_IDS)) {
return (hasBit(ShowMoved, SHOW_MOVED.SENT) ? ALL_SENT : SENT) === labelID;
}
if ([DRAFTS, ALL_DRAFTS].includes(labelID as MAILBOX_LABEL_IDS)) {
return (hasBit(ShowMoved, SHOW_MOVED.DRAFTS) ? ALL_DRAFTS : DRAFTS) === labelID;
}
// We don't want to show the All mail folder in the details
if ([ALL_MAIL, ALMOST_ALL_MAIL].includes(labelID as MAILBOX_LABEL_IDS)) {
return false;
}
return true;
})
.filter((labelID) => standardFolders[labelID] || customFolders[labelID])
.map((labelID) => {
if (standardFolders[labelID]) {
return standardFolders[labelID];
}
const folder = customFolders[labelID];
return {
icon: 'folder',
name: folder?.Name,
to: `/${folder?.ID}`,
color: folder?.Color,
parentID: folder?.ParentID,
};
});
};
export const getCurrentFolderID = (labelIDs: string[] = [], customFoldersList: Folder[] = []): string => {
const allFolderIDs = [...DEFAULT_FOLDERS, ...customFoldersList.map(({ ID }) => ID)];
return labelIDs.find((labeID) => allFolderIDs.includes(labeID)) || '';
};
export const getFolderName = (labelID: string, customFoldersList: Folder[] = []): string => {
const standardFolders = getStandardFolders();
if (standardFolders[labelID]) {
return standardFolders[labelID].name;
}
const { Name = '' } = customFoldersList.find(({ ID }) => ID === labelID) || {};
return Name;
};
export const isAutoRead = (labelID: MAILBOX_LABEL_IDS | string) =>
LABELS_AUTO_READ.includes(labelID as MAILBOX_LABEL_IDS);
export const isUnmodifiableByUser = (labelID: MAILBOX_LABEL_IDS | string) =>
LABELS_UNMODIFIABLE_BY_USER.includes(labelID as MAILBOX_LABEL_IDS);
export interface UnreadStatus {
id: string;
unread: number;
}
export const applyLabelChangesOnMessage = <T>(
message: MessageWithOptionalBody & T,
changes: LabelChanges,
unreadStatuses?: UnreadStatus[]
): MessageWithOptionalBody & T => {
const { LabelIDs: inputLabelIDs } = message;
const LabelIDs = [...inputLabelIDs];
Object.keys(changes).forEach((labelID) => {
const index = LabelIDs.findIndex((existingLabelID) => existingLabelID === labelID);
if (changes[labelID]) {
if (index === -1) {
LabelIDs.push(labelID);
}
} else if (index >= 0) {
LabelIDs.splice(index, 1);
}
});
if (unreadStatuses) {
const elementUnreadStatus = unreadStatuses.find((element) => element.id === message.ID)?.unread;
if (elementUnreadStatus) {
return { ...message, LabelIDs, Unread: elementUnreadStatus };
}
}
return { ...message, LabelIDs };
};
export const applyLabelChangesOnConversation = (
conversation: Conversation,
changes: LabelChanges,
unreadStatuses?: UnreadStatus[]
): Conversation => {
let Time = conversation.Time;
const Labels = [...(conversation.Labels || [])];
Object.keys(changes).forEach((labelID) => {
const index = Labels.findIndex((existingLabel) => existingLabel.ID === labelID);
if (changes[labelID]) {
if (index === -1) {
Labels.push({
ID: labelID,
ContextNumMessages: conversation.NumMessages || 1,
});
} else {
Labels[index] = {
...Labels[index],
ContextNumMessages: conversation.NumMessages || 1,
};
}
} else if (index >= 0) {
// When the conversation has been received through the event manager it will not have a Time field
// By removing the label, we are losing the context time associated
// If we rollback that change, both label time and fallback on conversation will be missing
// By filling the conversation time at label removal, we ensure there will be a time on rollback
if (Time === undefined) {
Time = Labels[index].ContextTime;
}
Labels.splice(index, 1);
}
});
if (unreadStatuses) {
const elementUnreadStatus = unreadStatuses.find((element) => element.id === conversation.ID)?.unread;
if (elementUnreadStatus) {
return { ...conversation, Time, Labels, NumUnread: elementUnreadStatus };
}
}
return { ...conversation, Time, Labels };
};
export const applyLabelChangesOnOneMessageOfAConversation = (
conversation: Conversation,
changes: LabelChanges
): { updatedConversation: Conversation; conversationChanges: LabelChanges } => {
let Time = conversation.Time;
const Labels = [...(conversation.Labels || [])];
const conversationChanges: LabelChanges = {};
Object.keys(changes).forEach((labelID) => {
const index = Labels.findIndex((existingLabel) => existingLabel.ID === labelID);
const hasLabel = index >= 0;
const numMessages = Labels?.[index]?.ContextNumMessages || 0;
if (changes[labelID]) {
if (hasLabel) {
Labels[index] = { ...Labels[index], ContextNumMessages: numMessages + 1 };
} else {
Labels.push({ ID: labelID, ContextNumMessages: 1 });
conversationChanges[labelID] = true;
}
} else if (hasLabel) {
if (numMessages <= 1) {
// When the conversation has been received through the event manager it will not have a Time field
// By removing the label, we are losing the context time associated
// If we rollback that change, both label time and fallback on conversation will be missing
// By filling the conversation time at label removal, we ensure there will be a time on rollback
if (Time === undefined) {
Time = Labels[index].ContextTime;
}
Labels.splice(index, 1);
conversationChanges[labelID] = false;
} else {
Labels[index] = { ...Labels[index], ContextNumMessages: numMessages - 1 };
}
}
});
return { updatedConversation: { ...conversation, Time, Labels }, conversationChanges };
};
// For some locations, we want to display the total number of messages instead of the number of unreads (e.g. Scheduled folder)
export const shouldDisplayTotal = (labelID: string) => {
const needsDisplayTotalLabels = [SCHEDULED, SNOOZED];
return needsDisplayTotalLabels.includes(labelID as MAILBOX_LABEL_IDS);
};
export const canMoveAll = (
currentLabelID: string,
targetLabelID: string,
elementIDs: string[],
selectedIDs: string[],
isSearch: boolean
) => {
// We also need to hide move all actions in ALL_DRAFTS and ALL_SENT location because the goal of this setting
// is to keep the message in DRAFTS and SENT locations all the time.
return (
!labelIncludes(currentLabelID, targetLabelID, ALL_MAIL, SCHEDULED, ALL_DRAFTS, ALL_SENT) &&
elementIDs.length > 0 &&
selectedIDs.length === 0 &&
!isSearch
);
};
| 3,809
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/mail.test.ts
|
import { combineHeaders, splitMail } from './mail';
describe('combineHeaders', () => {
it('should combine headers', async () => {
const baseHeader = `Return-Path: <address1@pm.me>
X-Original-To: address2@pm.me
Delivered-To: address1@pm.me
Content-Type: text/html
Date: Mon, 6 Feb 2023 16:47:37 +0100`;
const extraHeaders = `Content-Type: multipart/mixed;boundary=---------------------something`;
const expected = `Return-Path: <address1@pm.me>
X-Original-To: address2@pm.me
Delivered-To: address1@pm.me
Content-Type: multipart/mixed;boundary=---------------------something
Date: Mon, 6 Feb 2023 16:47:37 +0100`;
const result = await combineHeaders(baseHeader, extraHeaders);
expect(result).toEqual(expected);
});
});
describe('splitMail', () => {
it('should split the mail into header and body', function () {
const mailHeaders = `Content-Type: multipart/mixed;boundary=---------------------something1`;
const mailBody = `-----------------------something1
Content-Type: multipart/related;boundary=---------------------something2
-----------------------something2
Content-Type: text/html;charset=utf-8
Content-Transfer-Encoding: base64
messageContenthlYWQ+CgogICAgPG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBlIiBjb250
ZW50PSJ0ZXh0L2h0bWw7IGNoYXJzZXQ9VVRGLTgiPgogIDwvaGVhZD4KICA8Ym9keT4KICAgIDxw
PjxhIGhyZWY9Im1haWx0bzpTbGFjawombHQ7ZWItVDAzRFA0QzRDLVU3VjRaRlFLQi1ibXVzNmxw
M3dzamVwajNzbjJ3dWt1ZHY2dUBzbGFjay1tYWlsLmNvbSZndDs/c3ViamVjdD1SZXBseQogICAg
ICAgIHRvIFZvam8gSWxpZXZza2kiPlJlcGx5PC9hPgogICAgICA8YSBocmVmPSJtYWlsdG86Uk9S
TwogICAgICAgICZsdDtyb3JvdGVzdDVAcHJvdG9ubWFpbC5jb20mZ3Q7P3N1YmplY3Q9UmVwbHkg
dG8gcm9ybyI+UmVwbHk8L2E+PC9wPgogIDwvYm9keT4KPC9odG1sPgo=
-----------------------something2--
-----------------------something1--`;
const mailString = `${mailHeaders}
${mailBody}`;
const { headers, body } = splitMail(mailString);
expect(headers).toEqual(mailHeaders);
expect(body).toEqual(mailBody);
});
});
| 3,810
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/mail.ts
|
// TODO: drop pmcrypto import, see https://jira.protontech.ch/projects/CRYPTO/issues/CRYPTO-101
// eslint-disable-next-line no-restricted-imports
import { parseMail } from 'pmcrypto/lib/message/parseMail';
/**
* Overwrites the headers in baseHeader by the headers defined in extraHeaders.
*/
export const combineHeaders = async (baseHeader: string, extraHeaders: string) => {
const { headers: parsedExtras } = await parseMail(extraHeaders);
const extraHeaderKeys = Object.keys(parsedExtras);
return extraHeaderKeys.reduce((inputHeader, key) => {
const capsKey = key.replace(/(^|-)./g, (letter) => letter.toUpperCase());
const values = parsedExtras[key];
const headerLine = values.map((val) => `${capsKey}: ${val}`).join('\r\n');
const outputHeader = inputHeader.replace(new RegExp(`^${key}:.*(?=$[^ ])`, 'im'), headerLine);
if (outputHeader.indexOf(capsKey) === -1) {
return `${inputHeader + headerLine}\r\n`;
}
return outputHeader;
}, baseHeader);
};
/**
* Splits the mail into header and body.
*/
export const splitMail = (mail: string) => {
// double new line separates message body and the headers
const headersEnd = mail.search(/\r?\n\r?\n/);
if (headersEnd === -1) {
return { headers: mail, body: '' };
}
const headers = mail.substring(0, headersEnd);
// remove leading newlines
const body = mail.substring(headersEnd).trimStart();
return { headers, body };
};
| 3,811
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/mailSettings.test.ts
|
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings';
import { isConversationMode } from './mailSettings';
describe('mailSettings', () => {
describe('isConversationMode', () => {
const emptyLocation = { pathname: '', search: '', state: {}, hash: '' };
const locationWithParameters = { pathname: '', search: '', state: {}, hash: '#keyword=panda' };
it('should be false if labelID is single only', () => {
expect(isConversationMode(MAILBOX_LABEL_IDS.ALL_DRAFTS, { ViewMode: VIEW_MODE.GROUP }, emptyLocation)).toBe(
false
);
});
it('should be false if mail settings is single', () => {
expect(
isConversationMode(MAILBOX_LABEL_IDS.ALL_DRAFTS, { ViewMode: VIEW_MODE.SINGLE }, emptyLocation)
).toBe(false);
});
it('should be true if mail settings is group and label is not single only', () => {
expect(isConversationMode(MAILBOX_LABEL_IDS.INBOX, { ViewMode: VIEW_MODE.GROUP }, emptyLocation)).toBe(
true
);
});
it('should be false if search parameters are defined', () => {
expect(
isConversationMode(MAILBOX_LABEL_IDS.INBOX, { ViewMode: VIEW_MODE.GROUP }, locationWithParameters)
).toBe(false);
});
});
});
| 3,812
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/mailSettings.ts
|
import { Location } from 'history';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { VIEW_LAYOUT, VIEW_MODE } from '@proton/shared/lib/mail/mailSettings';
import { isSearch } from './elements';
import { isAlwaysMessageLabels } from './labels';
import { extractSearchParameters } from './mailboxUrl';
export const isColumnMode = ({ ViewLayout = VIEW_LAYOUT.COLUMN }: Partial<MailSettings> = {}) =>
ViewLayout === VIEW_LAYOUT.COLUMN;
export const isConversationMode = (
labelID = '',
{ ViewMode = VIEW_MODE.GROUP }: Partial<MailSettings> = {},
location?: Location
) => {
const searchParams = location ? extractSearchParameters(location) : {};
return !isAlwaysMessageLabels(labelID) && ViewMode === VIEW_MODE.GROUP && !isSearch(searchParams);
};
| 3,813
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/mailboxUrl.ts
|
import { generatePath, match, matchPath } from 'react-router';
import { Location } from 'history';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { changeSearchParams, getSearchParams } from '@proton/shared/lib/helpers/url';
import { isNumber } from '@proton/shared/lib/helpers/validators';
import { MAIN_ROUTE_PATH } from '../constants';
import { Filter, SearchParameters, Sort } from '../models/tools';
import { getHumanLabelID } from './labels';
// No interface to comply with generatePath argument type
export type MailUrlParams = {
labelID: string;
elementID?: string;
messageID?: string;
};
export const getUrlPathname = (params: MailUrlParams) =>
generatePath(MAIN_ROUTE_PATH, {
...params,
// The as any is needed du to a bug into ExtractRouteParams inference which takes the `?` in the param name
// Remove this once fixed
labelID: getHumanLabelID(params.labelID),
} as any);
export const setParamsInLocation = (location: Location, params: MailUrlParams): Location => ({
...location,
pathname: getUrlPathname(params),
});
export const setParamsInUrl = (location: Location, params: MailUrlParams): string =>
getUrlPathname(params) + location.search;
export const getParamsFromPathname = (pathname: string): match<MailUrlParams> =>
matchPath(pathname, { path: MAIN_ROUTE_PATH }) as match<MailUrlParams>;
const stringToPage = (string: string | undefined): number => {
if (string === undefined) {
return 0;
}
const pageNumber = parseInt(string, 10);
if (!Number.isNaN(pageNumber)) {
return pageNumber - 1;
}
return 0;
};
const stringToSort = (string: string | undefined, labelID?: string): Sort => {
const isScheduledLabel = labelID && labelID === MAILBOX_LABEL_IDS.SCHEDULED;
switch (string) {
case '-size':
return { sort: 'Size', desc: true };
case 'size':
return { sort: 'Size', desc: false };
case 'date':
return { sort: 'Time', desc: !!isScheduledLabel };
default:
return { sort: 'Time', desc: !isScheduledLabel };
}
};
const stringToInt = (string: string | undefined): number | undefined => {
if (string === undefined) {
return undefined;
}
return isNumber(string) ? parseInt(string, 10) : undefined;
};
export const sortToString = (sort: Sort): string | undefined =>
sort.sort === 'Time' ? (sort.desc ? undefined : 'date') : sort.desc ? '-size' : 'size';
const stringToFilter = (string: string | undefined): Filter => {
switch (string) {
case 'read':
return { Unread: 0 };
case 'unread':
return { Unread: 1 };
case 'has-file':
return { Attachments: 1 };
default:
return {};
}
};
type FilterStatus = 'has-file' | 'unread' | 'read';
export const filterToString = (filter: Filter): FilterStatus | undefined => {
if (filter.Attachments === 1) {
return 'has-file';
}
if (filter.Unread === 1) {
return 'unread';
}
if (filter.Unread === 0) {
return 'read';
}
return undefined;
};
export const keywordToString = (keyword: string): string | undefined => {
const trimmed = keyword.trim();
return trimmed || undefined;
};
export const pageFromUrl = (location: Location) => stringToPage(getSearchParams(location.hash).page);
export const sortFromUrl = (location: Location, labelID?: string) =>
stringToSort(getSearchParams(location.hash).sort, labelID);
export const filterFromUrl = (location: Location) => stringToFilter(getSearchParams(location.hash).filter);
export const extractSearchParameters = (location: Location): SearchParameters => {
const { address, from, to, keyword, begin, end, wildcard } = getSearchParams(location.hash);
return {
address,
from,
to,
keyword,
begin: stringToInt(begin),
end: stringToInt(end),
wildcard: stringToInt(wildcard),
};
};
export const setPageInUrl = (location: Location, page: number) =>
changeSearchParams(location.pathname, location.hash, { page: page === 0 ? undefined : String(page + 1) });
export const setSortInUrl = (location: Location, sort: Sort) =>
changeSearchParams(location.pathname, location.hash, { page: undefined, sort: sortToString(sort) });
export const setFilterInUrl = (location: Location, filter: Filter) =>
changeSearchParams(location.pathname, location.hash, { page: undefined, filter: filterToString(filter) });
export const setKeywordInUrl = (location: Location, keyword: string) =>
changeSearchParams(location.pathname, location.hash, { page: undefined, keyword: keywordToString(keyword) });
| 3,814
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/moveToFolder.test.ts
|
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Label, MailSettings } from '@proton/shared/lib/interfaces';
import { SPAM_ACTION } from '@proton/shared/lib/mail/mailSettings';
import { addApiMock, apiMock } from '@proton/testing/lib/api';
import {
askToUnsubscribe,
getNotificationTextMoved,
getNotificationTextUnauthorized,
searchForScheduled,
} from '../helpers/moveToFolder';
import { Element } from '../models/element';
const { SPAM, TRASH, SENT, ALL_SENT, DRAFTS, ALL_DRAFTS, INBOX, SCHEDULED } = MAILBOX_LABEL_IDS;
describe('moveToFolder', () => {
describe('getNotificationTextMoved', () => {
it.each`
folderID | isMessage | elementsCount | messagesNotAuthorizedToMove | folderName | fromLabelID | expectedText
${SPAM} | ${true} | ${1} | ${1} | ${`Spam`} | ${undefined} | ${`Message moved to spam and sender added to your spam list.`}
${SPAM} | ${true} | ${2} | ${0} | ${`Spam`} | ${undefined} | ${`2 messages moved to spam and senders added to your spam list.`}
${SPAM} | ${true} | ${2} | ${1} | ${`Spam`} | ${undefined} | ${`2 messages moved to spam and senders added to your spam list. 1 message could not be moved.`}
${SPAM} | ${false} | ${1} | ${1} | ${`Spam`} | ${undefined} | ${`Conversation moved to spam and sender added to your spam list.`}
${SPAM} | ${false} | ${2} | ${1} | ${`Spam`} | ${undefined} | ${`2 conversations moved to spam and senders added to your spam list.`}
${INBOX} | ${true} | ${1} | ${1} | ${`Inbox`} | ${SPAM} | ${`Message moved to Inbox and sender added to your not spam list.`}
${INBOX} | ${true} | ${2} | ${0} | ${`Inbox`} | ${SPAM} | ${`2 messages moved to Inbox and senders added to your not spam list.`}
${INBOX} | ${true} | ${2} | ${1} | ${`Inbox`} | ${SPAM} | ${`2 messages moved to Inbox and senders added to your not spam list. 1 message could not be moved.`}
${INBOX} | ${false} | ${1} | ${1} | ${`Inbox`} | ${SPAM} | ${`Conversation moved to Inbox and sender added to your not spam list.`}
${INBOX} | ${false} | ${2} | ${1} | ${`Inbox`} | ${SPAM} | ${`2 conversations moved to Inbox and senders added to your not spam list.`}
${TRASH} | ${true} | ${1} | ${1} | ${`Trash`} | ${INBOX} | ${`Message moved to Trash.`}
${TRASH} | ${true} | ${2} | ${0} | ${`Trash`} | ${INBOX} | ${`2 messages moved to Trash.`}
${TRASH} | ${true} | ${2} | ${1} | ${`Trash`} | ${INBOX} | ${`2 messages moved to Trash. 1 message could not be moved.`}
${TRASH} | ${false} | ${1} | ${1} | ${`Trash`} | ${INBOX} | ${`Conversation moved to Trash.`}
${TRASH} | ${false} | ${2} | ${1} | ${`Trash`} | ${INBOX} | ${`2 conversations moved to Trash.`}
`(
'should return expected text [$expectedText]',
({
isMessage,
elementsCount,
messagesNotAuthorizedToMove,
folderName,
folderID,
fromLabelID,
expectedText,
}) => {
expect(
getNotificationTextMoved(
isMessage,
elementsCount,
messagesNotAuthorizedToMove,
folderName,
folderID,
fromLabelID
)
).toEqual(expectedText);
}
);
});
describe('getNotificationTextUnauthorized', () => {
it.each`
folderID | fromLabelID | expectedText
${INBOX} | ${SENT} | ${`Sent messages cannot be moved to Inbox`}
${INBOX} | ${ALL_SENT} | ${`Sent messages cannot be moved to Inbox`}
${SPAM} | ${SENT} | ${`Sent messages cannot be moved to Spam`}
${SPAM} | ${ALL_SENT} | ${`Sent messages cannot be moved to Spam`}
${INBOX} | ${DRAFTS} | ${`Drafts cannot be moved to Inbox`}
${INBOX} | ${ALL_DRAFTS} | ${`Drafts cannot be moved to Inbox`}
${SPAM} | ${DRAFTS} | ${`Drafts cannot be moved to Spam`}
${SPAM} | ${ALL_DRAFTS} | ${`Drafts cannot be moved to Spam`}
`(`should return expected text [$expectedText]} `, ({ folderID, fromLabelID, expectedText }) => {
expect(getNotificationTextUnauthorized(folderID, fromLabelID)).toEqual(expectedText);
});
});
describe('searchForScheduled', () => {
it('should show move schedule modal when moving scheduled messages', async () => {
const folderID = TRASH;
const isMessage = true;
const elements: Element[] = [{ LabelIDs: [SCHEDULED] } as Element];
const setCanUndo = jest.fn();
const handleShowModal = jest.fn();
await searchForScheduled(folderID, isMessage, elements, setCanUndo, handleShowModal);
expect(handleShowModal).toHaveBeenCalled();
});
it('should not show move schedule modal when moving other type of messages', async () => {
const folderID = TRASH;
const isMessage = true;
const elements: Element[] = [{ LabelIDs: [SPAM] } as Element];
const setCanUndo = jest.fn();
const handleShowModal = jest.fn();
await searchForScheduled(folderID, isMessage, elements, setCanUndo, handleShowModal);
expect(handleShowModal).not.toHaveBeenCalled();
});
it('should show move schedule modal when moving scheduled conversations', async () => {
const folderID = TRASH;
const isMessage = false;
const elements: Element[] = [
{
ID: 'conversation',
Labels: [{ ID: SCHEDULED } as Label],
} as Element,
];
const setCanUndo = jest.fn();
const handleShowModal = jest.fn();
await searchForScheduled(folderID, isMessage, elements, setCanUndo, handleShowModal);
expect(handleShowModal).toHaveBeenCalled();
});
it('should not show move schedule modal when moving other types of conversations', async () => {
const folderID = TRASH;
const isMessage = false;
const elements: Element[] = [
{
ID: 'conversation',
Labels: [{ ID: SPAM } as Label],
} as Element,
];
const setCanUndo = jest.fn();
const handleShowModal = jest.fn();
await searchForScheduled(folderID, isMessage, elements, setCanUndo, handleShowModal);
expect(handleShowModal).not.toHaveBeenCalled();
});
});
describe('askToUnsubscribe', () => {
it('should not open the unsubscribe modal when SpamAction in setting is set', async () => {
const folderID = SPAM;
const isMessage = true;
const elements = [{} as Element];
const api = apiMock;
const handleShowSpamModal = jest.fn();
const mailSettings = { SpamAction: SPAM_ACTION.SpamAndUnsub } as MailSettings;
await askToUnsubscribe(folderID, isMessage, elements, api, handleShowSpamModal, mailSettings);
expect(handleShowSpamModal).not.toHaveBeenCalled();
});
it('should not open the unsubscribe modal when no message can be unsubscribed', async () => {
const folderID = SPAM;
const isMessage = true;
const elements = [{} as Element];
const api = apiMock;
const handleShowSpamModal = jest.fn();
const mailSettings = { SpamAction: null } as MailSettings;
await askToUnsubscribe(folderID, isMessage, elements, api, handleShowSpamModal, mailSettings);
expect(handleShowSpamModal).not.toHaveBeenCalled();
});
it('should open the unsubscribe modal and unsubscribe', async () => {
const folderID = SPAM;
const isMessage = true;
const elements = [
{
UnsubscribeMethods: {
OneClick: 'OneClick',
},
} as Element,
];
const api = apiMock;
const handleShowSpamModal = jest.fn(() => {
return Promise.resolve({ unsubscribe: true, remember: false });
});
const mailSettings = { SpamAction: null } as MailSettings;
const result = await askToUnsubscribe(
folderID,
isMessage,
elements,
api,
handleShowSpamModal,
mailSettings
);
expect(result).toEqual(SPAM_ACTION.SpamAndUnsub);
expect(handleShowSpamModal).toHaveBeenCalled();
});
it('should open the unsubscribe modal but not unsubscribe', async () => {
const folderID = SPAM;
const isMessage = true;
const elements = [
{
UnsubscribeMethods: {
OneClick: 'OneClick',
},
} as Element,
];
const api = apiMock;
const handleShowSpamModal = jest.fn(() => {
return Promise.resolve({ unsubscribe: false, remember: false });
});
const mailSettings = { SpamAction: null } as MailSettings;
const result = await askToUnsubscribe(
folderID,
isMessage,
elements,
api,
handleShowSpamModal,
mailSettings
);
expect(result).toEqual(SPAM_ACTION.JustSpam);
expect(handleShowSpamModal).toHaveBeenCalled();
});
it('should remember to always unsubscribe', async () => {
const updateSettingSpy = jest.fn();
addApiMock(`mail/v4/settings/spam-action`, updateSettingSpy, 'put');
const folderID = SPAM;
const isMessage = true;
const elements = [
{
UnsubscribeMethods: {
OneClick: 'OneClick',
},
} as Element,
];
const api = apiMock;
const handleShowSpamModal = jest.fn(() => {
return Promise.resolve({ unsubscribe: true, remember: true });
});
const mailSettings = { SpamAction: null } as MailSettings;
const result = await askToUnsubscribe(
folderID,
isMessage,
elements,
api,
handleShowSpamModal,
mailSettings
);
expect(result).toEqual(SPAM_ACTION.SpamAndUnsub);
expect(handleShowSpamModal).toHaveBeenCalled();
expect(updateSettingSpy).toHaveBeenCalled();
});
});
});
| 3,815
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/moveToFolder.ts
|
import { c, msgid } from 'ttag';
import { updateSpamAction } from '@proton/shared/lib/api/mailSettings';
import { TelemetryMailSelectAllEvents, TelemetryMeasurementGroups } from '@proton/shared/lib/api/telemetry';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { sendTelemetryReport } from '@proton/shared/lib/helpers/metrics';
import { Api, MailSettings } from '@proton/shared/lib/interfaces';
import { Folder } from '@proton/shared/lib/interfaces/Folder';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { SPAM_ACTION } from '@proton/shared/lib/mail/mailSettings';
import { isUnsubscribable } from '@proton/shared/lib/mail/messages';
import isTruthy from '@proton/utils/isTruthy';
import { isCustomFolder } from 'proton-mail/helpers/labels';
import { Conversation } from '../models/conversation';
import { Element } from '../models/element';
const { SPAM, TRASH, SENT, ALL_SENT, DRAFTS, ALL_DRAFTS, INBOX, ARCHIVE, SCHEDULED, SNOOZED } = MAILBOX_LABEL_IDS;
const joinSentences = (success: string, notAuthorized: string) => [success, notAuthorized].filter(isTruthy).join(' ');
export const getNotificationTextMoved = (
isMessage: boolean,
elementsCount: number,
messagesNotAuthorizedToMove: number,
folderName: string,
folderID?: string,
fromLabelID?: string
) => {
const notAuthorized = messagesNotAuthorizedToMove
? c('Info').ngettext(
msgid`${messagesNotAuthorizedToMove} message could not be moved.`,
`${messagesNotAuthorizedToMove} messages could not be moved.`,
messagesNotAuthorizedToMove
)
: '';
if (folderID === SPAM) {
if (isMessage) {
if (elementsCount === 1) {
return c('Success').t`Message moved to spam and sender added to your spam list.`;
}
return joinSentences(
c('Success').ngettext(
msgid`${elementsCount} message moved to spam and sender added to your spam list.`,
`${elementsCount} messages moved to spam and senders added to your spam list.`,
elementsCount
),
notAuthorized
);
}
if (elementsCount === 1) {
return c('Success').t`Conversation moved to spam and sender added to your spam list.`;
}
return c('Success').ngettext(
msgid`${elementsCount} conversation moved to spam and sender added to your spam list.`,
`${elementsCount} conversations moved to spam and senders added to your spam list.`,
elementsCount
);
}
if (fromLabelID === SPAM && folderID !== TRASH) {
if (isMessage) {
if (elementsCount === 1) {
// translator: Strictly 1 message moved from spam, the variable is the name of the destination folder
return c('Success').t`Message moved to ${folderName} and sender added to your not spam list.`;
}
return joinSentences(
c('Success').ngettext(
// translator: The first variable is the number of message moved, written in digits, and the second one is the name of the destination folder
msgid`${elementsCount} message moved to ${folderName} and sender added to your not spam list.`,
`${elementsCount} messages moved to ${folderName} and senders added to your not spam list.`,
elementsCount
),
notAuthorized
);
}
if (elementsCount === 1) {
return c('Success').t`Conversation moved to ${folderName} and sender added to your not spam list.`;
}
return c('Success').ngettext(
msgid`${elementsCount} conversation moved to ${folderName} and sender added to your not spam list.`,
`${elementsCount} conversations moved to ${folderName} and senders added to your not spam list.`,
elementsCount
);
}
if (isMessage) {
if (elementsCount === 1) {
return c('Success').t`Message moved to ${folderName}.`;
}
return joinSentences(
c('Success').ngettext(
msgid`${elementsCount} message moved to ${folderName}.`,
`${elementsCount} messages moved to ${folderName}.`,
elementsCount
),
notAuthorized
);
}
if (elementsCount === 1) {
return c('Success').t`Conversation moved to ${folderName}.`;
}
return c('Success').ngettext(
msgid`${elementsCount} conversation moved to ${folderName}.`,
`${elementsCount} conversations moved to ${folderName}.`,
elementsCount
);
};
export const getNotificationTextUnauthorized = (folderID?: string, fromLabelID?: string) => {
let notificationText = c('Error display when performing invalid move on message')
.t`This action cannot be performed`;
if (fromLabelID === SENT || fromLabelID === ALL_SENT) {
if (folderID === INBOX) {
notificationText = c('Error display when performing invalid move on message')
.t`Sent messages cannot be moved to Inbox`;
} else if (folderID === SPAM) {
notificationText = c('Error display when performing invalid move on message')
.t`Sent messages cannot be moved to Spam`;
}
} else if (fromLabelID === DRAFTS || fromLabelID === ALL_DRAFTS) {
if (folderID === INBOX) {
notificationText = c('Error display when performing invalid move on message')
.t`Drafts cannot be moved to Inbox`;
} else if (folderID === SPAM) {
notificationText = c('Error display when performing invalid move on message')
.t`Drafts cannot be moved to Spam`;
}
}
return notificationText;
};
const searchForLabelInElement = (isMessage: boolean, elements: Element[], labelToSearch: MAILBOX_LABEL_IDS) => {
if (isMessage) {
return (elements as Message[]).filter((element) => element.LabelIDs.includes(labelToSearch));
} else {
return (elements as Conversation[]).filter(
(element) => element.Labels?.some((label) => label.ID === labelToSearch)
);
}
};
const searchForLabelsAndOpenModal = async (
forbiddenLabels: string[],
labelToSearch: MAILBOX_LABEL_IDS,
folderID: string,
isMessage: boolean,
elements: Element[],
setCanUndo: (canUndo: boolean) => void,
handleShowModal: (ownProps: unknown) => Promise<unknown>,
setContainFocus?: (contains: boolean) => void
) => {
if (!forbiddenLabels.includes(folderID)) {
return;
}
const numberOfMessages = searchForLabelInElement(isMessage, elements, labelToSearch).length;
const canUndo = !(numberOfMessages > 0 && numberOfMessages === elements.length);
setCanUndo(canUndo);
if (!canUndo) {
setContainFocus?.(false);
await handleShowModal({ isMessage, onCloseCustomAction: () => setContainFocus?.(true) });
}
};
/*
* Opens a modal when finding scheduled messages that are moved to trash.
* If all selected are scheduled elements, we prevent doing a Undo because trashed scheduled becomes draft.
* And undoing this action transforms the draft into another draft.
*/
export const searchForScheduled = async (
folderID: string,
isMessage: boolean,
elements: Element[],
setCanUndo: (canUndo: boolean) => void,
handleShowModal: (ownProps: unknown) => Promise<unknown>,
setContainFocus?: (contains: boolean) => void
) => {
await searchForLabelsAndOpenModal(
[TRASH],
SCHEDULED,
folderID,
isMessage,
elements,
setCanUndo,
handleShowModal,
setContainFocus
);
};
/*
* Opens a modal when finding snozed messages that are moved to trash or archive.
* Unlike scheduled messages, snoozed messages cannot be moved to custom folders.
*/
export const searchForSnoozed = async (
folderID: string,
isMessage: boolean,
elements: Element[],
setCanUndo: (canUndo: boolean) => void,
handleShowModal: (ownProps: unknown) => Promise<unknown>,
setContainFocus?: (contains: boolean) => void,
folders: Folder[] = []
) => {
await searchForLabelsAndOpenModal(
[TRASH, ARCHIVE, INBOX],
SNOOZED,
folderID,
isMessage,
elements,
setCanUndo,
handleShowModal,
setContainFocus
);
const hasSnoozeLabel = searchForLabelInElement(isMessage, elements, SNOOZED).length;
if (hasSnoozeLabel && folders.map(({ ID }) => ID).includes(folderID)) {
await handleShowModal({ isMessage, onCloseCustomAction: () => setContainFocus?.(true) });
}
};
export const askToUnsubscribe = async (
folderID: string,
isMessage: boolean,
elements: Element[],
api: Api,
handleShowSpamModal: (ownProps: {
isMessage: boolean;
elements: Element[];
}) => Promise<{ unsubscribe: boolean; remember: boolean }>,
mailSettings: MailSettings
) => {
if (folderID === SPAM) {
if (mailSettings.SpamAction === null) {
const canBeUnsubscribed = elements.some((message) => isUnsubscribable(message));
if (!canBeUnsubscribed) {
return;
}
const { unsubscribe, remember } = await handleShowSpamModal({ isMessage, elements });
const spamAction = unsubscribe ? SPAM_ACTION.SpamAndUnsub : SPAM_ACTION.JustSpam;
if (remember) {
// Don't waste time
void api(updateSpamAction(spamAction));
}
// This choice is return and used in the label API request
return spamAction;
}
return mailSettings.SpamAction;
}
};
// Return the labelID if the folder is a system folder, 'custom_folder' otherwise
export const getCleanedFolderID = (labelID: string, folders: Folder[]) => {
return isCustomFolder(labelID, folders) ? 'custom_folder' : labelID;
};
export const sendSelectAllTelemetryReport = async ({
api,
sourceLabelID,
event,
}: {
api: Api;
sourceLabelID: string;
event: TelemetryMailSelectAllEvents;
}) => {
void sendTelemetryReport({
api: api,
measurementGroup: TelemetryMeasurementGroups.mailSelectAll,
event,
dimensions: {
sourceLabelID,
},
});
};
| 3,816
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/paging.test.ts
|
import { expectedPageLength, pageCount } from './paging';
describe('paging helper', () => {
describe('pageCount', () => {
it('should be 1 when total is less than size', () => {
expect(pageCount(10)).toBe(1);
});
it('should be the number of pages the user can see', () => {
expect(pageCount(125)).toBe(3);
});
});
describe('expectedPageLength', () => {
it('should be 0 if total is 0', () => {
expect(expectedPageLength(0, 0, 0)).toBe(0);
});
it('should be size if total is a multiple of the size', () => {
expect(expectedPageLength(0, 150, 0)).toBe(50);
});
it('should be the rest on last page', () => {
expect(expectedPageLength(2, 125, 0)).toBe(25);
});
it('should be the size if not last page', () => {
expect(expectedPageLength(1, 125, 0)).toBe(50);
});
it('should be 0 if page is after the total', () => {
expect(expectedPageLength(2, 100, 0)).toBe(0);
});
it('should deal with bypass filter when less than a page', () => {
expect(expectedPageLength(0, 25, 2)).toBe(27);
});
it('should deal with bypass filter even if there is no more elements', () => {
expect(expectedPageLength(0, 0, 2)).toBe(2);
});
it('should deal with bypass filter in a middle of a list', () => {
expect(expectedPageLength(1, 125, 2)).toBe(50);
});
it('should deal with bypass filter in the last page', () => {
expect(expectedPageLength(2, 125, 2)).toBe(27);
});
it('should deal with bypass filter if it changes the page cont', () => {
expect(expectedPageLength(0, 40, 20)).toBe(50);
});
it("should deal with bypass filter if it's huge", () => {
expect(expectedPageLength(0, 20, 60)).toBe(50);
});
});
});
| 3,817
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/paging.ts
|
import { PAGE_SIZE } from '../constants';
export const pageCount = (total: number) => Math.ceil(total / PAGE_SIZE) || 0;
export const expectedPageLength = (page: number, inputTotal: number, filterBypassCount: number) => {
const total = inputTotal + filterBypassCount;
if (total === 0) {
return 0;
}
const count = pageCount(total);
if (page >= count) {
return 0;
}
if (total % PAGE_SIZE === 0) {
return PAGE_SIZE;
}
if (count - 1 === page) {
return total % PAGE_SIZE;
}
return PAGE_SIZE;
};
| 3,818
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/parserHtml.test.ts
|
import { toText } from './parserHtml';
describe('toText', () => {
it('should not escape single underline', () => {
const string = 'MONO_TLS_PROVIDER';
expect(toText(string)).toEqual(string);
});
it('should not escape multiple underlines', () => {
const string = '___';
expect(toText(string)).toEqual(string);
});
it('should convert to the right format if there are LIs', () => {
const input = `
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<div>jeanne mange <b>une boule de glace</b> <i>à la vanille.</i><br></div>
<ul>
<li>Une vache<br></li>
<li>Un ane<br></li>
<li>Une brebis<br></li>
</ul>
<div>A table<br></div>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">Sent with <a href="https://proton.me/?utm_campaign=ww-all-2a-mail-pmm_mail-protonmail_signature&utm_source=proton_users&utm_medium=cta&utm_content=sent_with_protonmail_secure_email" target="_blank">ProtonMail</a> Secure Email.<br></div>
</div>`;
const result = `jeanne mange\xa0une boule de glace\xa0à la vanille.
- Une vache
- Un ane
- Une brebis
A table
Sent with ProtonMail Secure Email.`;
expect(toText(input)).toEqual(result);
});
it('should convert to the right format', () => {
const input = `
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<div>: <a href="http://anothercoffee.net">http://anothercoffee.net</a><br></div>
<div>: Drupal to WordPress migration specialists<br></div>
<div>:<br></div>
<div>: Another Cup of Coffee Limited<br></div>
<div>: Registered in England and Wales number 05992203<br></div>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">Sent with <a href="https://proton.me/?utm_campaign=ww-all-2a-mail-pmm_mail-protonmail_signature&utm_source=proton_users&utm_medium=cta&utm_content=sent_with_protonmail_secure_email" target="_blank">ProtonMail</a> Secure Email.<br></div>
</div>`;
const result = `: http://anothercoffee.net
: Drupal to WordPress migration specialists
:
: Another Cup of Coffee Limited
: Registered in England and Wales number 05992203
Sent with ProtonMail Secure Email.`;
expect(toText(input)).toEqual(result);
});
it('should keep the lines in signature', () => {
const input = `
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<div>---<br></div><div>This is a test account<br></div><div><br></div><div>swiip.test@protonmail.com<br></div>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
`;
const result = `---
This is a test account
swiip.test@protonmail.com`;
expect(toText(input)).toBe(result);
});
it('should keep the lines in original message', () => {
const input = `
<blockquote class="protonmail_quote" type="cite">
<div>Hey, this is a plain text message!<br>
<br>
Even with no less than 2 lines!</div>
</blockquote>
`;
const result = `> Hey, this is a plain text message!
>
> Even with no less than 2 lines!`;
expect(toText(input)).toBe(result);
});
it('should keep the lines in list', () => {
const input = `
<ul>
<li>content 1<br> content<br></li>
<li>content 2<br> content</li>
</ul>
`;
const result = `- content 1
content
- content 2
content`;
expect(toText(input)).toBe(result);
});
it('should keep empty lines in the beginning', () => {
const input = `
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;">test<br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div class="protonmail_signature_block" style="font-family: verdana; font-size: 20px;">
<div class="protonmail_signature_block-user">
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">my signature</div>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
`;
const result = `
test
my signature`;
expect(toText(input)).toBe(result);
});
it('should keep empty lines in the content and the signature', () => {
const input = `
<div style="font-family: verdana; font-size: 20px;">Testcontent1</div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;">Testcontent2</div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div style="font-family: verdana; font-size: 20px;">Testcontent3</div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div class="protonmail_signature_block" style="font-family: verdana; font-size: 20px;">
<div class="protonmail_signature_block-user">
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">Test1</div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);"><br></div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">Testtest2</div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);"><br></div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">Testtesttest3</div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);"><br></div>
<div style="font-family:arial;font-size:14px;color:rgb(34,34,34);">Testtesttesttest4</div>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty"></div>
</div>
`;
const result = `Testcontent1
Testcontent2
Testcontent3
Test1
Testtest2
Testtesttest3
Testtesttesttest4`;
expect(toText(input)).toBe(result);
});
});
| 3,819
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/parserHtml.ts
|
import TurndownService from 'turndown';
import identity from '@proton/utils/identity';
const EMPTY_LINE_KEEPER = '%%%PROTON-EMPTY-LINE%%%';
/**
* Transform HTML to text
* Append lines before the content if it starts with a Signature
*/
export const toText = (html: string, convertImages = false) => {
const turndownService = new TurndownService({
bulletListMarker: '-',
strongDelimiter: '' as any,
emDelimiter: '' as any,
hr: '',
});
const replaceBreakLine = {
filter: 'br',
replacement(content: string, node: HTMLElement) {
// ex <li>monique<br></li>
if (node.parentElement?.lastChild === node && node.parentElement.textContent) {
return node.parentElement.nodeName !== 'LI' ? '\n' : '';
}
// Turndown remove multiple empty lines by default
// So we use special anchors on each line break to for keeping all lines
return `${EMPTY_LINE_KEEPER}\n`;
},
} as TurndownService.Rule;
const replaceImg = {
filter: 'img',
replacement(content: string, element: HTMLElement) {
if (!convertImages) {
return '';
}
const image = element as HTMLImageElement;
// needed for the automatic conversion done by pgp/inline, otherwise the conversion happens and people forget that they have selected this for some contacts
const attribute = image.alt || image.src;
return attribute ? `[${attribute}]` : '';
},
} as TurndownService.Rule;
const replaceAnchor = {
filter: 'a',
replacement(content: string, node: HTMLElement) {
return node.textContent;
},
} as TurndownService.Rule;
const replaceDiv = {
filter: ['div'],
replacement(content: string, node: HTMLElement) {
if (node.children.length > 0 && (node.lastChild?.nodeName === 'BR' || node.lastChild?.nodeName === 'DIV')) {
return content;
}
return `${content}\n`;
},
} as TurndownService.Rule;
const removeHiddenTags = {
filter: (node: HTMLElement) => node.style.display === 'none' || node.style.visibility === 'hidden',
replacement: () => '',
} as TurndownService.Rule;
turndownService.use([
() => turndownService.addRule('replaceAnchor', replaceAnchor),
() => turndownService.addRule('replaceDiv', replaceDiv),
() => turndownService.addRule('replaceImg', replaceImg),
() => turndownService.addRule('replaceBreakLine', replaceBreakLine),
() => turndownService.addRule('removeHiddenTags', removeHiddenTags),
]);
/**
* Override turndown to NOT escape any HTML. For example MONO_TLS_PROVIDER -> MONO\_TLS\_PROVIDER.
* Just return the value that is passed in.
* Fixes https://github.com/ProtonMail/Angular/issues/6556
*/
turndownService.escape = identity;
let output = turndownService.turndown(html);
// Remove anchors to meant to keep empty lines
const emptyLineRegex = new RegExp(EMPTY_LINE_KEEPER, 'gi');
output = output.replace(emptyLineRegex, '');
return output;
};
| 3,820
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/recipients.test.ts
|
import { Recipient } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { Conversation } from '../models/conversation';
import { getElementSenders } from './recipients';
describe('recipients helpers', () => {
const sender: Recipient = {
Address: 'sender@proton.me',
Name: 'Sender',
};
const recipient: Recipient = {
Address: 'recipient@proton.me',
Name: 'Recipient',
};
it('should give the sender of a message', () => {
const message = {
Sender: sender,
} as Message;
const result = getElementSenders(message, false, false);
const expected: Recipient[] = [sender];
expect(result).toEqual(expected);
});
it('should give the recipients of a message', () => {
const message = {
Sender: sender,
ToList: [recipient],
} as Message;
const result = getElementSenders(message, false, true);
const expected: Recipient[] = [recipient];
expect(result).toEqual(expected);
});
it('should give the senders of a conversation', () => {
const conversation = {
Senders: [sender],
} as Conversation;
const result = getElementSenders(conversation, true, false);
const expected: Recipient[] = [sender];
expect(result).toEqual(expected);
});
it('should give the recipients of a conversation', () => {
const conversation = {
Senders: [sender],
Recipients: [recipient],
} as Conversation;
const result = getElementSenders(conversation, true, true);
const expected: Recipient[] = [recipient];
expect(result).toEqual(expected);
});
});
| 3,821
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/recipients.ts
|
import { Recipient } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { getRecipients as getMessageRecipients, getSender } from '@proton/shared/lib/mail/messages';
import { Element } from '../models/element';
import { getRecipients as getConversationRecipients, getSenders } from './conversation';
/**
* Get an array of Recipients that we use to display the recipients in the message list
* In most locations, we want to see the Senders at this place, but for some other (e.g. Sent)
* we will need to display the recipients instead.
*/
export const getElementSenders = (
element: Element,
conversationMode: boolean,
displayRecipients: boolean
): Recipient[] => {
// For some locations (e.g. Sent folder), if this is a message that the user sent,
// we don't display the sender but the recipients
let recipients: Recipient[] = [];
if (displayRecipients) {
recipients = conversationMode ? getConversationRecipients(element) : getMessageRecipients(element as Message);
} else {
if (conversationMode) {
recipients = getSenders(element);
} else {
const sender = getSender(element as Message);
recipients = sender ? [sender] : [];
}
}
return recipients;
};
| 3,822
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/schedule.test.ts
|
import { getMinScheduleTime } from './schedule';
describe('getMinScheduleTime', () => {
afterEach(() => {
jest.useRealTimers();
});
it('should get the correct min scheduled time if selected date is not today', () => {
const fakeNow = new Date(2021, 0, 1, 9, 20, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
// Date which is currently selected is not today
const date = new Date(2021, 0, 5, 9, 20, 0);
const minTimeDate = getMinScheduleTime(date);
// We expect the function to return undefined because if not today,
// there is no min time (we want the whole interval from 00:00 to 23:30)
const expectedMinTimeDate = undefined;
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
it('should get the correct min scheduled time if time < XX:30 and still in 2 minutes limit', () => {
const fakeNow = new Date(2021, 0, 1, 9, 20, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const minTimeDate = getMinScheduleTime(fakeNow);
const expectedMinTimeDate = new Date(2021, 0, 1, 9, 30, 0);
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
it('should get the correct min scheduled time if time < XX:30 and not in 2 minutes limit', () => {
const fakeNow = new Date(2021, 0, 1, 9, 28, 30);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const minTimeDate = getMinScheduleTime(fakeNow);
// We cannot schedule a message within the next 2 minutes, so if it's 9:28, we should return 10:00
const expectedMinTimeDate = new Date(2021, 0, 1, 10, 0, 0);
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
it('should get the correct min scheduled time if time > XX:30 and still in 2 minutes limit', () => {
const fakeNow = new Date(2021, 0, 1, 9, 55, 0);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const minTimeDate = getMinScheduleTime(fakeNow);
const expectedMinTimeDate = new Date(2021, 0, 1, 10, 0, 0);
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
it('should get the correct min scheduled time if time > XX:30 and not in 2 minutes limit', () => {
const fakeNow = new Date(2021, 0, 1, 9, 58, 30);
jest.useFakeTimers().setSystemTime(fakeNow.getTime());
const minTimeDate = getMinScheduleTime(fakeNow);
// We cannot schedule a message within the next 2 minutes, so if it's 9:58, we should return 10:30
const expectedMinTimeDate = new Date(2021, 0, 1, 10, 30, 0);
expect(minTimeDate).toEqual(expectedMinTimeDate);
});
});
| 3,823
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/schedule.ts
|
import { addMinutes, addSeconds, isToday } from 'date-fns';
export const getMinScheduleTime = (date: Date) => {
// If date is not today, there is no min time because we want to display all intervals
if (!isToday(date)) {
return undefined;
}
// Date that will be used for intervals, we don't want it to have minutes or seconds set in intervals
// Intervals needs to be XX:00 AM/PM or XX:30 AM/PM
const nowForInterval = new Date();
nowForInterval.setMinutes(0, 0);
// Current date used to get the correct min interval to display to the user
// Limit is now date + 2 minutes
const now = new Date();
const limit = addSeconds(now, 120);
// Calculate intervals
// If it's 9:50 AM/PM, we should get
// 9:30, 10:00, 10:30
const nextIntervals = Array.from(Array(3)).map((_, i) => addMinutes(nowForInterval, 30 * (i + 1)));
// Return the correct min interval to display in the time input
// If it's 9:XX, we should get intervals 9:30, 10:00, 10:30
// If it's 9:20 => return 9:30
// If it's 9:55 => return 10:00
// If it's 9:58 => return 10:30
return limit <= nextIntervals[0]
? nextIntervals[0]
: limit <= nextIntervals[1]
? nextIntervals[1]
: nextIntervals[2];
};
| 3,824
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/sidebar.test.ts
|
import { FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder';
import { UnreadCounts } from '../components/sidebar/MailSidebarList';
import { getUnreadCount } from './sidebar';
const EXPANDED = 1;
const COLLAPSED = 0;
describe('getUnreadCount', () => {
const counterMap = { A: 3, B: 1, C: 2, D: 0 } as UnreadCounts;
const folder = {
ID: 'A',
Expanded: EXPANDED,
subfolders: [
{
ID: 'B',
Expanded: EXPANDED,
subfolders: [
{
ID: 'C',
Expanded: EXPANDED,
subfolders: [
{
ID: 'D',
Expanded: EXPANDED,
} as FolderWithSubFolders,
],
} as FolderWithSubFolders,
],
} as FolderWithSubFolders,
],
} as FolderWithSubFolders;
it('should accumulate unread total when collapsed', () => {
expect(getUnreadCount(counterMap, { ...folder, Expanded: COLLAPSED })).toEqual(6);
});
it('should display display individual unreal total', () => {
expect(getUnreadCount(counterMap, folder)).toEqual(3);
});
});
| 3,825
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/sidebar.ts
|
import { FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder';
import { UnreadCounts } from '../components/sidebar/MailSidebarList';
export const getUnreadCount = (counterMap: UnreadCounts, folder: FolderWithSubFolders): number => {
if (folder.Expanded) {
return counterMap[folder.ID] || 0;
}
return (folder?.subfolders || []).reduce(
(acc, fold) => acc + getUnreadCount(counterMap, { ...fold, Expanded: 0 }), // force Expanded to 0 to count all sub folders
counterMap[folder.ID] || 0
);
};
| 3,826
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/string.test.ts
|
import { extractChevrons, htmlEntities, replaceLineBreaks, toUnsignedString, ucFirst } from './string';
describe('toUnsignedString', () => {
it('should convert integer to unsigned string', () => {
const value = 1000;
const result = toUnsignedString(value, 1);
expect(result).not.toContain('-');
expect(result.length).toEqual(10);
expect(result).toEqual('1111101000');
});
});
describe('ucFirst', () => {
it('should uppercase the first character in a string', () => {
const string = 'hello welcome at Proton';
const expected = 'Hello welcome at Proton';
expect(ucFirst(string)).toEqual(expected);
});
});
describe('extractChevrons', () => {
it('should extract chevrons from string', () => {
const string1 = '<address@pm.me>';
const string2 = 'Address <address@pm.me>';
const string3 = 'no chevrons here';
expect(extractChevrons(string1)).toEqual('address@pm.me');
expect(extractChevrons(string2)).toEqual('address@pm.me');
expect(extractChevrons(string3)).toEqual('');
});
});
describe('htmlEntities', () => {
it('should add HTML entities in string', () => {
const string = 'chevrons=<> and=& quote=" rest should be okay#@!$%^*()_-';
const expected = 'chevrons=<> and=& quote=" rest should be okay#@!$%^*()_-';
expect(htmlEntities(string)).toEqual(expected);
});
});
describe('replaceLineBreaks', () => {
it('should replace line breaks from string', () => {
const string = `<div>Hello\nHow\rare\r\nyou?</div>`;
const expected = `<div>Hello<br />How<br />are<br />you?</div>`;
expect(replaceLineBreaks(string)).toEqual(expected);
});
});
| 3,827
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/string.ts
|
export const EMAIL_FORMATING = {
OPEN_TAG_AUTOCOMPLETE: '‹',
CLOSE_TAG_AUTOCOMPLETE: '›',
OPEN_TAG_AUTOCOMPLETE_RAW: '<',
CLOSE_TAG_AUTOCOMPLETE_RAW: '>',
};
const { OPEN_TAG_AUTOCOMPLETE, CLOSE_TAG_AUTOCOMPLETE, OPEN_TAG_AUTOCOMPLETE_RAW, CLOSE_TAG_AUTOCOMPLETE_RAW } =
EMAIL_FORMATING;
export const MAP_TAGS = {
[OPEN_TAG_AUTOCOMPLETE_RAW]: OPEN_TAG_AUTOCOMPLETE,
[CLOSE_TAG_AUTOCOMPLETE_RAW]: CLOSE_TAG_AUTOCOMPLETE,
[OPEN_TAG_AUTOCOMPLETE]: OPEN_TAG_AUTOCOMPLETE_RAW,
[CLOSE_TAG_AUTOCOMPLETE]: CLOSE_TAG_AUTOCOMPLETE_RAW,
};
/**
* Converts the integer to a 32-bit base encoded string in 2s complement format, so that it doesn't contain a sign "-"
* @param val The integer to be encoded
* @param bits The amount of bits per character
*/
export const toUnsignedString = (val: number, bits: number) => {
const base = 1 << bits;
const wordCount = Math.ceil(32 / bits);
const bottomBits = (wordCount - 1) * bits;
const bottom = val & ((1 << bottomBits) - 1);
const top = val >>> bottomBits;
if (top === 0) {
return bottom.toString(base);
}
const topString = top.toString(base);
const bottomString = bottom.toString(base);
const padLength = wordCount - topString.length - bottomString.length;
const middleString = '0'.repeat(padLength);
return topString + middleString + bottomString;
};
export const ucFirst = (input = '') => {
return input.charAt(0).toUpperCase() + input.slice(1);
};
/**
* Extract value between chevrons
* @param str ex: Andy <andy@pm.me>
* @return ex: andy@pm.me
*/
export const extractChevrons = (str = '') => {
const CHEVRONS_REGEX = /<([^>]+)>/g;
const [, match = ''] = CHEVRONS_REGEX.exec(str) || [];
return match;
};
/**
* @{link https://css-tricks.com/snippets/javascript/htmlentities-for-javascript/}
*/
export const htmlEntities = (str = '') => {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
export const uniqID = () => {
return `pt${Math.random().toString(32).slice(2, 12)}-${Date.now()}`;
};
const lineBreaksRegex = /(?:\r\n|\r|\n)/g;
export const replaceLineBreaks = (content: string) => {
return content.replace(lineBreaksRegex, '<br />');
};
export const removeLineBreaks = (content: string) => {
return content.replace(lineBreaksRegex, '');
};
/**
* Generate a hash
*/
export const hash = (str = '') => {
// bitwise or with 0 ( | 0) makes sure we are using integer arithmetic and not floating point arithmetic
return str.split('').reduce((prevHash, currVal) => (prevHash * 31 + currVal.charCodeAt(0)) | 0, 0);
};
| 3,828
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/textToHtml.test.ts
|
import { MailSettings } from '@proton/shared/lib/interfaces';
import { textToHtml } from './textToHtml';
describe('textToHtml', () => {
it('should convert simple string from plain text to html', () => {
expect(textToHtml('This a simple string', '', undefined, undefined)).toEqual('This a simple string');
});
it('should convert multiline string too', () => {
const html = textToHtml(
`Hello
this is a multiline string`,
'',
undefined,
undefined
);
expect(html).toEqual(`Hello<br>
this is a multiline string`);
});
it('Multi line', () => {
// Add a little
const html = textToHtml(
`a title
## hello
this is a multiline string`,
'<p>My signature</p>',
{
Signature: '<p>My signature</p>',
FontSize: 16,
FontFace: 'Arial',
} as MailSettings,
undefined
);
expect(html).toEqual(`a title<br>
## hello<br>
this is a multiline string`);
});
it('should not convert markdown line headings ', () => {
/**
* Here the "--" represents a h2 title in markdown
*/
const html = textToHtml(
`a title
--
this is a multiline string`,
'',
undefined,
undefined
);
expect(html).toEqual(`a title<br>
--<br>
this is a multiline string`);
});
});
| 3,829
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/textToHtml.ts
|
import markdownit from 'markdown-it';
import { defaultFontStyle } from '@proton/components/components/editor/helpers';
import { MailSettings, UserSettings } from '@proton/shared/lib/interfaces';
import { templateBuilder } from './message/messageSignature';
import { toText } from './parserHtml';
const SIGNATURE_PLACEHOLDER = '--protonSignature--';
const OPTIONS = {
breaks: true,
linkify: true,
};
const md = markdownit('default', OPTIONS).disable(['lheading', 'heading', 'list', 'code', 'fence', 'hr']);
/**
* This function generates a random string that is not included in the input text.
* This is used to be able to insert and remove placeholders in new lines, so markdown will treat those newlines
* as not empty. Therefore we need the placeholders to be unique, to not remove parts of the text when we
* remove the placeholders.
*
* To ensure the placeholder is unique we try a random string, which should be with > 99% chance unique,
* but if it's not unique, we'll retry to make the function always behave correctly.
* @param text
* @returns {string}
*/
const generatePlaceHolder = (text: string) => {
let placeholder = '';
do {
placeholder = Math.random().toString(36).substring(3) + Math.random().toString(36).substring(3);
} while (text.includes(placeholder));
return placeholder;
};
/**
* Fills a given text with newlines with placeholders that can be removed later.
* For instance the following input:
* "
*
*
* "
* is turned into
* "
* placeholder
* "
* The input is not turned into
* "placeholder
* placeholder
* placeholder"
* as we expect the first new line to come from an non empty new line, and the last new line is followed by a non
* empty new line. This is how addNewLinePlaceholders uses this function.
*/
const newLineIntoPlaceholder = (match: string, placeholder: string) =>
match.replace(/(\r\n|\n)/g, (match) => match + placeholder).replace(new RegExp(`${placeholder}$`, 'g'), '');
/**
* Turns any empty lines into lines filled with the specified placeholder
* to trick the markdown converter into keeping
* those empty lines.
*/
const addNewLinePlaceholders = (text: string, placeholder: string) => {
const startingNewline = text.startsWith('\n') ? text : `\n${text}`;
const textWPlaceholder = startingNewline.replace(/((\r\n|\n)\s*(\r\n|\n))+/g, (match) =>
newLineIntoPlaceholder(match, placeholder)
);
// don't remove empty new lines before '>'
const noEmptyLines = textWPlaceholder.replace(/^\n/g, '');
// add an empty line (otherwise markdownit doesnt end the blockquote) if it comes after a `>`
return noEmptyLines.replace(/(>[^\r\n]*(?:\r\n|\n))(\s*[^>])/g, (match, line1, line2) => `${line1}\n${line2}`);
};
const removeNewLinePlaceholder = (html: string, placeholder: string) => html.replace(new RegExp(placeholder, 'g'), '');
/**
* Escapes backslashes from the input text with another backslash.
*/
const escapeBackslash = (text = '') => text.replace(/\\/g, '\\\\');
/**
* Replace the signature by a temp hash, we replace it only
* if the content is the same.
*/
const replaceSignature = (
input: string,
signature: string,
mailSettings: MailSettings | undefined,
userSettings: UserSettings | undefined
) => {
const fontStyle = defaultFontStyle(mailSettings);
const signatureTemplate = templateBuilder(signature, mailSettings, userSettings, fontStyle, false, true);
const signatureText = toText(signatureTemplate)
.replace(/\u200B/g, '')
.trim();
return input.replace(signatureText, SIGNATURE_PLACEHOLDER);
};
/**
* Replace the hash by the signature inside the message formated as HTML
* We prevent too many lines to be added as we already have a correct message
*/
const attachSignature = (
input: string,
signature: string,
plaintext: string,
mailSettings: MailSettings | undefined,
userSettings: UserSettings | undefined
) => {
const fontStyle = defaultFontStyle(mailSettings);
const signatureTemplate = templateBuilder(
signature,
mailSettings,
userSettings,
fontStyle,
false,
!plaintext.startsWith(SIGNATURE_PLACEHOLDER)
);
return input.replace(SIGNATURE_PLACEHOLDER, signatureTemplate);
};
export const textToHtml = (
input = '',
signature: string,
mailSettings: MailSettings | undefined,
userSettings: UserSettings | undefined
) => {
const text = replaceSignature(input, signature, mailSettings, userSettings);
// We want empty new lines to behave as if they were not empty (this is non-standard markdown behaviour)
// It's more logical though for users that don't know about markdown.
const placeholder = generatePlaceHolder(text);
// We don't want to treat backslash as a markdown escape since it removes backslashes. So escape all backslashes with a backslash.
const withPlaceholder = addNewLinePlaceholders(escapeBackslash(text), placeholder);
const rendered = md.render(withPlaceholder);
const html = removeNewLinePlaceholder(rendered, placeholder);
const withSignature = attachSignature(html, signature, text, mailSettings, userSettings).trim();
/**
* The capturing group includes negative lookup "(?!<p>)" in order to avoid nested problems.
* Ex, this capture will be ignored : "<p>Hello</p><p>Hello again</p>""
* Because it would have ended up with this result : "Hello</p><p>Hello again"
*/
const extractContentFromPTag = /^<p>(((?!<p>)[\s\S])*)<\/p>$/.exec(withSignature)?.[1];
return extractContentFromPTag || withSignature;
};
| 3,830
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/upload.ts
|
import { getClientID } from '@proton/shared/lib/apps/helper';
import { getAppVersionHeaders, getUIDHeaders } from '@proton/shared/lib/fetch/headers';
import { serializeData } from '@proton/shared/lib/fetch/helpers';
import createListeners from '@proton/shared/lib/helpers/listeners';
import { API_URL, APP_NAME, APP_VERSION } from '../config';
import { createErrorHandler } from './dom';
export type HTTPHeaders = { [key: string]: string };
export enum HTTP_METHODS {
GET = 'get',
POST = 'post',
PUT = 'put',
DELETE = 'delete',
}
export enum HTTP_INPUTS {
FORM_DATA = 'form',
}
export interface RequestParams {
method: HTTP_METHODS;
url: string;
input: HTTP_INPUTS;
data: { [key: string]: Blob | string | undefined };
}
const clientID = getClientID(APP_NAME);
const appVersionHeaders = getAppVersionHeaders(clientID, APP_VERSION);
const defaultHeaders: HTTPHeaders = {
'X-Requested-With': 'XMLHttpRequest',
Accept: 'application/vnd.protonmail.v1+json',
...appVersionHeaders,
};
export interface Upload<T> {
/**
* Open reference to the actual XHR, but other fields should be more practical
*/
xhr: XMLHttpRequest;
/**
* Add listener to the upload progress events
*/
addProgressListener: (listener: (event: ProgressEvent) => void) => void;
/**
* Executing ths function will abort the current upload
*/
abort: () => void;
/**
* Promise resolved at the end of the upload and containing the JSON content returned by the server
*/
resultPromise: Promise<T>;
}
export const upload = <T>(uid: string, paramsPromise: RequestParams | Promise<RequestParams>): Upload<T> => {
const xhr = new XMLHttpRequest();
const { notify, subscribe } = createListeners<[ProgressEvent], void>();
const authHeaders = getUIDHeaders(uid) as HTTPHeaders;
const asyncResolution = async () => {
const params = await paramsPromise;
const { body, headers: dataHeaders = {} } = serializeData(params.data, params.input) as {
body: any;
headers?: HTTPHeaders;
};
const headers = {
...defaultHeaders,
...dataHeaders,
...authHeaders,
};
await new Promise<XMLHttpRequest>((resolve, reject) => {
xhr.upload.onprogress = notify;
xhr.onload = resolve as any;
xhr.upload.onerror = createErrorHandler(reject);
xhr.onerror = createErrorHandler(reject);
xhr.open(params.method, `${API_URL}/${params.url}`);
xhr.withCredentials = true;
Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key]));
xhr.send(body);
});
return JSON.parse(xhr.responseText);
};
return {
xhr,
addProgressListener: subscribe,
abort: () => xhr.abort(),
resultPromise: asyncResolution(),
};
};
| 3,831
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/url.test.ts
|
import { protonizer } from '@proton/shared/lib/sanitize';
import { removeLineBreaks } from './test/message';
import { mailtoParser, toAddresses } from './url';
const address1 = 'address1@pm.me';
const address2 = 'address2@pm.me';
const address3 = 'address3@pm.me';
const address4 = 'address4@pm.me';
const addressName1 = 'Address1';
const addressName2 = 'Address2';
const htmlEntity = '%C2%AD'; // Test when mailto contains HTML entity "­"
const subject = 'Mail subject';
const body = 'Mail body';
const bodyWithImages = `<div>
Body of the email
<img src="imageUrl" style="width:auto;">
</div>`;
describe('toAddresses', () => {
it('should split an addresses string to a list of recipients', function () {
const inputString1 = `${address1}, ${address2}`;
const inputString2 = `${addressName1} <${address1}>`;
const expectedResult1 = [
{ Name: address1, Address: address1 },
{ Name: address2, Address: address2 },
];
const expectedResult2 = [{ Name: addressName1, Address: address1 }];
expect(toAddresses(inputString1)).toEqual(expectedResult1);
expect(toAddresses(inputString2)).toEqual(expectedResult2);
});
});
describe('mailtoParser', () => {
it.each`
toList | expectedToList
${address1} | ${[{ Name: address1, Address: address1 }]}
${`${address1},${address2}`} | ${[{ Name: address1, Address: address1 }, { Name: address2, Address: address2 }]}
${`${addressName1} <${address1}>`} | ${[{ Name: addressName1, Address: address1 }]}
${`${addressName1} <${address1}>, ${addressName2} <${address2}>`} | ${[{ Name: addressName1, Address: address1 }, { Name: addressName2, Address: address2 }]}
${`address${htmlEntity}1@pm.me`} | ${[{ Name: address1, Address: address1 }]}
`('should detect the TO list in a mailto string with TO = $toList', ({ toList, expectedToList }) => {
const mailto = `mailto:${toList}?subject=${subject}`;
const { data } = mailtoParser(mailto);
expect(data?.ToList).toEqual(expectedToList);
});
it.each`
ccList | expectedCCList
${address1} | ${[{ Name: address1, Address: address1 }]}
${`${address1},${address2}`} | ${[{ Name: address1, Address: address1 }, { Name: address2, Address: address2 }]}
${`${addressName1} <${address1}>`} | ${[{ Name: addressName1, Address: address1 }]}
${`${addressName1} <${address1}>, ${addressName2} <${address2}>`} | ${[{ Name: addressName1, Address: address1 }, { Name: addressName2, Address: address2 }]}
${`address${htmlEntity}1@pm.me`} | ${[{ Name: address1, Address: address1 }]}
`('should detect the CC list in a mailto string with CC = $ccList', ({ ccList, expectedCCList }) => {
const mailto = `mailto:${address3}?subject=${subject}&cc=${ccList}`;
const { data } = mailtoParser(mailto);
expect(data?.CCList).toEqual(expectedCCList);
});
it.each`
bccList | expectedBCCList
${address1} | ${[{ Name: address1, Address: address1 }]}
${`${address1},${address2}`} | ${[{ Name: address1, Address: address1 }, { Name: address2, Address: address2 }]}
${`${addressName1} <${address1}>`} | ${[{ Name: addressName1, Address: address1 }]}
${`${addressName1} <${address1}>, ${addressName2} <${address2}>`} | ${[{ Name: addressName1, Address: address1 }, { Name: addressName2, Address: address2 }]}
${`address${htmlEntity}1@pm.me`} | ${[{ Name: address1, Address: address1 }]}
`('should detect the BCC list in a mailto string with BCC = $bccList', ({ bccList, expectedBCCList }) => {
const mailto = `mailto:${address3}?subject=${subject}&bcc=${bccList}`;
const { data } = mailtoParser(mailto);
expect(data?.BCCList).toEqual(expectedBCCList);
});
it('should detect the subject in a mailto string', () => {
const mailto = `mailto:${address1}?subject=${subject}`;
const { data } = mailtoParser(mailto);
expect(data?.Subject).toEqual(subject);
});
it.each`
messageBody
${body}
${bodyWithImages}
`('should detect the body in a mailto string with Subject = $messagebody', ({ messageBody }) => {
const mailto = `mailto:${address1}?subject=${subject}&body=${messageBody}`;
const { decryption } = mailtoParser(mailto);
const decodedBody = decodeURIComponent(protonizer(messageBody, true).innerHTML);
expect(removeLineBreaks(decryption?.decryptedBody || '')).toEqual(removeLineBreaks(decodedBody));
});
it('should detect all fields in a mailto string', () => {
const mailto = `mailto:${address1}?subject=${subject}&cc=${address2},${address3}&bcc=${address4}&body=${body}`;
const { data, decryption } = mailtoParser(mailto);
const decodedBody = decodeURIComponent(protonizer(body, true).innerHTML);
expect(data?.ToList).toEqual([{ Name: address1, Address: address1 }]);
expect(data?.Subject).toEqual(subject);
expect(data?.CCList).toEqual([
{ Name: address2, Address: address2 },
{ Name: address3, Address: address3 },
]);
expect(data?.BCCList).toEqual([{ Name: address4, Address: address4 }]);
expect(removeLineBreaks(decryption?.decryptedBody || '')).toEqual(removeLineBreaks(decodedBody));
});
});
| 3,832
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/url.ts
|
import { Recipient } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { protonizer, sanitizeString } from '@proton/shared/lib/sanitize';
import { unescapeFromString } from '@proton/shared/lib/sanitize/escape';
import { MAILTO_PROTOCOL_HANDLER_PATH } from '../constants';
import { PartialMessageState } from '../logic/messages/messagesTypes';
/**
* Split an addresses string to a list of recipients
* @param emailsStr
*/
export const toAddresses = (emailsStr: string): Recipient[] => {
const emails = emailsStr.split(',');
// Remove potential unwanted HTML entities such as '­' from the address
const escaped = emails.map((email) => {
// Some HTML Entities might still be URI encoded at this point
const uriDecoded = decodeURIComponent(email);
return unescapeFromString(uriDecoded).trim();
});
return escaped.map((element) => {
// Search for elements with format "Name <Address>"
const nameAndAddressRegex = /([^<>]*)<(.*)>/g;
const findNameAndAddress = nameAndAddressRegex.exec(element);
// The first value of regex.exec is the entire match, but we want groups results
if (findNameAndAddress && findNameAndAddress.length === 3) {
return {
Name: sanitizeString(findNameAndAddress[1]).trim(),
Address: sanitizeString(findNameAndAddress[2]).trim(),
};
}
const sanitizedElement = sanitizeString(element).trim();
// Element is an address only
return { Name: sanitizedElement, Address: sanitizedElement };
});
};
/**
* Parse a mailto string
* @param Mailto string to parse
* @return Partial message formated from mailto string
*/
export const mailtoParser = (mailto: string): PartialMessageState => {
if (mailto.toLowerCase().indexOf('mailto:') !== 0) {
return {};
}
let j = mailto.indexOf('?');
// If no `?` detected
if (j < 0) {
j = mailto.length;
}
const to = mailto.substring(7, j);
const url = new URL(mailto);
const searchObject = {
subject: url.searchParams.get('subject'),
cc: url.searchParams.get('cc'),
bcc: url.searchParams.get('bcc'),
body: url.searchParams.get('body'),
};
const message: Partial<Message> = {};
let decryptedBody;
if (to) {
message.ToList = toAddresses(to);
}
if (searchObject.subject) {
message.Subject = decodeURIComponent(sanitizeString(searchObject.subject));
}
if (searchObject.cc) {
message.CCList = toAddresses(searchObject.cc);
}
if (searchObject.bcc) {
message.BCCList = toAddresses(searchObject.bcc);
}
if (searchObject.body) {
// use protonizer to replace src attributes to proton-src so that images are not loading without user approval
decryptedBody = decodeURIComponent(protonizer(searchObject.body, true).innerHTML);
}
return { data: message, decryption: { decryptedBody } };
};
export const registerMailToProtocolHandler = () => {
if ('registerProtocolHandler' in navigator) {
try {
navigator.registerProtocolHandler(
'mailto',
`${window.location.origin}${MAILTO_PROTOCOL_HANDLER_PATH}`,
// @ts-expect-error third arg is still recommended (cf. https://developer.mozilla.org/en-US/docs/Web/API/Navigator/registerProtocolHandler)
'ProtonMail'
);
} catch (e: any) {
console.error(e);
}
}
};
| 3,833
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/__mocks__/upload.ts
|
import { api } from '../test/api';
import { RequestParams, Upload } from '../upload';
export const upload = <T>(uid: string, paramsPromise: RequestParams | Promise<RequestParams>): Upload<T> => {
const asyncResolution = async () => {
const params = await paramsPromise;
return api(params);
};
return {
xhr: {} as XMLHttpRequest,
addProgressListener: jest.fn(),
abort: jest.fn(),
resultPromise: asyncResolution() as Promise<T>,
};
};
| 3,834
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/attachment.ts
|
import { ICAL_EXTENSIONS } from '@proton/shared/lib/calendar/constants';
import { KEY_EXTENSION } from '@proton/shared/lib/constants';
import { splitExtension } from '@proton/shared/lib/helpers/file';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { extractContentValue } from '@proton/shared/lib/mail/send/helpers';
import { MessageState } from '../../logic/messages/messagesTypes';
export const updateKeyPackets = (modelMessage: MessageState, syncedMessage: MessageState) => {
let changed = false;
const Attachments = modelMessage.data?.Attachments?.map((attachment) => {
const match = syncedMessage?.data?.Attachments.find(
(syncedAttachment) => attachment.ID === syncedAttachment.ID
);
if (match && attachment.KeyPackets !== match.KeyPackets) {
changed = true;
return { ...attachment, KeyPackets: match.KeyPackets };
}
return attachment;
});
return { changed, Attachments };
};
export const getPureAttachments = (attachments: Attachment[], isNumAttachmentsWithoutEmbedded: boolean) => {
// If the Feature flag is not set we need to return all attachments
if (!isNumAttachmentsWithoutEmbedded) {
return attachments;
}
return attachments.filter(({ Headers }) => {
// If the attachment disposition is inline and has the header content-id it's an embedded image
// In the attachment list, we want to hide embedded images so we need to filter them
if (Headers) {
const contentDisposition = extractContentValue(Headers['content-disposition']);
return Headers && !(contentDisposition === ATTACHMENT_DISPOSITION.INLINE && 'content-id' in Headers);
}
return true;
});
};
export const hasIcalExtension = (attachmentName: string) => ICAL_EXTENSIONS.includes(splitExtension(attachmentName)[1]);
export const hasKeyExtension = (attachmentName: string) => splitExtension(attachmentName)[1] === KEY_EXTENSION;
| 3,835
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/attachmentConverter.ts
|
import { MIMEAttachment, VERIFICATION_STATUS, WorkerDecryptionResult } from '@proton/crypto';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { ENCRYPTED_STATUS } from '../../constants';
// This prefix is really useful to distinguish 'real' attachments from pgp attachments.
export const ID_PREFIX = 'PGPAttachment';
export const getId = (message: Message, parsedAttachment: MIMEAttachment, number: number) =>
`${ID_PREFIX}_${message.ID}_${parsedAttachment.contentId}_${number}`;
/**
* Unfortunately mailparser doesn't expose header data directly so we will reconstruct the headers
*/
export const getHeaders = ({
fileName,
contentDisposition = '',
contentType = '',
headers: originalHeaders,
}: MIMEAttachment) => {
const headers: { [key: string]: any } = {};
const filenameOption = `; filename=${JSON.stringify(fileName)}`; // filename could have been generated, hence be missing from original headers
headers['content-disposition'] = contentDisposition + filenameOption;
// test if this is an assigned content id
if (originalHeaders['content-id'] && originalHeaders['content-id'].length > 0) {
headers['content-id'] = originalHeaders['content-id'][0];
}
if (contentDisposition.toLowerCase() === ATTACHMENT_DISPOSITION.INLINE) {
headers.embedded = 1;
}
headers['content-type'] = contentType + filenameOption;
return headers;
};
/**
* Convert a single attachment
*/
export const convertSingle = (
message: Message,
parsedAttachment: MIMEAttachment,
number: number,
verified: number, // TODO remove this variable?
onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void
): Attachment => {
const ID = getId(message, parsedAttachment, number);
const attachment: Attachment = {
ID,
Headers: getHeaders(parsedAttachment),
Name: parsedAttachment.fileName,
KeyPackets: null, // already decrypted;
MIMEType: parsedAttachment.contentType,
Size: parsedAttachment.size,
Encrypted: ENCRYPTED_STATUS.PGP_MIME,
};
const attachmentData: WorkerDecryptionResult<Uint8Array> = {
data: parsedAttachment.content,
filename: '',
signatures: [],
verified: VERIFICATION_STATUS.NOT_SIGNED,
};
onUpdateAttachment(ID, attachmentData /* , verified */);
// invalidSignature.askAgain(message, attachment, false);
return attachment;
};
/**
* Converts the parsedAttachment coming from mailparser to an attachment linked to the message provided.
*/
export const convert = (
message: Message,
attachments: MIMEAttachment[],
verified: number,
onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void
): Attachment[] => {
return attachments.map((attachment, number) =>
convertSingle(message, attachment, number, verified, onUpdateAttachment)
);
};
/**
* Considering a Attachment[], will return as is the common attachments
* But remove from the list and convert the pgp ones by files to upload
*/
export const convertToFile = (
attachments: Attachment[],
getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined
) => {
return attachments.reduce<[Attachment[], File[]]>(
(acc, attachment) => {
if (attachment.ID?.startsWith(ID_PREFIX)) {
const attachmentData = getAttachment(attachment.ID as string)?.data;
if (attachmentData) {
acc[1].push(new File([attachmentData], attachment.Name || '', { type: attachment.MIMEType }));
}
} else {
acc[0].push(attachment);
}
return acc;
},
[[], []]
);
};
| 3,836
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/attachmentDownloader.ts
|
import JSZip from 'jszip';
import type { WorkerDecryptionResult } from '@proton/crypto';
import { isFirefox } from '@proton/shared/lib/helpers/browser';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { splitExtension } from '@proton/shared/lib/helpers/file';
import { Api } from '@proton/shared/lib/interfaces';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import { MessageKeys, MessageVerification } from '../../logic/messages/messagesTypes';
import { getAndVerify } from './attachmentLoader';
export interface Download {
attachment: Attachment;
data: Uint8Array;
isError?: boolean;
verified: VERIFICATION_STATUS;
}
/**
* Format attachment for the download
*/
export const formatDownload = async (
attachment: Attachment,
verification: MessageVerification | undefined,
messageKeys: MessageKeys,
onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void,
api: Api,
getAttachment?: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined,
messageFlags?: number
): Promise<Download> => {
try {
const { data, verified } = await getAndVerify(
attachment,
verification,
messageKeys,
api,
getAttachment,
onUpdateAttachment,
messageFlags
);
return {
attachment,
data: data as Uint8Array,
verified,
};
} catch (error: any) {
// If the decryption fails we download the encrypted version
if (error.data) {
return {
attachment: {
Name: `${attachment.Name}.pgp`,
MIMEType: 'application/pgp-encrypted',
ID: attachment.ID,
},
data: error.binary,
isError: true,
verified: VERIFICATION_STATUS.NOT_VERIFIED,
};
}
throw error;
}
};
/**
* Generate a download for an attachment
*/
export const generateDownload = async (download: Download /* , message: MessageExtended */) => {
let mimeType = download.attachment.MIMEType;
// Since version 98, PDF are opened instead of being downloaded in Firefox
// One workaround is to use the type application/octet-stream
if (isFirefox()) {
mimeType = 'application/octet-stream';
}
downloadFile(new Blob([download.data], { type: mimeType }), download.attachment.Name);
};
/**
* The attachment's Name is not unique we need a unique name in order to make the zip.
* The lib doesn't allow duplicates
*/
export const formatDownloadAll = async (
attachments: Attachment[],
verification: MessageVerification | undefined,
messageKeys: MessageKeys,
onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void,
api: Api,
getAttachment?: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined,
messageFlags?: number
): Promise<Download[]> => {
const { list }: { list: Attachment[] } = attachments.reduce(
(acc: any, att) => {
const name = att.Name || '';
if (!acc.map[name]) {
acc.map[name] = { index: 0 };
} else {
acc.map[name].index++;
const [fileName, ext] = splitExtension(name);
const newName = `${fileName} (${acc.map[name].index}).${ext}`;
const updatedAttachment = { ...att, Name: newName };
acc.list.push(updatedAttachment);
return acc;
}
acc.list.push(att);
return acc;
},
{ list: [], map: {} }
);
return Promise.all(
list.map((att) =>
formatDownload(att, verification, messageKeys, onUpdateAttachment, api, getAttachment, messageFlags)
)
);
};
export const getZipAttachmentName = (message: Pick<Message, 'Subject'>) => `Attachments-${message.Subject}.zip`;
/**
* Zip and trigger download of a list of download objects
*/
export const generateDownloadAll = async (message: Pick<Message, 'Subject'>, list: Download[]) => {
const zip = new JSZip();
list.forEach(({ attachment: { Name = '' }, data }) => zip.file(Name, data));
const content = await zip.generateAsync({ type: 'blob' });
const name = getZipAttachmentName(message);
downloadFile(content, name);
};
| 3,837
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/attachmentLoader.ts
|
import { CryptoProxy, PublicKeyReference, SessionKey, WorkerDecryptionResult } from '@proton/crypto';
import { binaryStringToArray, decodeBase64 } from '@proton/crypto/lib/utils';
import { getAttachment } from '@proton/shared/lib/api/attachments';
import { getEOAttachment } from '@proton/shared/lib/api/eo';
import { Api } from '@proton/shared/lib/interfaces';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import { getEOSessionKey, getSessionKey } from '@proton/shared/lib/mail/send/attachments';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
import { MessageKeys, MessageVerification } from '../../logic/messages/messagesTypes';
export const getVerificationStatusFromKeys = (
decryptedAttachment: WorkerDecryptionResult<Uint8Array>,
verifyingKeys: PublicKeyReference[]
) => {
return verifyingKeys.length > 0 ? decryptedAttachment.verified : VERIFICATION_STATUS.NOT_VERIFIED;
};
// Reference: Angular/src/app/attachments/services/AttachmentLoader.js
export const decryptAndVerify = async (
encryptedBinaryBuffer: ArrayBuffer,
sessionKey: SessionKey,
signature?: string,
publicKeys?: PublicKeyReference | PublicKeyReference[],
encSignature?: string
): Promise<WorkerDecryptionResult<Uint8Array>> => {
const encryptedBinary = new Uint8Array(encryptedBinaryBuffer);
try {
return await CryptoProxy.decryptMessage({
binaryMessage: encryptedBinary,
sessionKeys: [sessionKey],
armoredSignature: signature,
armoredEncryptedSignature: encSignature,
verificationKeys: publicKeys,
format: 'binary',
});
} catch (err: any) {
console.error(err);
throw err;
}
};
export const getRequest = ({ ID = '' }: Attachment = {}, api: Api, messageKeys: MessageKeys): Promise<ArrayBuffer> => {
if (messageKeys.type === 'outside') {
return api(getEOAttachment(ID, messageKeys.decryptedToken, messageKeys.id));
}
return api(getAttachment(ID));
};
export const getDecryptedAttachment = async (
attachment: Attachment,
verification: MessageVerification | undefined,
messageKeys: MessageKeys,
api: Api,
messageFlags?: number
): Promise<WorkerDecryptionResult<Uint8Array>> => {
const isOutside = messageKeys.type === 'outside';
const encryptedBinary = await getRequest(attachment, api, messageKeys);
try {
if (!isOutside) {
const sessionKey = await getSessionKey(attachment, messageKeys.privateKeys, messageFlags);
const decryptedAttachment = await decryptAndVerify(
encryptedBinary,
sessionKey,
attachment.Signature,
verification?.verifyingKeys
);
const verified = getVerificationStatusFromKeys(decryptedAttachment, verification?.verifyingKeys || []);
return {
...decryptedAttachment,
verified,
} as WorkerDecryptionResult<Uint8Array>;
}
const sessionKey = await getEOSessionKey(attachment, messageKeys.password);
// eslint-disable-next-line @typescript-eslint/return-await
return await CryptoProxy.decryptMessage({
// a promise is returned here, just not detected properly by TS
binaryMessage: new Uint8Array(encryptedBinary),
passwords: [messageKeys.password],
format: 'binary',
sessionKeys: [sessionKey],
});
} catch (error: any) {
const blob = mergeUint8Arrays([
binaryStringToArray(decodeBase64(attachment.KeyPackets) || ''),
new Uint8Array(encryptedBinary),
]);
// Fallback download raw attachment
const newError = new Error('Attachment decryption error');
Object.assign(newError, { data: attachment, binary: blob, error });
throw newError;
}
};
export const getAndVerify = async (
attachment: Attachment = {},
verification: MessageVerification | undefined,
messageKeys: MessageKeys,
api: Api,
getAttachment?: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined,
onUpdateAttachment?: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void,
messageFlags?: number
): Promise<WorkerDecryptionResult<Uint8Array>> => {
const isOutside = messageKeys.type === 'outside';
let attachmentdata: WorkerDecryptionResult<Uint8Array>;
const attachmentID = attachment.ID || '';
if (attachment.Preview) {
return {
data: attachment.Preview,
filename: 'preview',
signatures: [],
verified: VERIFICATION_STATUS.NOT_SIGNED,
} as WorkerDecryptionResult<Uint8Array>;
}
if (!isOutside && getAttachment && onUpdateAttachment) {
const attachmentInState = getAttachment(attachmentID);
if (attachmentInState) {
attachmentdata = attachmentInState;
} else {
attachmentdata = await getDecryptedAttachment(attachment, verification, messageKeys, api, messageFlags);
}
onUpdateAttachment(attachmentID, attachmentdata);
} else {
attachmentdata = await getDecryptedAttachment(attachment, verification, messageKeys, api, messageFlags);
}
return attachmentdata;
};
export const get = (
attachment: Attachment = {},
verification: MessageVerification | undefined,
messageKeys: MessageKeys,
api: Api,
getAttachment?: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined,
onUpdateAttachment?: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void,
messageFlags?: number
): Promise<WorkerDecryptionResult<Uint8Array>> => {
return getAndVerify(attachment, verification, messageKeys, api, getAttachment, onUpdateAttachment, messageFlags);
};
| 3,838
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/attachmentThumbnails.ts
|
import { MAILBOX_LABEL_IDS, MIME_TYPES } from '@proton/shared/lib/constants';
import { AttachmentsMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import isTruthy from '@proton/utils/isTruthy';
import { hasIcalExtension, hasKeyExtension } from 'proton-mail/helpers/attachment/attachment';
import { hasLabel } from 'proton-mail/helpers/elements';
import { Element } from 'proton-mail/models/element';
const { SPAM } = MAILBOX_LABEL_IDS;
const ATTACHMENT_THUMBNAILS_BLOCK_LIST: string[] = [MIME_TYPES.ICS, MIME_TYPES.APPLICATION_ICS, MIME_TYPES.PGP_KEYS];
export const canShowAttachmentThumbnails = (
isCompactView: boolean,
element: Element,
attachmentMetadata: AttachmentsMetadata[],
canSeeThumbnailsFeature?: boolean
) => {
if (!!canSeeThumbnailsFeature) {
// Do not show attachments for SPAM elements to protect the user
const isSpam = hasLabel(element, SPAM);
const hasAttachmentsMetadata = attachmentMetadata.length > 0;
return !isSpam && !isCompactView && hasAttachmentsMetadata;
}
return false;
};
export const getOtherAttachmentsTitle = (attachmentsMetadata: AttachmentsMetadata[], maxAttachment: number) => {
return attachmentsMetadata
.map((metadata, index) => {
return index < maxAttachment ? '' : metadata.Name;
})
.filter(isTruthy)
.join(', ');
};
export const filterAttachmentToPreview = (attachmentsMetadata: AttachmentsMetadata[]) => {
// Check file MimeType to filter attachments
// It's possible that the file has not the MimeType we want to exclude, so we make an additional check on the extension
return attachmentsMetadata.filter(
(attachmentMetadata) =>
!ATTACHMENT_THUMBNAILS_BLOCK_LIST.includes(attachmentMetadata.MIMEType) &&
!hasIcalExtension(attachmentMetadata.Name) &&
!hasKeyExtension(attachmentMetadata.Name)
);
};
| 3,839
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/attachmentUploader.ts
|
import { c } from 'ttag';
import { PrivateKeyReference, PublicKeyReference } from '@proton/crypto';
import { uploadAttachment } from '@proton/shared/lib/api/attachments';
import { readFileAsBuffer } from '@proton/shared/lib/helpers/file';
import generateUID from '@proton/shared/lib/helpers/generateUID';
import { generateProtonWebUID } from '@proton/shared/lib/helpers/uid';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { Packets } from '@proton/shared/lib/interfaces/mail/crypto';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { getAttachments } from '@proton/shared/lib/mail/messages';
import { encryptAttachment } from '@proton/shared/lib/mail/send/attachments';
import {
ATTACHMENT_MAX_SIZE,
MESSAGE_ALREADY_SENT_INTERNAL_ERROR,
UPLOAD_ATTACHMENT_ERROR_CODES,
} from '../../constants';
import { MessageState, MessageStateWithData, PublicPrivateKey } from '../../logic/messages/messagesTypes';
import { generateCid, isEmbeddable } from '../message/messageEmbeddeds';
import { RequestParams, Upload, upload as uploadHelper } from '../upload';
// Reference: Angular/src/app/attachments/factories/attachmentModel.js
type UploadQueryResult = Promise<{
Code: number;
Attachment: Attachment;
Error?: string;
}>;
export interface UploadResult {
attachment: Attachment;
packets: Packets;
addressID: string; // The addressID used to encrypt packets
}
/**
* Read the file locally, and encrypt it. return the encrypted file.
*/
export const encryptFile = async (
file: File,
inline: boolean,
pubKeys: PublicKeyReference[],
privKey?: PrivateKeyReference[]
) => {
if (!file) {
throw new TypeError(c('Error').t`You did not provide a file.`);
}
try {
const result = await readFileAsBuffer(file);
return await encryptAttachment(new Uint8Array(result), file, inline, pubKeys, privKey);
} catch (e: any) {
throw new Error(c('Error').t`Failed to encrypt attachment. Please try again.`);
}
};
/**
* Add a new attachment, upload it to the server
*/
const uploadFile = (
file: File,
message: MessageStateWithData,
messageKeys: PublicPrivateKey,
inline: boolean,
uid: string,
cid = ''
): Upload<UploadResult> => {
const titleImage = c('Title').t`Image`;
const filename = file.name || `${titleImage} ${getAttachments(message.data).length + 1}`;
const ContentID = inline ? cid || generateCid(generateProtonWebUID(), message.data?.Sender?.Address || '') : '';
const publicKeys = messageKeys.publicKeys && messageKeys.publicKeys.length > 0 ? [messageKeys.publicKeys[0]] : [];
const privateKeys =
messageKeys.privateKeys && messageKeys.privateKeys.length > 0 ? [messageKeys.privateKeys[0]] : [];
let packets: Packets;
const getParams = async () => {
packets = await encryptFile(file, inline, publicKeys, privateKeys);
return uploadAttachment({
Filename: packets.Filename || filename,
MessageID: message.data.ID,
ContentID,
MIMEType: packets.MIMEType,
KeyPackets: new Blob([packets.keys]),
DataPacket: new Blob([packets.data]),
Signature: packets.signature ? new Blob([packets.signature]) : undefined,
}) as RequestParams;
};
const upload = uploadHelper(uid, getParams()) as Upload<UploadQueryResult>;
const attachPackets = async () => {
const result = await upload.resultPromise;
if (result?.Code === UPLOAD_ATTACHMENT_ERROR_CODES.MESSAGE_ALREADY_SENT) {
throw new Error(MESSAGE_ALREADY_SENT_INTERNAL_ERROR);
}
return { attachment: result.Attachment, packets, addressID: message.data.AddressID };
};
return {
...upload,
resultPromise: attachPackets(),
};
};
const buildHeaders = ({ Inline }: Packets, message: MessageStateWithData) => {
if (!Inline) {
return {};
}
const cid = generateCid(generateProtonWebUID(), message.data?.Sender?.Address || '');
return {
'content-disposition': ATTACHMENT_DISPOSITION.INLINE,
'content-id': cid,
};
};
const packetToAttachment = (packet: Packets, message: MessageStateWithData) => {
return {
ID: generateUID('att'),
Name: packet.Filename,
Size: packet.FileSize,
MIMEType: packet.MIMEType,
KeyPackets: new Blob([packet.keys]),
DataPacket: new Blob([packet.data]),
Preview: packet.Preview,
Headers: buildHeaders(packet, message),
};
};
/**
* Add a new EO attachment
*/
const uploadEOFile = (
file: File,
message: MessageStateWithData,
publicKeys: PublicKeyReference[],
inline: boolean
): Promise<{ attachment: Attachment; packets: Packets }> => {
const getAttachment = async () => {
const packets = (await encryptFile(file, inline, publicKeys)) as Packets;
return { attachment: packetToAttachment(packets, message) as Attachment, packets };
};
return getAttachment();
};
/**
* Upload a list of attachments [...File]
*/
export const upload = (
files: File[] = [],
message: MessageStateWithData,
messageKeys: PublicPrivateKey,
action = ATTACHMENT_DISPOSITION.ATTACHMENT,
uid: string,
cid = ''
): Upload<UploadResult>[] => {
return files.map((file) => {
const inline = isEmbeddable(file.type) && action === ATTACHMENT_DISPOSITION.INLINE;
return uploadFile(file, message, messageKeys, inline, uid, cid);
});
};
export const uploadEO = (
file: File,
message: MessageStateWithData,
publicKey: PublicKeyReference[],
action = ATTACHMENT_DISPOSITION.ATTACHMENT
) => {
const inline = isEmbeddable(file.type) && action === ATTACHMENT_DISPOSITION.INLINE;
return uploadEOFile(file, message, publicKey, inline);
};
/**
* Is current attachments plus eventual files to upload will exceed the max size
*/
const isSizeExceeded = (message: MessageState, files: File[] = []) => {
const attachments = getAttachments(message.data);
const attachmentsSize = attachments.reduce((acc, attachment) => acc + (attachment.Size || 0), 0);
const filesSize = files.reduce((acc, file) => acc + (file.size || 0), 0);
return attachmentsSize + filesSize > ATTACHMENT_MAX_SIZE;
};
/**
* Is current attachments plus eventual files to upload will exceed the max count
*/
const isCountExceeded = (message: MessageState, files: File[] = [], attachmentsLengthLimit: number) => {
const attachments = getAttachments(message.data);
const attachmentsCount = attachments.length + files.length;
return attachmentsCount > attachmentsLengthLimit;
};
interface CheckSizeAndLengthOptions {
createNotification: any;
message: MessageState;
files: File[];
pendingUploadFiles?: File[];
attachmentsCountLimit: number;
}
export const checkSizeAndLength = ({
createNotification,
message,
files,
pendingUploadFiles = [],
attachmentsCountLimit,
}: CheckSizeAndLengthOptions) => {
const totalFiles = [...files, ...pendingUploadFiles];
const sizeExcedeed = isSizeExceeded(message, totalFiles);
const countExceeded = isCountExceeded(message, totalFiles, attachmentsCountLimit);
if (countExceeded) {
/*
* translator: attachmentsCountLimit is the number of attachments maximum that we can have in a message
* Example : Maximum number of attachments (100) exceeded.
*/
createNotification({
type: 'error',
text: c('Error').t`Maximum number of attachments (${attachmentsCountLimit}) exceeded`,
});
}
if (sizeExcedeed) {
createNotification({
type: 'error',
text: c('Error').t`Attachments are limited to 25 MB`,
});
}
return sizeExcedeed || countExceeded;
};
| 3,840
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachmentConverter.test.ts
|
import { MIMEAttachment, WorkerDecryptionResult } from '@proton/crypto';
import { stringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { ENCRYPTED_STATUS } from '../../../constants';
import { ID_PREFIX, convert, convertSingle, convertToFile, getHeaders, getId } from '../attachmentConverter';
const fileName = 'fileName';
const messageID = 'messageID';
const contentID = 'contentID';
const contentDisposition = ATTACHMENT_DISPOSITION.INLINE;
const message = { ID: messageID } as Message;
const originalHeaders = {
'content-id': [contentID],
};
const attachmentSize = 222;
const mimeAttachment = {
contentId: contentID,
fileName,
contentDisposition,
contentType: '',
headers: originalHeaders,
size: attachmentSize,
content: stringToUint8Array('content'),
} as MIMEAttachment;
describe('getId', () => {
it('should return the expected attachment ID', function () {
const number = 1;
const parsedAttachment = { contentId: contentID } as MIMEAttachment;
const expected = `${ID_PREFIX}_${messageID}_${contentID}_${number}`;
expect(getId(message, parsedAttachment, number)).toEqual(expected);
});
});
describe('getHeaders', () => {
it('should return attachment headers', () => {
const expected = {
'content-disposition': `${contentDisposition}; filename="${fileName}"`,
'content-id': contentID,
'content-type': `; filename="${fileName}"`,
embedded: 1,
};
expect(getHeaders(mimeAttachment)).toEqual(expected);
});
});
describe('convertSingle', () => {
it('should convert a single parsed attachment to an attachment', () => {
const spy = jest.fn((ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => {
console.log(ID, attachment);
});
const attachment = convertSingle(message, mimeAttachment, 1, 0, spy);
const expectedAttachment = {
Encrypted: ENCRYPTED_STATUS.PGP_MIME,
ID: getId(message, mimeAttachment, 1),
Headers: {
'content-disposition': `${contentDisposition}; filename="${fileName}"`,
'content-id': contentID,
'content-type': `; filename="${fileName}"`,
embedded: 1,
},
Name: fileName,
KeyPackets: null,
MIMEType: '',
Size: attachmentSize,
};
expect(attachment).toEqual(expectedAttachment);
expect(spy).toHaveBeenCalled();
});
});
describe('convert', () => {
it('should convert multiple parsed attachments to attachment', function () {
const spy = jest.fn((ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => {
console.log(ID, attachment);
});
const mimeAttachment2 = {
contentId: `${contentID}-2`,
fileName: `${fileName}-2`,
contentDisposition,
contentType: '',
headers: originalHeaders,
size: attachmentSize,
content: stringToUint8Array('content-2'),
} as MIMEAttachment;
const attachments = convert(message, [mimeAttachment, mimeAttachment2], 0, spy);
const expectedAttachments = [
{
Encrypted: ENCRYPTED_STATUS.PGP_MIME,
ID: getId(message, mimeAttachment, 0),
Headers: {
'content-disposition': `${contentDisposition}; filename="${fileName}"`,
'content-id': contentID,
'content-type': `; filename="${fileName}"`,
embedded: 1,
},
Name: fileName,
KeyPackets: null,
MIMEType: '',
Size: attachmentSize,
},
{
Encrypted: ENCRYPTED_STATUS.PGP_MIME,
ID: getId(message, mimeAttachment2, 1),
Headers: {
'content-disposition': `${contentDisposition}; filename="${fileName}-2"`,
'content-id': contentID,
'content-type': `; filename="${fileName}-2"`,
embedded: 1,
},
Name: `${fileName}-2`,
KeyPackets: null,
MIMEType: '',
Size: attachmentSize,
},
];
expect(attachments).toEqual(expectedAttachments);
expect(spy).toHaveBeenCalledTimes(2);
});
});
describe('convertToFile', () => {
it('should return normal attachments and convert to file pgp attachments', () => {
const spy = jest.fn((ID: string) => {
return {
filename: 'attachment-2',
verified: 1,
data: stringToUint8Array(`content-${ID}`),
signatures: [stringToUint8Array(`content-${ID}`)],
} as WorkerDecryptionResult<Uint8Array>;
});
const attachments = [
{ ID: 'attachment-1' },
{
ID: `${ID_PREFIX}-attachment-2`,
Name: 'attachment-2',
MIMEType: 'attachment',
},
];
const expected = [{ ID: 'attachment-1' }];
const result = convertToFile(attachments, spy);
expect(result[0]).toEqual(expected);
expect(result[1][0].name).toEqual('attachment-2');
});
});
| 3,841
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachmentDownloader.test.ts
|
import { encodeBase64 } from '@proton/crypto/lib/utils';
import * as browser from '@proton/shared/lib/helpers/browser';
import * as downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { stringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import { MessageKeys, MessageVerification } from '../../../logic/messages/messagesTypes';
import { api } from '../../test/api';
import { GeneratedKey, generateKeys, releaseCryptoProxy, setupCryptoProxyForTesting } from '../../test/crypto';
import {
Download,
formatDownload,
formatDownloadAll,
generateDownload,
generateDownloadAll,
getZipAttachmentName,
} from '../attachmentDownloader';
const subject = 'Message subject';
const message = { Subject: subject };
const me = 'me@pm.me';
const attachmentName = 'Attachment Name';
const attachment1 = {
ID: '1',
Name: attachmentName,
Preview: stringToUint8Array('message preview'),
KeyPackets: encodeBase64('keypackets'),
} as Attachment;
const verification = {} as MessageVerification;
const getAttachment = jest.fn();
const onUpdateAttachment = jest.fn();
describe('formatDownload', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should format download', async () => {
const result = await formatDownload(
attachment1,
verification,
messageKeys,
api,
getAttachment,
onUpdateAttachment
);
expect(result.data).toBeDefined();
expect(result.attachment).toEqual(attachment1);
expect(result.verified).toEqual(VERIFICATION_STATUS.NOT_SIGNED);
});
it('should return an error while formatting download when attachment is broken', async () => {
const verificationWithError = {
verificationErrors: [{ message: 'there is an issue' }],
} as MessageVerification;
const result = await formatDownload(
{ ...attachment1, Preview: undefined },
verificationWithError,
messageKeys,
api,
getAttachment,
onUpdateAttachment
);
const expectedAttachment = {
Name: `${attachmentName}.pgp`,
MIMEType: 'application/pgp-encrypted',
ID: '1',
};
expect(result.attachment).toEqual(expectedAttachment);
expect(result.isError).toBeTruthy();
expect(result.verified).toEqual(VERIFICATION_STATUS.NOT_VERIFIED);
});
});
describe('generateDownload', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should generate a download', async () => {
const downloadFileSpy = jest.spyOn(downloadFile, 'default').mockReturnValue();
const download = {
attachment: {
Name: 'attachment1',
},
data: stringToUint8Array('download 1 data'),
verified: 1,
} as Download;
await generateDownload(download);
const downloadAll = downloadFileSpy.mock.calls[0];
expect(downloadFileSpy).toHaveBeenCalled();
// Check that the spy has been called with a blob of type zip and the correct filename
expect(downloadAll[1]).toEqual('attachment1');
});
it('should generate a download with the correct mimeType for firefox', async () => {
const downloadFileSpy = jest.spyOn(downloadFile, 'default').mockReturnValue();
jest.spyOn(browser, 'isFirefox').mockReturnValue(true);
const download = {
attachment: {
Name: 'attachment1',
},
data: stringToUint8Array('download 1 data'),
verified: 1,
} as Download;
await generateDownload(download);
const downloadAll = downloadFileSpy.mock.calls[0];
expect(downloadFileSpy).toHaveBeenCalled();
// Check that the spy has been called with a blob of type zip and the correct filename
expect(downloadAll[0]?.type).toEqual('application/octet-stream');
expect(downloadAll[1]).toEqual('attachment1');
});
});
describe('formatDownloadALl', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should format download all', async () => {
const result = await formatDownloadAll(
[attachment1],
verification,
messageKeys,
onUpdateAttachment,
api,
getAttachment
);
expect(result[0]?.data).toBeDefined();
expect(result[0]?.attachment).toEqual(attachment1);
expect(result[0]?.verified).toEqual(VERIFICATION_STATUS.NOT_SIGNED);
});
});
describe('getZipAttachmentName', () => {
it('should generate a zip name for attachments', () => {
expect(getZipAttachmentName(message)).toEqual(`Attachments-${subject}.zip`);
});
});
describe('generateDownloadAll', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should generate a download all', async () => {
const downloadFileSpy = jest.spyOn(downloadFile, 'default').mockReturnValue();
const downloads = [
{
attachment: {
Name: 'attachment1',
},
data: stringToUint8Array('download 1 data'),
verified: 1,
} as Download,
{
attachment: {
Name: 'attachment2',
},
data: stringToUint8Array('download 2 data'),
verified: 1,
} as Download,
];
await generateDownloadAll(message, downloads);
const downloadAll = downloadFileSpy.mock.calls[0];
expect(downloadFileSpy).toHaveBeenCalled();
// Check that the spy has been called with a blob of type zip and the correct filename
expect(downloadAll[0]?.type).toEqual('application/zip');
expect(downloadAll[1]).toEqual(`Attachments-${subject}.zip`);
});
});
| 3,842
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachmentLoader.test.ts
|
import { encodeBase64 } from '@proton/crypto/lib/utils';
import { stringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { MessageKeys, MessageVerification } from '../../../logic/messages/messagesTypes';
import { addApiMock, api } from '../../test/api';
import { GeneratedKey, generateKeys, releaseCryptoProxy, setupCryptoProxyForTesting } from '../../test/crypto';
import { get, getAndVerify, getDecryptedAttachment, getRequest } from '../attachmentLoader';
const me = 'me@pm.me';
const attachmentID = 'attachmentID';
const attachmentName = 'attachmentName';
const attachmentMimeType = 'application/pdf';
const attachment1 = {
ID: attachmentID,
Name: attachmentName,
Preview: stringToUint8Array('message preview'),
KeyPackets: encodeBase64('keypackets'),
MIMEType: attachmentMimeType,
} as Attachment;
const outsideMessageKeys = {
type: 'outside',
password: 'password',
id: 'id',
decryptedToken: 'token',
} as MessageKeys;
// TODO Test decrypt function
describe('getRequest', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should make an api request for a normal attachment', async () => {
const spy = jest.fn();
addApiMock(`mail/v4/attachments/${attachmentID}`, spy, 'get');
await getRequest({ ID: attachmentID }, api, messageKeys);
expect(spy).toHaveBeenCalled();
});
it('should make an api request for a EO attachment', async () => {
const spy = jest.fn();
addApiMock(`mail/v4/eo/attachment/${attachmentID}`, spy, 'get');
await getRequest({ ID: attachmentID }, api, outsideMessageKeys);
expect(spy).toHaveBeenCalled();
});
});
describe('getDecryptedAttachment', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
// TODO Need to test case where we get the decrypted attachment, for normal and EO attachments
it('should throw an error when the attachment is broken', async () => {
addApiMock(`mail/v4/attachments/${attachmentID}`, jest.fn(), 'get');
const verificationWithError = {
verificationErrors: [{ message: 'there is an issue' }],
} as MessageVerification;
const result = getDecryptedAttachment(attachment1, verificationWithError, messageKeys, api);
expect(result).rejects.toThrow('Attachment decryption error');
});
});
describe('getAndVerify', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
const getAttachment = jest.fn();
const onUpdateAttachment = jest.fn();
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should return the attachment Preview', async () => {
const result = await getAndVerify(
attachment1,
{} as MessageVerification,
messageKeys,
api,
getAttachment,
onUpdateAttachment
);
expect(result.filename).toEqual('preview');
});
// TODO need to test case where we can get the attachment, for normal and EO attachments
});
describe('get + reverify', () => {
let toKeys: GeneratedKey;
let messageKeys: MessageKeys;
const getAttachment = jest.fn();
const onUpdateAttachment = jest.fn();
beforeAll(async () => {
await setupCryptoProxyForTesting();
toKeys = await generateKeys('me', me);
messageKeys = {
type: 'publicPrivate',
publicKeys: toKeys.publicKeys,
privateKeys: toKeys.privateKeys,
};
});
afterAll(async () => {
await releaseCryptoProxy();
});
it('should get the attachment', async () => {
const getResult = await get(
attachment1,
{} as MessageVerification,
messageKeys,
api,
getAttachment,
onUpdateAttachment
);
expect(getResult.filename).toEqual('preview');
});
});
| 3,843
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachmentThumbnails.test.ts
|
import { MAILBOX_LABEL_IDS, MIME_TYPES } from '@proton/shared/lib/constants';
import { AttachmentsMetadata, Message } from '@proton/shared/lib/interfaces/mail/Message';
import {
canShowAttachmentThumbnails,
filterAttachmentToPreview,
getOtherAttachmentsTitle,
} from 'proton-mail/helpers/attachment/attachmentThumbnails';
import { Conversation } from 'proton-mail/models/conversation';
const { SPAM, INBOX } = MAILBOX_LABEL_IDS;
const getConversation = (isSpam = false) => {
return {
AttachmentsMetadata: [
{ ID: '1' } as AttachmentsMetadata,
{ ID: '2' } as AttachmentsMetadata,
] as AttachmentsMetadata[],
Labels: isSpam ? [{ ID: SPAM }] : [{ ID: INBOX }],
} as Conversation;
};
const getMessage = (isSpam = false) => {
return {
AttachmentsMetadata: [
{ ID: '1' } as AttachmentsMetadata,
{ ID: '2' } as AttachmentsMetadata,
] as AttachmentsMetadata[],
LabelIDs: isSpam ? [SPAM] : [INBOX],
ConversationID: 'conversationID',
} as Message;
};
const attachmentsMetadata = [{ ID: '1' } as AttachmentsMetadata];
describe('attachmentThumbnails', () => {
describe('canShowAttachmentThumbnails', () => {
it('should show attachment thumbnails', () => {
expect(canShowAttachmentThumbnails(false, getConversation(), attachmentsMetadata, true)).toBeTruthy();
expect(canShowAttachmentThumbnails(false, getMessage(), attachmentsMetadata, true)).toBeTruthy();
});
it('should not show attachment thumbnails when feature flag is off', () => {
expect(canShowAttachmentThumbnails(false, getConversation(), attachmentsMetadata, false)).toBeFalsy();
expect(canShowAttachmentThumbnails(false, getMessage(), attachmentsMetadata, false)).toBeFalsy();
});
it('should not show attachment thumbnails on compact view', () => {
expect(canShowAttachmentThumbnails(true, getConversation(), attachmentsMetadata, true)).toBeFalsy();
expect(canShowAttachmentThumbnails(true, getMessage(), attachmentsMetadata, true)).toBeFalsy();
});
it('should not show attachment thumbnails when no attachment metadata is attached to the element', () => {
expect(canShowAttachmentThumbnails(false, {} as Conversation, [], true)).toBeFalsy();
expect(canShowAttachmentThumbnails(false, {} as Message, [], true)).toBeFalsy();
});
it('should not show attachment thumbnails when element is in SPAM', () => {
expect(canShowAttachmentThumbnails(false, getConversation(true), attachmentsMetadata, true)).toBeFalsy();
expect(canShowAttachmentThumbnails(false, getMessage(true), attachmentsMetadata, true)).toBeFalsy();
});
});
describe('getOtherAttachmentsTitle', () => {
const attachmentMetadata = [
{ ID: '1', Name: 'attachment1.png' } as AttachmentsMetadata,
{ ID: '2', Name: 'attachment2.jpg' } as AttachmentsMetadata,
{ ID: '3', Name: 'attachment3.pdf' } as AttachmentsMetadata,
{ ID: '4', Name: 'attachment4.txt' } as AttachmentsMetadata,
] as AttachmentsMetadata[];
it('should return the expected title', () => {
const res = getOtherAttachmentsTitle(attachmentMetadata, 2);
expect(res).toEqual('attachment3.pdf, attachment4.txt');
});
});
describe('filterAttachmentToPreview', () => {
it('should filter attachments correctly', () => {
const pdfAttachment = {
MIMEType: 'application/pdf',
} as AttachmentsMetadata;
const imageAttachment = {
MIMEType: 'image/png',
} as AttachmentsMetadata;
const attachmentsMetada: AttachmentsMetadata[] = [
{ MIMEType: MIME_TYPES.ICS } as AttachmentsMetadata,
{ MIMEType: MIME_TYPES.APPLICATION_ICS } as AttachmentsMetadata,
{ MIMEType: MIME_TYPES.PGP_KEYS } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.ics' } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.ical' } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.ifb' } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.icalendar' } as AttachmentsMetadata,
{ MIMEType: 'whatever', Name: 'attachment.asc' } as AttachmentsMetadata,
pdfAttachment,
imageAttachment,
];
const expected: AttachmentsMetadata[] = [pdfAttachment, imageAttachment];
expect(filterAttachmentToPreview(attachmentsMetada)).toEqual(expected);
});
});
});
| 3,844
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/attachment/test/attachments.test.ts
|
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { getPureAttachments, updateKeyPackets } from '../attachment';
describe('updateKeyPackets', () => {
const attachments = [
{
ID: 'attachment-1',
KeyPackets: 'random-key-packet-1',
},
];
const modelMessage = {
localID: 'modelMessage',
data: {
Attachments: attachments,
},
} as MessageState;
it('should update attachment key packets', () => {
const expectedAttachments = [
{
ID: 'attachment-1',
KeyPackets: 'different-key-packet',
},
];
const syncedMessage = {
localID: 'syncedMessage',
data: {
Attachments: expectedAttachments,
},
} as MessageState;
const { changed, Attachments } = updateKeyPackets(modelMessage, syncedMessage);
expect(changed).toBeTruthy();
expect(Attachments).toEqual(expectedAttachments);
});
it('should not update KeyPackets when attachments are up to date', function () {
const { changed, Attachments } = updateKeyPackets(modelMessage, modelMessage);
expect(changed).toBeFalsy();
expect(Attachments).toEqual(attachments);
});
});
describe('getPureAttachments', () => {
const attachments = [
{
Name: 'normal attachment',
Headers: {
'content-disposition': ATTACHMENT_DISPOSITION.ATTACHMENT,
},
} as Attachment,
{
Name: 'invalid inline image',
Headers: {
'content-disposition': ATTACHMENT_DISPOSITION.INLINE,
},
} as Attachment,
{
Name: 'inline image',
Headers: {
'content-disposition': ATTACHMENT_DISPOSITION.INLINE,
'content-id': 'content-id',
},
} as Attachment,
] as Attachment[];
it('should return all attachments when embedded images must displayed', () => {
expect(getPureAttachments(attachments, false)).toEqual(attachments);
});
it('should return only pure attachments when embedded images are hidden', () => {
expect(getPureAttachments(attachments, true)).toEqual([...attachments.slice(0, 2)]);
});
});
| 3,845
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/calendar/emailReminder.ts
|
import { SECOND } from '@proton/shared/lib/constants';
import { fromUTCDate, toLocalDate } from '@proton/shared/lib/date/timezone';
import { CalendarEvent } from '@proton/shared/lib/interfaces/calendar';
export const getEventLocalStartEndDates = (event: CalendarEvent, occurrenceTimestamp: number) => {
const { StartTime, EndTime, FullDay } = event;
const isAllDay = !!FullDay;
const duration = (EndTime - StartTime) * SECOND;
const startUtcDate = new Date(occurrenceTimestamp * SECOND);
const startDate = isAllDay ? toLocalDate(fromUTCDate(startUtcDate)) : startUtcDate;
return [startDate, new Date(+startDate + duration)];
};
| 3,846
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/calendar/invite.test.ts
|
import { generateAttendeeToken } from '@proton/shared/lib/calendar/attendees';
import { ICAL_ATTENDEE_RSVP, ICAL_ATTENDEE_STATUS, ICAL_METHOD } from '@proton/shared/lib/calendar/constants';
import { generateVeventHashUID } from '@proton/shared/lib/calendar/helper';
import {
EVENT_INVITATION_ERROR_TYPE,
EventInvitationError,
} from '@proton/shared/lib/calendar/icsSurgery/EventInvitationError';
import { getIsRruleSupported } from '@proton/shared/lib/calendar/recurrence/rrule';
import { parse } from '@proton/shared/lib/calendar/vcal';
import { getIsTimezoneComponent } from '@proton/shared/lib/calendar/vcalHelper';
import { Recipient } from '@proton/shared/lib/interfaces';
import { Attendee, CalendarEvent, Participant } from '@proton/shared/lib/interfaces/calendar';
import { VcalVcalendar, VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { RequireSome } from '@proton/shared/lib/interfaces/utils';
import { MessageStateWithData } from 'proton-mail/logic/messages/messagesTypes';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../test/crypto';
import { EventInvitation, getIsPartyCrasher, getSupportedEventInvitation, parseVcalendar } from './invite';
describe('Invitations', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
describe('getIsRruleSupported for invitations', () => {
test('should accept events with daily recurring rules valid for invitations', () => {
const vevents = [
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;UNTIL=20200330T150000Z;INTERVAL=100;BYMONTH=3\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;INTERVAL=2;BYSECOND=30;BYMINUTE=5,10,15;BYHOUR=10\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;INTERVAL=2;BYWEEKNO=13;COUNT=499;WKST=TH\r\nEND:VEVENT`,
];
const rrules = vevents.map((vevent) => {
const parsedVevent = parse(vevent) as RequireSome<VcalVeventComponent, 'rrule'>;
return parsedVevent.rrule.value;
});
expect(rrules.map((rrule) => getIsRruleSupported(rrule, true))).toEqual(vevents.map(() => true));
});
test('should refuse events with invalid daily recurring rules', () => {
const vevents = [
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;COUNT=500\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=DAILY;INTERVAL=1000;BYMONTHDAY=11,22\r\nEND:VEVENT`,
];
const rrules = vevents.map((vevent) => {
const parsedVevent = parse(vevent) as RequireSome<VcalVeventComponent, 'rrule'>;
return parsedVevent.rrule.value;
});
expect(rrules.map((rrule) => getIsRruleSupported(rrule, true))).toEqual(vevents.map(() => false));
});
test('should accept events with yearly recurring rules valid for invitations', () => {
const vevents = [
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;UNTIL=20200330T150000Z;INTERVAL=1;BYDAY=MO,SU,TH;BYMONTHDAY=30,31;BYMONTH=3\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=2;BYSECOND=30;BYHOUR=10;BYMONTH=5\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=2;BYMONTH=3;BYMONTHDAY=17,22;COUNT=499\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=2TU;BYMONTH=7\r\nEND:VEVENT`,
];
const rrules = vevents.map((vevent) => {
const parsedVevent = parse(vevent) as RequireSome<VcalVeventComponent, 'rrule'>;
return parsedVevent.rrule.value;
});
expect(rrules.map((rrule) => getIsRruleSupported(rrule, true))).toEqual(vevents.map(() => true));
});
test('should refuse events with invalid yearly recurring rules', () => {
const vevents = [
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;COUNT=500\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;INTERVAL=100;BYMONTHDAY=11,22\r\nEND:VEVENT`,
`BEGIN:VEVENT\r\nRRULE:FREQ=YEARLY;BYMONTHDAY=11\r\nEND:VEVENT`,
];
const rrules = vevents.map((vevent) => {
const parsedVevent = parse(vevent) as RequireSome<VcalVeventComponent, 'rrule'>;
return parsedVevent.rrule.value;
});
expect(rrules.map((rrule) => getIsRruleSupported(rrule, true))).toEqual(vevents.map(() => false));
});
});
describe('getSupportedEvent for invitations', () => {
test('should not import alarms for invites and keep recurrence id', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:REQUEST
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VTIMEZONE
TZID:/Europe/Vilnius
BEGIN:DAYLIGHT
TZOFFSETFROM:+0200
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
DTSTART:20030330T030000
TZNAME:EEST
TZOFFSETTO:+0300
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0300
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
DTSTART:20031026T040000
TZNAME:EET
TZOFFSETTO:+0200
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
TRANSP:OPAQUE
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200821T081914Z
SEQUENCE:1
CREATED:20200821T081842Z
DTSTART;TZID=Europe/Vilnius:20200915T090000
DTEND;TZID=Europe/Vilnius:20200915T100000
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
SUMMARY:Yearly single edit
RECURRENCE-ID;TZID=Europe/Vilnius:20220915T090000
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toMatchObject({
method: 'REQUEST',
vevent: {
component: 'vevent',
uid: { value: 'BA3017ED-889A-4BCB-B9CB-11CE30586021' },
dtstamp: {
value: { year: 2020, month: 8, day: 21, hours: 8, minutes: 19, seconds: 14, isUTC: true },
},
dtstart: {
value: { year: 2020, month: 9, day: 15, hours: 9, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Vilnius' },
},
dtend: {
value: { year: 2020, month: 9, day: 15, hours: 10, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Vilnius' },
},
'recurrence-id': {
value: { year: 2022, month: 9, day: 15, hours: 9, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Vilnius' },
},
},
vtimezone: parsedInvitation.components?.find((component) => getIsTimezoneComponent(component)),
originalVcalInvitation: parsedInvitation,
originalUniqueIdentifier: 'BA3017ED-889A-4BCB-B9CB-11CE30586021',
hasMultipleVevents: false,
fileName: 'test.ics',
});
});
test('should refuse invitations with inconsistent custom yearly recurrence rules', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:REQUEST
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VTIMEZONE
TZID:Europe/Vilnius
BEGIN:DAYLIGHT
TZOFFSETFROM:+0200
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
DTSTART:20030330T030000
TZNAME:EEST
TZOFFSETTO:+0300
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0300
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
DTSTART:20031026T040000
TZNAME:EET
TZOFFSETTO:+0200
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
DTEND;TZID=Europe/Vilnius:20200915T100000
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200821T081914Z
SEQUENCE:1
SUMMARY:Yearly custom 2
DTSTART;TZID=Europe/Vilnius:20200915T090000
X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
CREATED:20200821T081842Z
RRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=9;BYDAY=1TU
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).rejects.toMatchObject(
new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, {
method: ICAL_METHOD.REQUEST,
})
);
});
test('should refuse invitations with non-yearly recurrence rules that contain a byyearday', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
DTEND;TZID=Europe/Vilnius:20200915T100000
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200121T081914Z
SEQUENCE:1
SUMMARY:Non-yearly with byyearday
DTSTART;TZID=Europe/Vilnius:20200915T090000
X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
CREATED:20200821T081842Z
RRULE:FREQ=MONTHLY;INTERVAL=1;BYYEARDAY=21
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).rejects.toMatchObject(
new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, {
method: ICAL_METHOD.REQUEST,
})
);
});
test('should generate a hash UID for invitations with no method and drop alarms and recurrence id', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTAMP:19980309T231000Z
DTSTART;TZID=/mozilla.org/20050126_1/Europe/Brussels:20021231T203000
DTEND;TZID=/mozilla.org/20050126_1/Europe/Brussels:20030101T003000
RECURRENCE-ID;TZID=Europe/Brussels:20121231T203000
LOCATION:1CP Conference Room 4350
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toMatchObject({
method: 'PUBLISH',
vevent: {
component: 'vevent',
uid: { value: 'original-uid-test-event-sha1-uid-cba317c4bb79e20bdca567bf6dc80dfce145712b' },
dtstamp: {
value: { year: 1998, month: 3, day: 9, hours: 23, minutes: 10, seconds: 0, isUTC: true },
},
dtstart: {
value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Brussels' },
},
dtend: {
value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Brussels' },
},
},
originalVcalInvitation: parsedInvitation,
originalUniqueIdentifier: 'test-event',
hasMultipleVevents: false,
fileName: 'test.ics',
});
});
test('should generate a DTSTAMP from the message if no DTSTAMP was present', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTART;TZID=/mozilla.org/20050126_1/Europe/Brussels:20021231T203000
DTEND;TZID=/mozilla.org/20050126_1/Europe/Brussels:20030101T003000
LOCATION:1CP Conference Room 4350
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Date.UTC(2022, 9, 10, 10, 0, 0) / 1000 } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toEqual({
method: 'PUBLISH',
vevent: expect.objectContaining({
component: 'vevent',
uid: { value: 'original-uid-test-event-sha1-uid-1d92b0aa7fed011b07b53161798dfeb45cf4e186' },
dtstamp: {
value: { year: 2022, month: 10, day: 10, hours: 10, minutes: 0, seconds: 0, isUTC: true },
},
dtstart: {
value: { year: 2002, month: 12, day: 31, hours: 20, minutes: 30, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Brussels' },
},
dtend: {
value: { year: 2003, month: 1, day: 1, hours: 0, minutes: 30, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Brussels' },
},
sequence: { value: 0 },
}),
originalIcsHasNoOrganizer: false,
originalVcalInvitation: parsedInvitation,
originalUniqueIdentifier: 'test-event',
legacyUid: 'sha1-uid-1d92b0aa7fed011b07b53161798dfeb45cf4e186-original-uid-test-event',
hasMultipleVevents: false,
fileName: 'test.ics',
});
});
test('should not throw without version, untrimmed calscale and duration', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE: Gregorian
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTAMP:19980309T231000Z
DTSTART;VALUE=DATE:20021231
DURATION:PT2D
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).resolves.not.toThrow();
});
test('should throw for unknown calscales', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIANU
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
DTEND;TZID=Europe/Vilnius:20200915T100000
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200121T081914Z
SEQUENCE:1
SUMMARY:Non-yearly with byyearday
DTSTART;TZID=Europe/Vilnius:20200915T090000
X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
CREATED:20200821T081842Z
RRULE:FREQ=MONTHLY;INTERVAL=1;BYYEARDAY=21
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).rejects.toMatchObject(
new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED, {
method: ICAL_METHOD.REQUEST,
})
);
});
test('should not throw when receiving a VTIMEZONE without TZID', async () => {
const invitation = `BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
X-WR-TIMEZONE:Pacific/Niue
BEGIN:VTIMEZONE
X-LIC-LOCATION:Pacific/Niue
BEGIN:STANDARD
TZOFFSETFROM:-1100
TZOFFSETTO:-1100
TZNAME:-11
DTSTART:19700101T000000
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
DTSTART:20220403T153000Z
DTEND:20220403T163000Z
DTSTAMP:20220307T132207Z
ORGANIZER;CN=calendarregression@gmail.com:mailto:calendarregression@gmail.c
om
UID:0928j897bqah35i424dnvjdu3v12346465465@google.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;CN=calendar-user-pentest1@protonmail.com;X-NUM-GUESTS=0:mailto:calenda
r-user-pentest1@protonmail.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;CN=android@protonqa.xyz;X-NUM-GUESTS=0:mailto:android@protonqa.xyz
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE
;CN=calendarregression@gmail.com;X-NUM-GUESTS=0:mailto:calendarregression@g
mail.com
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;CN=visionary@lysenko.proton.black;X-NUM-GUESTS=0:mailto:visionary@lyse
nko.proton.black
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;CN=pro@lysenko.proton.black;X-NUM-GUESTS=0:mailto:pro@lysenko.proton.b
lack
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
TRUE;CN=plus@lysenko.proton.black;X-NUM-GUESTS=0:mailto:plus@lysenko.proton
.black
X-GOOGLE-CONFERENCE:https://meet.google.com/aey-yjac-rfe
X-MICROSOFT-CDO-OWNERAPPTID:-1984897430
CREATED:20220307T132206Z
DESCRIPTION:-::~:~::~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~
:~:~:~:~:~:~:~:~::~:~::-\\nDo not edit this section of the description.\\n\\nT
his event has a video call.\\nJoin: https://meet.google.com/aey-yjac-rfe\\n\\n
View your event at https://calendar.google.com/calendar/event?action=VIEW&e
id=MDkyOGo4OTdicWFoMzVpNDI0ZG52amR1M3YgcHJvQGx5c2Vua28ucHJvdG9uLmJsYWNr&tok
=MjgjY2FsZW5kYXJyZWdyZXNzaW9uQGdtYWlsLmNvbWM0MmE4NGNmZDY5NTBlYzliNzdlY2Q1N2
ZiNDcwYWFmNjc1YWY5NDE&ctz=Europe%2FVilnius&hl=en_GB&es=1.\\n-::~:~::~:~:~:~:
~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~:~::~:~::-
LAST-MODIFIED:20220307T132206Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Pacific / Niue (3)
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
await expect(
getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).resolves.not.toThrow();
});
test('should reformat break lines properly', async () => {
const invitation = `BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
DTSTART;VALUE=DATE:20220111
DTEND;VALUE=DATE:20220112
DTSTAMP:20210108T113223Z
ORGANIZER:mailto:orgo@protonmail.com
UID:case5544646879321797797898799
X-MICROSOFT-CDO-OWNERAPPTID:-1089749046
ATTENDEE;CN=att1@protonmail.com;CUTYPE=INDIVIDUAL;EMAIL=att1@protonmail.com;RSVP=TRUE;PARTSTAT=NEEDS-ACTION:/aMjk2MDIzMDQ4Mjk2MDI
zMIZjbeHD-pCEmJU6loV23jx6n2nXhXA9yXmtoE4a87979dmv46466/principal/
ATTENDEE;CN=att2@pm.me;CUTYPE=INDIVIDUAL;EMAIL=att2@pm.me;RSVP=TRUE;PARTSTAT=NEEDS-ACTION:/aMjk2MDIzMDQ4Mjk2MDI
zMIZjbeHD-pCEmJU6loV23jx6n2nXhXA9yXmtoE4ad7879mv67/principal/
CREATED:20210108T113222Z
DESCRIPTION:Extracting attendee
LAST-MODIFIED:20210108T113222Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Attendees - 6 invited apple 2
TRANSP:TRANSPARENT
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Math.round(Date.now() / 1000) } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toMatchObject({
method: 'REQUEST',
vevent: {
component: 'vevent',
uid: { value: 'case5544646879321797797898799' },
dtstamp: {
value: { year: 2021, month: 1, day: 8, hours: 11, minutes: 32, seconds: 23, isUTC: true },
},
dtstart: {
value: { year: 2022, month: 1, day: 11 },
parameters: { type: 'date' },
},
summary: { value: 'Attendees - 6 invited apple 2' },
description: { value: 'Extracting attendee' },
sequence: { value: 0 },
organizer: { value: 'mailto:orgo@protonmail.com' },
attendee: [
{
value: 'mailto:att1@protonmail.com',
parameters: {
cn: 'att1@protonmail.com',
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION,
},
},
{
value: 'mailto:att2@pm.me',
parameters: {
cn: 'att2@pm.me',
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION,
},
},
],
},
vtimezone: parsedInvitation.components?.find((component) => getIsTimezoneComponent(component)),
originalVcalInvitation: parsedInvitation,
originalUniqueIdentifier: 'case5544646879321797797898799',
hasMultipleVevents: false,
fileName: 'test.ics',
});
});
describe('should fix sequences out of bounds', () => {
test('if they are negative', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTART;TZID=/mozilla.org/20050126_1/Europe/Brussels:20021231T203000
DTEND;TZID=/mozilla.org/20050126_1/Europe/Brussels:20030101T003000
SEQUENCE:-1
LOCATION:1CP Conference Room 4350
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Date.UTC(2022, 9, 10, 10, 0, 0) / 1000 } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toEqual(
expect.objectContaining({
vevent: expect.objectContaining({
sequence: { value: 0 },
}),
})
);
});
test('if they are too big', async () => {
const invitation = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.13.6//EN
BEGIN:VEVENT
UID:test-event
DTSTART;TZID=/mozilla.org/20050126_1/Europe/Brussels:20021231T203000
DTEND;TZID=/mozilla.org/20050126_1/Europe/Brussels:20030101T003000
SEQUENCE:2205092022
LOCATION:1CP Conference Room 4350
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
TRANSP:OPAQUE
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
BEGIN:VALARM
TRIGGER:-PT15H
ACTION:DISPLAY
END:VALARM
BEGIN:VALARM
TRIGGER:-PT1W2D
ACTION:EMAIL
END:VALARM
END:VEVENT
END:VCALENDAR`;
const parsedInvitation = parseVcalendar(invitation) as VcalVcalendar;
const message = { Time: Date.UTC(2022, 9, 10, 10, 0, 0) / 1000 } as Message;
expect(
await getSupportedEventInvitation({
vcalComponent: parsedInvitation,
message,
icsBinaryString: invitation,
icsFileName: 'test.ics',
primaryTimezone: 'America/Sao_Paulo',
})
).toEqual(
expect.objectContaining({
vevent: expect.objectContaining({
sequence: { value: 57608374 },
}),
})
);
});
});
});
describe('getSupportedEventInvitation should guess a timezone to localize floating dates for invites', () => {
const generateVcalSetup = ({
method = ICAL_METHOD.REQUEST,
primaryTimezone = 'Asia/Seoul',
xWrTimezone = '',
vtimezonesTzids = [],
}: {
method?: ICAL_METHOD;
xWrTimezone?: string;
vtimezonesTzids?: string[];
primaryTimezone?: string;
}) => {
const xWrTimezoneString = xWrTimezone ? `X-WR-TIMEZONE:${xWrTimezone}` : '';
const vtimezonesString = vtimezonesTzids
.map(
(tzid) => `BEGIN:VTIMEZONE
TZID:${tzid}
END:VTIMEZONE`
)
.join('\n');
const vcal = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:${method}
${xWrTimezoneString}
${vtimezonesString}
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
DTSTART:20200915T090000
DTEND:20200915T100000
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
UID:BA3017ED-889A-4BCB-B9CB-11CE30586021
DTSTAMP:20200821T081914Z
SEQUENCE:1
SUMMARY:Floating date-time
RRULE:FREQ=DAILY;INTERVAL=2;COUNT=5
END:VEVENT
END:VCALENDAR`;
return {
vcalComponent: parse(vcal) as VcalVcalendar,
message: { Time: Math.round(Date.now() / 1000) } as Message,
icsBinaryString: vcal,
icsFileName: 'test.ics',
primaryTimezone,
};
};
const localizedVevent = (tzid: string) => ({
component: 'vevent',
uid: { value: 'BA3017ED-889A-4BCB-B9CB-11CE30586021' },
dtstamp: {
value: { year: 2020, month: 8, day: 21, hours: 8, minutes: 19, seconds: 14, isUTC: true },
},
dtstart: {
value: { year: 2020, month: 9, day: 15, hours: 9, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid },
},
dtend: {
value: { year: 2020, month: 9, day: 15, hours: 10, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid },
},
summary: { value: 'Floating date-time' },
sequence: { value: 1 },
rrule: { value: { freq: 'DAILY', interval: 2, count: 5 } },
organizer: {
value: 'mailto:aGmailOne@gmail.com',
parameters: { cn: 'testKrt' },
},
attendee: [
{
value: 'mailto:testme@pm.me',
parameters: {
partstat: 'NEEDS-ACTION',
rsvp: 'TRUE',
cn: 'testme@pm.me',
},
},
{
value: 'mailto:aGmailOne@gmail.com',
parameters: {
partstat: 'ACCEPTED',
cn: 'testKrt',
},
},
],
});
test('when there is both x-wr-timezone and single vtimezone (use x-wr-timezone)', async () => {
const { vevent } =
(await getSupportedEventInvitation(
generateVcalSetup({
xWrTimezone: 'Europe/Brussels',
vtimezonesTzids: ['America/New_York'],
})
)) || {};
expect(vevent).toEqual(localizedVevent('Europe/Brussels'));
});
test('when there is a single vtimezone and no x-wr-timezone', async () => {
const { vevent } =
(await getSupportedEventInvitation(
generateVcalSetup({
vtimezonesTzids: ['Europe/Vilnius'],
})
)) || {};
expect(vevent).toEqual(localizedVevent('Europe/Vilnius'));
});
test('when there is a single vtimezone and x-wr-timezone is not supported', async () => {
await expect(
getSupportedEventInvitation(
generateVcalSetup({
method: ICAL_METHOD.REPLY,
xWrTimezone: 'Moon/Tranquility',
vtimezonesTzids: ['Europe/Vilnius'],
})
)
).rejects.toThrowError('Unsupported response');
});
test('when there is no vtimezone nor x-wr-timezone (reject unsupported event)', async () => {
await expect(
getSupportedEventInvitation(
generateVcalSetup({
method: ICAL_METHOD.CANCEL,
})
)
).rejects.toThrowError('Unsupported invitation');
});
test('when there is no x-wr-timezone and more than one vtimezone (reject unsupported event)', async () => {
await expect(
getSupportedEventInvitation(
generateVcalSetup({
method: ICAL_METHOD.COUNTER,
vtimezonesTzids: ['Europe/Vilnius', 'America/New_York'],
})
)
).rejects.toThrowError('Unsupported response');
});
});
describe('getSupportedEventInvitation should guess a timezone to localize floating dates for invites for import PUBLISH', () => {
const generateVcalSetup = async ({
method = ICAL_METHOD.PUBLISH,
xWrTimezone = '',
vtimezonesTzids = [],
primaryTimezone,
uid = 'BA3017ED-889A-4BCB-B9CB-11CE30586021',
}: {
method?: ICAL_METHOD;
xWrTimezone?: string;
vtimezonesTzids?: string[];
primaryTimezone: string;
uid?: string;
}) => {
const xWrTimezoneString = xWrTimezone ? `X-WR-TIMEZONE:${xWrTimezone}` : '';
const vtimezonesString = vtimezonesTzids
.map(
(tzid) => `BEGIN:VTIMEZONE
TZID:${tzid}
END:VTIMEZONE`
)
.join('\n');
const vcal = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:${method}
${xWrTimezoneString}
${vtimezonesString}
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
DTSTART:20200915T090000
DTEND:20200915T100000
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
UID:${uid}
DTSTAMP:20200821T081914Z
SEQUENCE:1
SUMMARY:Floating date-time
RRULE:FREQ=DAILY;INTERVAL=2;COUNT=5
END:VEVENT
END:VCALENDAR`;
const parsedVcal = parse(vcal) as VcalVcalendar;
return {
vcalComponent: parsedVcal,
message: { Time: Math.round(Date.now() / 1000) } as Message,
icsBinaryString: vcal,
icsFileName: 'test.ics',
primaryTimezone,
hashUid: await generateVeventHashUID(vcal, uid),
};
};
const localizedVevent = (tzid: string, hashUid: string) => ({
component: 'vevent',
uid: { value: hashUid },
dtstamp: {
value: { year: 2020, month: 8, day: 21, hours: 8, minutes: 19, seconds: 14, isUTC: true },
},
dtstart: {
value: { year: 2020, month: 9, day: 15, hours: 9, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid },
},
dtend: {
value: { year: 2020, month: 9, day: 15, hours: 10, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid },
},
summary: { value: 'Floating date-time' },
sequence: { value: 1 },
rrule: { value: { freq: 'DAILY', interval: 2, count: 5 } },
});
test('when there is both x-wr-timezone and single vtimezone (use x-wr-timezone)', async () => {
const setup = await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
xWrTimezone: 'Europe/Brussels',
vtimezonesTzids: ['America/New_York'],
});
const { vevent } = (await getSupportedEventInvitation(setup)) || {};
expect(vevent).toEqual(localizedVevent('Europe/Brussels', setup.hashUid));
});
test('when there is a single vtimezone and no x-wr-timezone', async () => {
const setup = await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
vtimezonesTzids: ['Europe/Vilnius'],
});
const { vevent } = (await getSupportedEventInvitation(setup)) || {};
expect(vevent).toEqual(localizedVevent('Europe/Vilnius', setup.hashUid));
});
test('when there is a single vtimezone and x-wr-timezone is not supported', async () => {
await expect(
getSupportedEventInvitation(
await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
xWrTimezone: 'Moon/Tranquility',
vtimezonesTzids: ['Europe/Vilnius'],
})
)
).rejects.toThrowError('Unsupported event');
});
test('when there is no vtimezone nor x-wr-timezone (use primary time zone)', async () => {
const setup = await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
});
const { vevent } = (await getSupportedEventInvitation(setup)) || {};
expect(vevent).toEqual(localizedVevent('Asia/Seoul', setup.hashUid));
});
test('when there is no x-wr-timezone and more than one vtimezone (use primary time zone)', async () => {
const setup = await generateVcalSetup({
primaryTimezone: 'Asia/Seoul',
vtimezonesTzids: ['Europe/Vilnius', 'America/New_York'],
});
const { vevent } = (await getSupportedEventInvitation(setup)) || {};
expect(vevent).toEqual(localizedVevent('Asia/Seoul', setup.hashUid));
});
});
describe('getSupportedEventInvitation should throw', () => {
const generateVcalSetup = async ({
method = ICAL_METHOD.REQUEST,
primaryTimezone,
uid,
}: {
method?: ICAL_METHOD;
xWrTimezone?: string;
vtimezonesTzids?: string[];
primaryTimezone: string;
uid?: string;
}) => {
const vcal = `BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:${method}
BEGIN:VEVENT
ATTENDEE;CUTYPE=INDIVIDUAL;EMAIL="testme@pm.me";PARTSTAT=NEED
S-ACTION;RSVP=TRUE:mailto:testme@pm.me
ATTENDEE;CN="testKrt";CUTYPE=INDIVIDUAL;EMAIL="aGmailOne@gmail.co
m";PARTSTAT=ACCEPTED;ROLE=CHAIR:mailto:aGmailOne@gmail.com
DTSTART:20200915T090000
DTEND:20200915T100000
ORGANIZER;CN="testKrt":mailto:aGmailOne@gmail.com
${uid ? `UID:${uid}` : ''}
DTSTAMP:20200821T081914Z
SEQUENCE:1
SUMMARY:Testing something
RRULE:FREQ=DAILY;INTERVAL=2;COUNT=5
END:VEVENT
END:VCALENDAR`;
const parsedVcal = parse(vcal) as VcalVcalendar;
return {
vcalComponent: parsedVcal,
message: { Time: Math.round(Date.now() / 1000) } as Message,
icsBinaryString: vcal,
icsFileName: 'test.ics',
primaryTimezone,
hashUid: await generateVeventHashUID(vcal, uid),
};
};
test('when invitations do not have UID', async () => {
await expect(
getSupportedEventInvitation(
await generateVcalSetup({
method: ICAL_METHOD.REQUEST,
primaryTimezone: 'Asia/Seoul',
})
)
).rejects.toThrowError('Invalid invitation');
});
});
describe('getIsPartyCrasher', () => {
describe('organizer mode', () => {
const isOrganizerMode = true;
const calendarEventUID = 'calendarEventUID';
const attendeeAddress = 'attendee@pm.me';
const organizerAddress = 'organizer@pm.me';
const message = {
data: {
Sender: {
Address: attendeeAddress,
} as Recipient,
},
} as MessageStateWithData;
it('should return false when there is no event in the DB', async () => {
const results = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === false)).toBeTruthy();
});
it('should return false when the event in the DB contains the attendee (decryptable event)', async () => {
const results = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
invitationApi: {
attendee: {
emailAddress: attendeeAddress,
} as Participant,
organizer: {
emailAddress: organizerAddress,
},
} as RequireSome<EventInvitation, 'calendarEvent'>,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === false)).toBeTruthy();
});
it('should return true when the event in the DB does not contain the attendee (decryptable event)', async () => {
const results = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
invitationApi: {
organizer: {
emailAddress: organizerAddress,
},
} as RequireSome<EventInvitation, 'calendarEvent'>,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === true)).toBeTruthy();
});
it('should return false when the event in the DB contains the attendee (undecryptable event)', async () => {
const results = await Promise.all(
[true, false].map(async (isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
calendarEvent: {
UID: calendarEventUID,
Attendees: [
{
Token: await generateAttendeeToken(attendeeAddress, calendarEventUID),
},
] as Attendee[],
} as CalendarEvent,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === false)).toBeTruthy();
});
it('should return true when the event in the DB does not contain the attendee (undecryptable event)', async () => {
const results = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
calendarEvent: {
UID: calendarEventUID,
Attendees: [] as Attendee[],
} as CalendarEvent,
message,
isPartyCrasherIcs,
})
)
);
expect(results.every((result) => result === true)).toBeTruthy();
});
});
describe('attendee mode', () => {
const isOrganizerMode = false;
const attendeeAddress = 'attendee@pm.me';
const organizerAddress = 'organizer@pm.me';
const message = {
data: {
Sender: {
Address: organizerAddress,
} as Recipient,
},
} as MessageStateWithData;
it('should return the isPartyCrasher value computed from the ics when the invitation is not in the user calendar', async () => {
const [truthyResult, falsyResult] = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
message,
isPartyCrasherIcs,
})
)
);
expect(truthyResult).toEqual(true);
expect(falsyResult).toEqual(false);
});
it('should return the isPartyCrasher value computed from the ics when the user is in the invitation attendee list', async () => {
const [truthyResult, falsyResult] = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
invitationApi: {
attendee: {
emailAddress: attendeeAddress,
} as Participant,
organizer: {
emailAddress: organizerAddress,
},
} as RequireSome<EventInvitation, 'calendarEvent'>,
message,
isPartyCrasherIcs,
})
)
);
expect(truthyResult).toEqual(true);
expect(falsyResult).toEqual(false);
});
it('should return the isPartyCrasher value computed from the ics when the user is not in the invitation attendee list', async () => {
const [truthyResult, falsyResult] = await Promise.all(
[true, false].map((isPartyCrasherIcs) =>
getIsPartyCrasher({
isOrganizerMode,
invitationApi: {} as RequireSome<EventInvitation, 'calendarEvent'>,
message,
isPartyCrasherIcs,
})
)
);
expect(truthyResult).toEqual(true);
expect(falsyResult).toEqual(false);
});
});
});
});
| 3,847
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/calendar/invite.ts
|
import { getUnixTime } from 'date-fns';
import { serverTime } from '@proton/crypto';
import { generateAttendeeToken, getAttendeeEmail } from '@proton/shared/lib/calendar/attendees';
import { getDoesCalendarNeedUserAction, getIsCalendarDisabled } from '@proton/shared/lib/calendar/calendar';
import { ICAL_METHOD, ICAL_METHODS_ATTENDEE } from '@proton/shared/lib/calendar/constants';
import { getSelfAddressData } from '@proton/shared/lib/calendar/deserialize';
import { generateVeventHashUID, getIsProtonUID } from '@proton/shared/lib/calendar/helper';
import {
EVENT_INVITATION_ERROR_TYPE,
EventInvitationError,
cloneEventInvitationErrorWithConfig,
} from '@proton/shared/lib/calendar/icsSurgery/EventInvitationError';
import { getSupportedCalscale } from '@proton/shared/lib/calendar/icsSurgery/vcal';
import { getSupportedEvent, withSupportedDtstamp } from '@proton/shared/lib/calendar/icsSurgery/vevent';
import {
buildPartyCrasherParticipantData,
findAttendee,
getParticipant,
} from '@proton/shared/lib/calendar/mailIntegration/invite';
import { getOccurrencesBetween } from '@proton/shared/lib/calendar/recurrence/recurring';
import { parseWithRecoveryAndMaybeErrors, serialize } from '@proton/shared/lib/calendar/vcal';
import {
buildVcalOrganizer,
getDtendProperty,
propertyToLocalDate,
propertyToUTCDate,
} from '@proton/shared/lib/calendar/vcalConverter';
import {
getHasDtStart,
getHasRecurrenceId,
getIcalMethod,
getIsEventComponent,
getIsProtonReply,
getIsTimezoneComponent,
getIsValidMethod,
getIsXOrIanaComponent,
getIsYahooEvent,
getPmSharedEventID,
getPmSharedSessionKey,
} from '@proton/shared/lib/calendar/vcalHelper';
import {
getIsEventCancelled,
getIsRecurring,
getSequence,
getUidValue,
withDtstamp,
} from '@proton/shared/lib/calendar/veventHelper';
import { SECOND } from '@proton/shared/lib/constants';
import { getSupportedTimezone } from '@proton/shared/lib/date/timezone';
import { getIsAddressActive, getIsAddressDisabled } from '@proton/shared/lib/helpers/address';
import { canonicalizeEmailByGuess, canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email';
import { omit } from '@proton/shared/lib/helpers/object';
import { Address } from '@proton/shared/lib/interfaces';
import {
CalendarEvent,
CalendarEventEncryptionData,
CalendarWidgetData,
Participant,
PmInviteData,
VcalDateOrDateTimeProperty,
VcalNumberProperty,
VcalStringProperty,
VcalVcalendar,
VcalVeventComponent,
VcalVtimezoneComponent,
VcalXOrIanaComponent,
VisualCalendar,
} from '@proton/shared/lib/interfaces/calendar';
import { ContactEmail } from '@proton/shared/lib/interfaces/contacts';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { RequireSome, Unwrap } from '@proton/shared/lib/interfaces/utils';
import { getOriginalTo, hasSimpleLoginSender } from '@proton/shared/lib/mail/messages';
import unary from '@proton/utils/unary';
import { hasIcalExtension } from 'proton-mail/helpers/attachment/attachment';
import { MessageStateWithData, MessageWithOptionalBody } from '../../logic/messages/messagesTypes';
import { FetchAllEventsByUID } from './inviteApi';
export enum EVENT_TIME_STATUS {
PAST,
HAPPENING,
FUTURE,
}
export interface EventInvitation {
originalVcalInvitation?: VcalVcalendar;
originalUniqueIdentifier?: string;
originalIcsHasNoOrganizer?: boolean;
legacyUid?: string;
fileName?: string;
vevent: VcalVeventComponent;
hasMultipleVevents?: boolean;
calendarEvent?: CalendarEvent;
method?: ICAL_METHOD;
vtimezone?: VcalVtimezoneComponent;
xOrIanaComponents?: VcalXOrIanaComponent[];
organizer?: Participant;
attendee?: Participant;
participants?: Participant[];
}
export enum UPDATE_ACTION {
NONE,
KEEP_PARTSTAT,
RESET_PARTSTAT,
UPDATE_PARTSTAT,
CANCEL,
}
export interface InvitationModel {
isImport: boolean;
isOrganizerMode: boolean;
hasMultipleVevents: boolean;
timeStatus: EVENT_TIME_STATUS;
isPartyCrasher?: boolean;
hasProtonUID: boolean;
isAddressActive: boolean;
isAddressDisabled: boolean;
canCreateCalendar: boolean;
maxUserCalendarsDisabled: boolean;
hasNoCalendars: boolean;
isOutdated?: boolean;
isFromFuture?: boolean;
isProtonInvite?: boolean;
isReinvite?: boolean;
reinviteEventID?: string;
updateAction?: UPDATE_ACTION;
hideSummary?: boolean;
hideLink?: boolean;
calendarData?: CalendarWidgetData;
singleEditData?: CalendarEvent[];
reencryptionData?: Required<Pick<CalendarEventEncryptionData, 'encryptingAddressID' | 'sharedSessionKey'>>;
pmData?: PmInviteData;
invitationIcs?: RequireSome<EventInvitation, 'method'>;
invitationApi?: RequireSome<EventInvitation, 'calendarEvent'>;
parentInvitationApi?: RequireSome<EventInvitation, 'calendarEvent'>;
error?: EventInvitationError;
hasDecryptionError?: boolean;
}
interface NonRFCCompliantVcalendar extends VcalVcalendar {
uid?: VcalStringProperty;
sequence?: VcalNumberProperty;
}
export const getHasInvitationIcs = (model: InvitationModel): model is RequireSome<InvitationModel, 'invitationIcs'> => {
return !!model.invitationIcs;
};
export const getHasInvitationApi = (model: InvitationModel): model is RequireSome<InvitationModel, 'invitationApi'> => {
return !!model.invitationApi;
};
export const getInvitationHasMethod = (
invitation: EventInvitation
): invitation is RequireSome<EventInvitation, 'method'> => {
return invitation.method !== undefined;
};
export const getInvitationHasEventID = (
invitation: EventInvitation
): invitation is RequireSome<EventInvitation, 'calendarEvent'> => {
return invitation.calendarEvent?.ID !== undefined;
};
export const getInvitationHasAttendee = (
invitation: EventInvitation
): invitation is RequireSome<EventInvitation, 'attendee'> => {
return invitation.attendee !== undefined;
};
export const getInvitationUID = (invitationOrError: EventInvitation | EventInvitationError) => {
if (invitationOrError instanceof EventInvitationError) {
return;
}
return getUidValue(invitationOrError.vevent);
};
export const getHasFullCalendarData = (data?: CalendarWidgetData): data is Required<CalendarWidgetData> => {
const { memberID, addressKeys, calendarKeys, calendarSettings } = data || {};
return !!(memberID && addressKeys && calendarKeys && calendarSettings);
};
export const filterAttachmentsForEvents = (attachments: Attachment[]): Attachment[] =>
attachments.filter(({ Name = '' }) => hasIcalExtension(Name));
// Some external providers include UID and SEQUENCE outside the VEVENT component
export const withOutsideUIDAndSequence = (vevent: VcalVeventComponent, vcal: NonRFCCompliantVcalendar) => {
const { uid: veventUid, sequence: veventSequence } = vevent;
const { uid: vcalUid, sequence: vcalSequence } = vcal;
const result = { ...vevent };
if (!veventUid && vcalUid) {
result.uid = { ...vcalUid };
}
if (!veventSequence && vcalSequence) {
result.sequence = { ...vcalSequence };
}
return result;
};
export const getHasMultipleVevents = (vcal?: VcalVcalendar) => {
const numberOfVevents = vcal?.components?.filter(unary(getIsEventComponent)).length || 0;
return numberOfVevents > 1;
};
export const extractVevent = (vcal?: VcalVcalendar): VcalVeventComponent | undefined => {
const result = vcal?.components?.find(getIsEventComponent);
// return a copy
return result ? { ...result } : undefined;
};
export const extractUniqueVTimezone = (vcal?: VcalVcalendar): VcalVtimezoneComponent | undefined => {
const vtimezones = vcal?.components?.filter(getIsTimezoneComponent);
if (vtimezones?.length === 1) {
return vtimezones[0];
}
};
export const extractXOrIanaComponents = (vcal?: VcalVcalendar): VcalXOrIanaComponent[] | undefined => {
const result = vcal?.components?.filter(getIsXOrIanaComponent);
// return a copy
return result ? { ...result } : undefined;
};
export const getIsOrganizerMode = (event: VcalVeventComponent, emailTo: string) => {
if (!event.organizer) {
return false;
}
const organizerEmail = getAttendeeEmail(event.organizer);
return canonicalizeInternalEmail(organizerEmail) === canonicalizeInternalEmail(emailTo);
};
export const getSingleEditWidgetData = ({
otherEvents,
otherParentEvents,
}: Unwrap<ReturnType<FetchAllEventsByUID>>) => {
return (otherParentEvents || otherEvents).filter(({ RecurrenceID }) => !!RecurrenceID);
};
export const getIsInvitationOutdated = ({
invitationIcs,
invitationApi,
isOrganizerMode,
}: {
invitationIcs: EventInvitation;
invitationApi?: EventInvitation;
isOrganizerMode: boolean;
}) => {
const veventIcs = invitationIcs.vevent;
const veventApi = invitationApi?.vevent;
const updateTime = invitationApi?.attendee?.updateTime;
if (!veventApi) {
return false;
}
// DTSTAMP should always be present, but just in case
const timestampIcs = veventIcs.dtstamp ? getUnixTime(propertyToUTCDate(veventIcs.dtstamp)) : undefined;
const timestampApi = veventApi.dtstamp ? getUnixTime(propertyToUTCDate(veventApi.dtstamp)) : undefined;
const timestampDiff = timestampIcs !== undefined && timestampApi !== undefined ? timestampIcs - timestampApi : 0;
const updateTimeDiff =
timestampIcs !== undefined && updateTime !== undefined ? timestampIcs - (updateTime || 0) : timestampDiff;
const sequenceDiff = getSequence(veventIcs) - getSequence(veventApi);
if (isOrganizerMode) {
return sequenceDiff < 0 || updateTimeDiff < 0;
}
return sequenceDiff < 0 || timestampDiff < 0;
};
export const getIsInvitationFromFuture = ({
invitationIcs,
invitationApi,
isOrganizerMode,
}: {
invitationIcs: EventInvitation;
invitationApi?: EventInvitation;
isOrganizerMode: boolean;
}) => {
const veventIcs = invitationIcs.vevent;
const veventApi = invitationApi?.vevent;
if (!veventApi) {
return false;
}
const sequenceDiff = getSequence(veventIcs) - getSequence(veventApi);
// return true when the attendee replies to an instance of the event with higher sequence
return isOrganizerMode && sequenceDiff > 0;
};
/**
* A PM invite is either a new invitation or one for which the calendar event
* is linked to the one sent in the ics
*/
export const getIsProtonInvite = ({
invitationIcs,
calendarEvent,
pmData,
}: {
invitationIcs: RequireSome<EventInvitation, 'method'>;
calendarEvent?: CalendarEvent;
pmData?: PmInviteData;
}) => {
const { method } = invitationIcs;
const { sharedEventID, isProtonReply } = pmData || {};
if ([ICAL_METHOD.REQUEST, ICAL_METHOD.CANCEL].includes(method)) {
if (!calendarEvent) {
return !!sharedEventID;
}
return sharedEventID === calendarEvent.SharedEventID;
}
if (method === ICAL_METHOD.REPLY) {
return !!isProtonReply;
}
return false;
};
/**
* Detect case of being re-invited
*/
export const getIsReinvite = ({
invitationIcs,
calendarEvent,
isOrganizerMode,
isOutdated,
}: {
invitationIcs: EventInvitation;
calendarEvent?: CalendarEvent;
isOrganizerMode: boolean;
isOutdated: boolean;
}) => {
const { method } = invitationIcs;
if (isOrganizerMode || method !== ICAL_METHOD.REQUEST || !calendarEvent || isOutdated) {
return false;
}
return getIsEventCancelled(calendarEvent);
};
export const getIsNonSoughtEvent = (
event: CalendarEvent,
vevent: VcalVeventComponent,
supportedRecurrenceId?: VcalDateOrDateTimeProperty
) => {
if (!event.RecurrenceID) {
return false;
}
if (!getHasRecurrenceId(vevent)) {
return true;
}
return getUnixTime(propertyToUTCDate(supportedRecurrenceId || vevent['recurrence-id'])) !== event.RecurrenceID;
};
/**
* Determines if a single edit can be created from a parent. So basically check if the recurrence-id
* matches a parent occurrence
*/
export const getCanCreateSingleEdit = (singleEditVevent: VcalVeventComponent, parentVevent: VcalVeventComponent) => {
if (!getIsRecurring(parentVevent) || !getHasRecurrenceId(singleEditVevent)) {
return false;
}
const utcStart = +propertyToUTCDate(singleEditVevent['recurrence-id']);
const occurrencesAtStart = getOccurrencesBetween(parentVevent, utcStart, utcStart);
return occurrencesAtStart.length === 1;
};
/**
* Determines if a event has already passed with respect to a timestamp in milliseconds
*/
export const getEventTimeStatus = (vevent: VcalVeventComponent, now: number) => {
if (vevent.rrule?.value) {
// ignore complexity of recurring events for the moment
return EVENT_TIME_STATUS.FUTURE;
}
const nowTimestamp = getUnixTime(now);
const startTimestamp = getUnixTime(propertyToLocalDate(vevent.dtstart));
const endTimestamp = getUnixTime(propertyToLocalDate(getDtendProperty(vevent)));
if (nowTimestamp >= endTimestamp) {
return EVENT_TIME_STATUS.PAST;
}
if (nowTimestamp >= startTimestamp) {
return EVENT_TIME_STATUS.HAPPENING;
}
return EVENT_TIME_STATUS.FUTURE;
};
export const parseVcalendar = (data: string) => {
try {
if (!data) {
return;
}
return parseWithRecoveryAndMaybeErrors(data);
} catch (e: any) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.PARSING_ERROR);
}
};
interface ProcessedInvitation<T> {
isImport: boolean;
isOrganizerMode: boolean;
timeStatus: EVENT_TIME_STATUS;
isAddressActive: boolean;
isAddressDisabled: boolean;
invitation: EventInvitation & T;
isPartyCrasher: boolean;
originalIcsHasNoOrganizer?: boolean;
}
export const processEventInvitation = <T>(
invitation: EventInvitation & T,
message: MessageStateWithData,
contactEmails: ContactEmail[],
ownAddresses: Address[]
): ProcessedInvitation<T> => {
const { vevent, calendarEvent, method, originalIcsHasNoOrganizer } = invitation;
const isImport = method === ICAL_METHOD.PUBLISH;
const timeStatus = getEventTimeStatus(vevent, +serverTime());
const attendees = vevent.attendee || [];
const { organizer } = vevent;
const originalTo = getOriginalTo(message.data);
const originalFrom = message.data.Sender.Address;
const isOrganizerMode = isImport ? false : getIsOrganizerMode(vevent, originalTo);
const { selfAddress, selfAttendee } = getSelfAddressData({
organizer,
attendees,
addresses: ownAddresses,
});
let isAddressActive = selfAddress ? getIsAddressActive(selfAddress) : true;
let isAddressDisabled = selfAddress ? getIsAddressDisabled(selfAddress) : false;
const hasProtonUID = getIsProtonUID(vevent.uid.value);
const processed: EventInvitation & T = { ...invitation };
let isPartyCrasher = false;
if (attendees) {
processed.participants = attendees.map((attendee) =>
getParticipant({
participant: attendee,
contactEmails,
selfAddress,
selfAttendee,
emailTo: originalTo,
})
);
}
if (organizer) {
processed.organizer = getParticipant({
participant: organizer,
selfAddress,
contactEmails,
emailTo: originalTo,
});
}
if (isOrganizerMode) {
const { attendee, index } = findAttendee(originalFrom, attendees);
if (attendee) {
processed.attendee = getParticipant({
participant: attendee,
selfAddress,
contactEmails,
emailTo: originalTo,
index,
calendarAttendees: calendarEvent?.Attendees,
xYahooUserStatus: vevent['x-yahoo-user-status']?.value,
});
} else {
isPartyCrasher = true;
}
} else {
// Attendee mode
if (selfAttendee) {
processed.attendee = getParticipant({
participant: selfAttendee,
selfAddress,
selfAttendee,
contactEmails,
emailTo: originalTo,
calendarAttendees: calendarEvent?.Attendees,
});
} else if (!isImport) {
// The user is a party crasher
isPartyCrasher = true;
if (!hasProtonUID && !hasSimpleLoginSender(message.data)) {
// To let the user reply, we fake it being in the attendee list
const { participant, selfAttendee, selfAddress } =
buildPartyCrasherParticipantData(originalTo, ownAddresses, contactEmails, attendees) || {};
if (participant && selfAttendee && selfAddress) {
processed.attendee = participant;
processed.vevent.attendee = [...(processed.vevent.attendee || []), selfAttendee];
// Now that the participant has been added to the event invitation, we need to check once again if the address is disabled or not
isAddressActive = getIsAddressActive(selfAddress);
isAddressDisabled = getIsAddressDisabled(selfAddress);
}
}
}
}
return {
isImport,
isOrganizerMode,
timeStatus,
isAddressActive,
isAddressDisabled,
invitation: processed,
isPartyCrasher,
originalIcsHasNoOrganizer,
};
};
interface GetInitialInvitationModelArgs {
invitationOrError: EventInvitation | EventInvitationError;
message: MessageStateWithData;
contactEmails: ContactEmail[];
ownAddresses: Address[];
calendar?: VisualCalendar;
hasNoCalendars: boolean;
canCreateCalendar: boolean;
maxUserCalendarsDisabled: boolean;
}
export const getInitialInvitationModel = ({
invitationOrError,
message,
contactEmails,
ownAddresses,
calendar,
hasNoCalendars,
canCreateCalendar,
maxUserCalendarsDisabled,
}: GetInitialInvitationModelArgs) => {
const errorModel = {
isImport: false,
hasMultipleVevents: false,
hasProtonUID: false,
isOrganizerMode: false,
isAddressDisabled: false,
isAddressActive: true,
canCreateCalendar,
maxUserCalendarsDisabled,
hasNoCalendars,
timeStatus: EVENT_TIME_STATUS.FUTURE,
};
if (invitationOrError instanceof EventInvitationError) {
return { ...errorModel, error: invitationOrError };
}
if (!getInvitationHasMethod(invitationOrError)) {
throw new Error('Initial invitation lacks ICAL method');
}
const {
isOrganizerMode,
isImport,
timeStatus,
isAddressActive,
isAddressDisabled,
invitation,
isPartyCrasher,
originalIcsHasNoOrganizer,
} = processEventInvitation<RequireSome<EventInvitation, 'method'>>(
invitationOrError,
message,
contactEmails,
ownAddresses
);
if (invitation.method === ICAL_METHOD.REPLY && !invitation.attendee) {
// If we couldn't find the attendee in the REPLY ics, something is wrong in the ics
return {
...errorModel,
error: new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, {
method: invitation.method,
}),
};
}
if (isPartyCrasher && originalIcsHasNoOrganizer) {
/*
If the user is a party crasher, most likely the invitation has been forwarded.
Therefore, we cannot assume the sender is the organizer, so in case the original ICS contained no organizer,
we have no other option than showing an error.
*/
return {
...errorModel,
error: new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, {
method: invitation.method,
}),
};
}
const result: InvitationModel = {
isOrganizerMode,
isImport,
hasMultipleVevents: !!invitation.hasMultipleVevents,
hasProtonUID: getIsProtonUID(invitation.vevent.uid.value),
timeStatus,
isAddressActive,
isAddressDisabled,
canCreateCalendar,
maxUserCalendarsDisabled,
hasNoCalendars,
invitationIcs: invitation,
isPartyCrasher,
};
if (calendar) {
result.calendarData = {
calendar,
isCalendarDisabled: getIsCalendarDisabled(calendar),
calendarNeedsUserAction: getDoesCalendarNeedUserAction(calendar),
};
}
if (!isImport && !getIsValidMethod(invitation.method, isOrganizerMode)) {
result.error = new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVALID_METHOD, {
method: invitation.method,
});
}
const isProtonReply = getIsProtonReply(invitation.vevent);
const sharedEventID = getPmSharedEventID(invitation.vevent);
const sharedSessionKey = getPmSharedSessionKey(invitation.vevent);
if (isProtonReply !== undefined || sharedEventID || sharedSessionKey) {
const pmData: PmInviteData = {};
if (isProtonReply !== undefined) {
pmData.isProtonReply = isProtonReply;
}
if (sharedEventID) {
pmData.sharedEventID = sharedEventID;
}
if (sharedSessionKey) {
pmData.sharedSessionKey = sharedSessionKey;
}
result.pmData = pmData;
}
const isYahooEvent = getIsYahooEvent(invitation.vevent);
if (isYahooEvent) {
// Yahoo does not send an updated DTSTAMP in their invite ICS's. This breaks all of our flow.
// To avoid that, we substitute the event DTSTAMP by the message DTSTAMP
invitation.vevent = withDtstamp(omit(invitation.vevent, ['dtstamp']), message.data.Time * SECOND);
}
return result;
};
export const getSupportedEventInvitation = async ({
vcalComponent,
message,
icsBinaryString,
icsFileName,
primaryTimezone,
}: {
vcalComponent: VcalVcalendar;
message: MessageWithOptionalBody;
icsBinaryString: string;
icsFileName: string;
primaryTimezone: string;
}): Promise<EventInvitation | undefined> => {
const { calscale, 'x-wr-timezone': xWrTimezone, method } = vcalComponent;
const supportedMethod = getIcalMethod(method);
const supportedCalscale = getSupportedCalscale(calscale);
if (!supportedMethod) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVALID_METHOD);
}
if (!supportedCalscale) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED, { method: supportedMethod });
}
if (!vcalComponent.components?.length) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.NO_COMPONENT, { method: supportedMethod });
}
const vevent = extractVevent(vcalComponent);
const vtimezone = extractUniqueVTimezone(vcalComponent);
if (!vevent) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.NO_VEVENT, { method: supportedMethod });
}
if (!getHasDtStart(vevent)) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, { method: supportedMethod });
}
const completeVevent = withOutsideUIDAndSequence(
withSupportedDtstamp(vevent, message.Time * SECOND),
vcalComponent
);
const hasMultipleVevents = getHasMultipleVevents(vcalComponent);
const isImport = supportedMethod === ICAL_METHOD.PUBLISH;
// To filter potentially equivalent invitation ics's, we have to generate a reliable
// unique identifier (resistant to format differences, like \n --> \r\n) for the ics if it has no UID
const originalUID = completeVevent.uid?.value;
const originalUniqueIdentifier =
hasMultipleVevents || !originalUID ? await generateVeventHashUID(serialize(vcalComponent)) : originalUID;
let legacyUid;
let originalIcsHasNoOrganizer = false;
if (isImport) {
const sha1Uid = await generateVeventHashUID(icsBinaryString, originalUID);
if (originalUID) {
// generate a hash UID with legacy format. The ICS widget will need it to find the event in the DB
// in case it was added before the UID migration
legacyUid = await generateVeventHashUID(icsBinaryString, originalUID, true);
}
completeVevent.uid = { value: sha1Uid };
} else if (!originalUID) {
// Invitations without UID should be considered invalid
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, { method: supportedMethod });
} else if (!completeVevent.organizer) {
originalIcsHasNoOrganizer = true;
// The ORGANIZER field is mandatory in an invitation
const guessOrganizerEmail = ICAL_METHODS_ATTENDEE.includes(supportedMethod)
? getOriginalTo(message)
: message.Sender.Address;
completeVevent.organizer = buildVcalOrganizer(guessOrganizerEmail);
}
const hasXWrTimezone = !!xWrTimezone?.value;
const calendarTzid = xWrTimezone ? getSupportedTimezone(xWrTimezone.value) : undefined;
// At this stage, vtimezone did not undergo any surgery and might lack the RFC-mandatory TZID
const invitationTzid = vtimezone?.tzid?.value;
const guessTzid = (() => {
if (!invitationTzid) {
return isImport ? primaryTimezone : undefined;
}
return getSupportedTimezone(invitationTzid);
})();
try {
const supportedEvent = getSupportedEvent({
method: supportedMethod,
vcalVeventComponent: completeVevent,
hasXWrTimezone,
calendarTzid,
guessTzid,
isEventInvitation: true,
generatedHashUid: isImport,
});
return {
method: supportedMethod,
vevent: supportedEvent,
vtimezone,
originalVcalInvitation: vcalComponent,
originalIcsHasNoOrganizer,
originalUniqueIdentifier,
legacyUid,
hasMultipleVevents,
fileName: icsFileName,
};
} catch (error: any) {
if (error instanceof EventInvitationError) {
throw cloneEventInvitationErrorWithConfig(error, {
method: supportedMethod,
originalUniqueIdentifier,
});
}
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_UNSUPPORTED, {
externalError: error,
method: supportedMethod,
originalUniqueIdentifier: originalUniqueIdentifier,
});
}
};
export const getDoNotDisplayButtons = (model: RequireSome<InvitationModel, 'invitationIcs'>) => {
const {
isImport,
hasMultipleVevents,
isOrganizerMode,
isPartyCrasher,
invitationIcs: { method, vevent: veventIcs, attendee: attendeeIcs },
invitationApi,
calendarData,
isOutdated,
isAddressActive,
} = model;
if (isOrganizerMode) {
return !isPartyCrasher || !!veventIcs['recurrence-id'];
}
if (isImport && (invitationApi || hasMultipleVevents)) {
return true;
}
return (
method === ICAL_METHOD.CANCEL ||
!!isOutdated ||
!isAddressActive ||
!!calendarData?.isCalendarDisabled ||
(isPartyCrasher && !attendeeIcs)
);
};
export const getDisableButtons = (model: RequireSome<InvitationModel, 'invitationIcs'>) => {
const { calendarData, isAddressActive, isImport } = model;
const alwaysDisable =
!calendarData?.calendar || calendarData.isCalendarDisabled || calendarData.calendarNeedsUserAction;
return isImport ? alwaysDisable : alwaysDisable || !isAddressActive;
};
export const getParticipantsList = (attendees?: Participant[], organizer?: Participant) => {
const list = attendees ? [...attendees] : [];
if (organizer) {
// we remove the organizer from the list of participants in case it's duplicated there
const canonicalOrganizerEmail = canonicalizeEmailByGuess(organizer.emailAddress);
const organizerIndex = list.findIndex(
({ emailAddress }) => canonicalizeEmailByGuess(emailAddress) === canonicalOrganizerEmail
);
if (organizerIndex !== -1) {
list.splice(organizerIndex, 1);
}
list.unshift(organizer);
}
return list;
};
export const getIsPartyCrasher = async ({
isOrganizerMode,
invitationApi,
calendarEvent,
message,
isPartyCrasherIcs,
}: {
isOrganizerMode: boolean;
invitationApi?: RequireSome<EventInvitation, 'calendarEvent'>;
calendarEvent?: CalendarEvent;
message: MessageStateWithData;
isPartyCrasherIcs?: boolean;
}) => {
if (isOrganizerMode) {
// on organizer mode we can only check party crasher status as long as the event exists in the DB
if (invitationApi) {
return !invitationApi.attendee;
} else if (calendarEvent) {
// If we do not have invitationApi, but we have a calendarEvent, it means we could not decrypt calendarEvent.
// Assuming the sender is a potential attendee, we can resort to checking attendee tokens in this case, since those are clear text
const senderToken = await generateAttendeeToken(
canonicalizeEmailByGuess(message.data.Sender.Address),
calendarEvent.UID
);
return !calendarEvent.Attendees.some(({ Token }) => Token === senderToken);
}
return false;
} else {
// on attendee mode we fully rely on whether the attendee appears in the ics or not
return isPartyCrasherIcs;
}
};
| 3,848
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/calendar/inviteApi.ts
|
import { getUnixTime } from 'date-fns';
import { syncMultipleEvents, updateAttendeePartstat, updatePersonalEventPart } from '@proton/shared/lib/api/calendars';
import { processApiRequestsSafe } from '@proton/shared/lib/api/helpers/safeApiRequests';
import { getPaginatedEventsByUID } from '@proton/shared/lib/calendar/api';
import {
getHasDefaultNotifications,
getHasSharedEventContent,
getHasSharedKeyPacket,
} from '@proton/shared/lib/calendar/apiModels';
import {
getAttendeeEmail,
modifyAttendeesPartstat,
toApiPartstat,
withPmAttendees,
} from '@proton/shared/lib/calendar/attendees';
import {
getCalendarWithReactivatedKeys,
getDoesCalendarNeedUserAction,
getIsCalendarDisabled,
getOwnedPersonalCalendars,
getVisualCalendars,
} from '@proton/shared/lib/calendar/calendar';
import { getHasUserReachedCalendarsLimit } from '@proton/shared/lib/calendar/calendarLimits';
import {
CALENDAR_TYPE,
ICAL_ATTENDEE_STATUS,
ICAL_EVENT_STATUS,
ICAL_METHOD,
} from '@proton/shared/lib/calendar/constants';
import { getCreationKeys } from '@proton/shared/lib/calendar/crypto/keys/helpers';
import setupCalendarHelper from '@proton/shared/lib/calendar/crypto/keys/setupCalendarHelper';
import { naiveGetIsDecryptionError } from '@proton/shared/lib/calendar/helper';
import {
EVENT_INVITATION_ERROR_TYPE,
EventInvitationError,
} from '@proton/shared/lib/calendar/icsSurgery/EventInvitationError';
import { getLinkedDateTimeProperty } from '@proton/shared/lib/calendar/icsSurgery/vevent';
import {
findAttendee,
getInvitedVeventWithAlarms,
getResetPartstatActions,
} from '@proton/shared/lib/calendar/mailIntegration/invite';
import { getIsRruleEqual } from '@proton/shared/lib/calendar/recurrence/rruleEqual';
import { createCalendarEvent } from '@proton/shared/lib/calendar/serialize';
import {
getHasModifiedAttendees,
getHasModifiedDateTimes,
getHasModifiedDtstamp,
propertyToUTCDate,
} from '@proton/shared/lib/calendar/vcalConverter';
import {
getHasAttendee,
getHasRecurrenceId,
getIsAlarmComponent,
getIsVeventCancelled,
} from '@proton/shared/lib/calendar/vcalHelper';
import {
getIsEventCancelled,
getSequence,
toApiNotifications,
withDtstamp,
} from '@proton/shared/lib/calendar/veventHelper';
import { API_CODES } from '@proton/shared/lib/constants';
import { omit, pick } from '@proton/shared/lib/helpers/object';
import { Address, Api } from '@proton/shared/lib/interfaces';
import {
CalendarEvent,
CalendarEventEncryptionData,
CalendarUserSettings,
CalendarWidgetData,
CalendarWithOwnMembers,
Participant,
PmInviteData,
SyncMultipleApiResponse,
UpdateEventPartApiResponse,
VcalAttendeeProperty,
VcalDateOrDateTimeProperty,
VcalVeventComponent,
VisualCalendar,
} from '@proton/shared/lib/interfaces/calendar';
import {
CreateCalendarEventSyncData,
CreateLinkedCalendarEventsSyncData,
CreateSinglePersonalEventData,
DeleteCalendarEventSyncData,
UpdateCalendarEventSyncData,
} from '@proton/shared/lib/interfaces/calendar/Api';
import { ContactEmail } from '@proton/shared/lib/interfaces/contacts';
import { GetAddressKeys } from '@proton/shared/lib/interfaces/hooks/GetAddressKeys';
import { GetCalendarEventRaw } from '@proton/shared/lib/interfaces/hooks/GetCalendarEventRaw';
import { GetCalendarInfo } from '@proton/shared/lib/interfaces/hooks/GetCalendarInfo';
import { GetCanonicalEmailsMap } from '@proton/shared/lib/interfaces/hooks/GetCanonicalEmailsMap';
import { RequireSome, Unwrap } from '@proton/shared/lib/interfaces/utils';
import { getPrimaryKey } from '@proton/shared/lib/keys';
import isTruthy from '@proton/utils/isTruthy';
import noop from '@proton/utils/noop';
import { MessageStateWithData } from '../../logic/messages/messagesTypes';
import {
EventInvitation,
UPDATE_ACTION,
getCanCreateSingleEdit,
getInvitationHasAttendee,
getIsInvitationFromFuture,
getIsInvitationOutdated,
getIsNonSoughtEvent,
getIsProtonInvite,
getSingleEditWidgetData,
processEventInvitation,
} from './invite';
const { CANCELLED } = ICAL_EVENT_STATUS;
const { NONE, KEEP_PARTSTAT, RESET_PARTSTAT, UPDATE_PARTSTAT, CANCEL } = UPDATE_ACTION;
/**
* Get calendars and calendar user settings. If no calendar exists, create one
*/
export const getOrCreatePersonalCalendarsAndSettings = async ({
api,
callEventManager,
addresses,
isFreeUser,
getAddressKeys,
getCalendars,
getCalendarUserSettings,
}: {
api: Api;
callEventManager: () => Promise<void>;
addresses: Address[];
isFreeUser: boolean;
getAddressKeys: GetAddressKeys;
getCalendars: () => Promise<CalendarWithOwnMembers[] | undefined>;
getCalendarUserSettings: () => Promise<CalendarUserSettings>;
}) => {
const silentApi = <T>(config: any) => api<T>({ ...config, silence: true });
let [calendarsWithOwnMembers = [], calendarUserSettings] = await Promise.all([
getCalendars(),
getCalendarUserSettings(),
]);
let calendars = getVisualCalendars(calendarsWithOwnMembers);
const { isCalendarsLimitReached } = getHasUserReachedCalendarsLimit(calendars, isFreeUser);
if (!getOwnedPersonalCalendars(calendars).length && !isCalendarsLimitReached) {
// create a calendar automatically
try {
const { calendar, updatedCalendarUserSettings } = await setupCalendarHelper({
api: silentApi,
addresses,
getAddressKeys,
});
// refresh list of calendars without awaiting
// (the refresh is just in case another widget gets opened quickly after, so that it knows there's a new calendar)
void callEventManager();
calendarUserSettings = { ...calendarUserSettings, ...updatedCalendarUserSettings };
calendars = getVisualCalendars([calendar]);
} catch {
// fail silently
noop();
}
}
return { calendars, calendarUserSettings };
};
const getRelevantEventsByUID = ({ api, uid, calendarIDs }: { api: Api; uid: string; calendarIDs: string[] }) => {
// No need to search for invitations in subscribed calendars
return getPaginatedEventsByUID({ api, uid, calendarType: CALENDAR_TYPE.PERSONAL }).then((events) =>
events.filter(({ CalendarID }) => calendarIDs.includes(CalendarID))
);
};
export type FetchAllEventsByUID = ({
uid,
api,
recurrenceId,
}: {
uid: string;
legacyUid?: string;
calendars: VisualCalendar[];
recurrenceId?: VcalDateOrDateTimeProperty;
api: Api;
}) => Promise<{
event?: CalendarEvent;
otherEvents: CalendarEvent[];
parentEvent?: CalendarEvent;
otherParentEvents?: CalendarEvent[];
supportedRecurrenceId?: VcalDateOrDateTimeProperty;
}>;
export const fetchAllEventsByUID: FetchAllEventsByUID = async ({ uid, legacyUid, calendars, api, recurrenceId }) => {
const timestamp = recurrenceId ? getUnixTime(propertyToUTCDate(recurrenceId)) : undefined;
const allowedCalendarIDs = calendars.map(({ ID }) => ID);
const promises: Promise<CalendarEvent[]>[] = (() => {
if (!legacyUid) {
return [getRelevantEventsByUID({ api, uid, calendarIDs: allowedCalendarIDs })];
}
/**
* We might be looking for an event with a legacy hash UID. We do not know in advance,
* so we have to fire two calls. We pick the response from the one containing a result, if any
*/
return [
Promise.all([
getRelevantEventsByUID({ api, uid, calendarIDs: allowedCalendarIDs }),
getRelevantEventsByUID({ api, uid: legacyUid, calendarIDs: allowedCalendarIDs }),
]).then(([result, resultLegacy]) => {
if (result[0]) {
return result;
}
return resultLegacy;
}),
];
})();
if (recurrenceId) {
/**
* Notice that due to how ICS surgery works, whenever we have a hash UID, we are guaranteed not to have a
* recurrence id, so we don't need to fire an extra call here if a legacy UID is present
*/
promises.unshift(
getPaginatedEventsByUID({ api, uid, recurrenceID: timestamp, calendarType: CALENDAR_TYPE.PERSONAL }).then(
(events) => events.filter(({ CalendarID }) => allowedCalendarIDs.includes(CalendarID))
)
);
}
const [[event, ...otherEvents] = [], [parentEvent, ...otherParentEvents] = []] = await Promise.all(promises);
if (!parentEvent) {
return { event, otherEvents };
}
/**
* If recurrenceID is passed, but the single edit is not found, it is possible that the ICS
* contained the wrong RECURRENCE-ID (Outlook sends a wrong one for single edits of all-day events).
* Try to recover. If we cannot find the single edit, return the parent
*/
if (!event && recurrenceId) {
try {
const supportedRecurrenceId = getLinkedDateTimeProperty({
component: 'vevent',
property: recurrenceId,
linkedIsAllDay: !!parentEvent.FullDay,
linkedTzid: parentEvent.StartTimezone,
});
const supportedTimestamp = getUnixTime(propertyToUTCDate(supportedRecurrenceId));
const [recoveredEvent, ...otherRecoveredEvents] = await getPaginatedEventsByUID({
api,
uid,
recurrenceID: supportedTimestamp,
calendarType: CALENDAR_TYPE.PERSONAL,
});
return recoveredEvent
? {
event: recoveredEvent,
otherEvents: otherRecoveredEvents,
parentEvent,
otherParentEvents,
supportedRecurrenceId,
}
: { event: parentEvent, otherEvents: otherParentEvents, supportedRecurrenceId };
} catch (e: any) {
noop();
}
}
return { event, otherEvents, parentEvent, otherParentEvents };
};
type FetchEventInvitation = (args: {
veventComponent: VcalVeventComponent;
legacyUid?: string;
api: Api;
getAddressKeys: GetAddressKeys;
getCalendarInfo: GetCalendarInfo;
getCalendarEventRaw: GetCalendarEventRaw;
calendars: VisualCalendar[];
defaultCalendar?: VisualCalendar;
message: MessageStateWithData;
contactEmails: ContactEmail[];
ownAddresses: Address[];
}) => Promise<{
invitation?: RequireSome<EventInvitation, 'calendarEvent'>;
parentInvitation?: RequireSome<EventInvitation, 'calendarEvent'>;
calendarData?: CalendarWidgetData;
calendarEvent?: CalendarEvent;
singleEditData?: CalendarEvent[];
reencryptionData?: Required<Pick<CalendarEventEncryptionData, 'encryptingAddressID' | 'sharedSessionKey'>>;
hasDecryptionError?: boolean;
supportedRecurrenceId?: VcalDateOrDateTimeProperty;
}>;
export const fetchEventInvitation: FetchEventInvitation = async ({
veventComponent,
legacyUid,
api,
getAddressKeys,
getCalendarInfo,
getCalendarEventRaw,
calendars,
defaultCalendar,
message,
contactEmails,
ownAddresses,
}) => {
const allEventsWithUID = await fetchAllEventsByUID({
uid: veventComponent.uid.value,
legacyUid,
api,
calendars,
recurrenceId: veventComponent['recurrence-id'],
});
const { event: calendarEvent, parentEvent: calendarParentEvent, supportedRecurrenceId } = allEventsWithUID;
const calendarWithPossiblyNotReactivatedKeys =
calendars.find(({ ID }) => ID === (calendarEvent || calendarParentEvent)?.CalendarID) || defaultCalendar;
if (!calendarWithPossiblyNotReactivatedKeys) {
return {};
}
const calendar = await getCalendarWithReactivatedKeys({
calendar: calendarWithPossiblyNotReactivatedKeys,
api,
addresses: ownAddresses,
getAddressKeys,
// if we fail to reactivate keys, fail silently and proceed with the calendar in a passphrase-needs-update state
handleError: noop,
});
const calendarData = {
calendar,
isCalendarDisabled: getIsCalendarDisabled(calendar),
calendarNeedsUserAction: getDoesCalendarNeedUserAction(calendar),
...(await getCalendarInfo(calendar.ID)),
};
// if we retrieved a single edit when not looking for one, or looking for another one, do not return it
if (!calendarEvent || getIsNonSoughtEvent(calendarEvent, veventComponent, supportedRecurrenceId)) {
return { calendarData };
}
const singleEditData = getSingleEditWidgetData(allEventsWithUID);
try {
const veventResults = await Promise.all(
[calendarEvent, calendarParentEvent].filter(isTruthy).map((event) => getCalendarEventRaw(event))
);
const [
{
veventComponent: vevent,
encryptionData: { sharedSessionKey, encryptingAddressID },
},
parentVeventResult,
] = veventResults;
const result: Unwrap<ReturnType<FetchEventInvitation>> = {
calendarData,
calendarEvent,
singleEditData,
supportedRecurrenceId,
};
const { invitation } = processEventInvitation({ vevent, calendarEvent }, message, contactEmails, ownAddresses);
result.invitation = invitation;
if (parentVeventResult && calendarParentEvent) {
const { invitation: parentInvitation } = processEventInvitation(
{ vevent: parentVeventResult.veventComponent, calendarEvent: calendarParentEvent },
message,
contactEmails,
ownAddresses
);
result.parentInvitation = parentInvitation;
}
if (encryptingAddressID && sharedSessionKey) {
result.reencryptionData = {
encryptingAddressID,
sharedSessionKey,
};
}
return result;
} catch (e: any) {
// We need to detect if the error is due to a failed decryption of the event.
// We don't have a great way of doing this as the error comes from openpgp
return { calendarData, hasDecryptionError: naiveGetIsDecryptionError(e), calendarEvent };
}
};
interface UpdateEventArgs {
calendarEvent: CalendarEvent;
vevent: VcalVeventComponent;
api: Api;
getCanonicalEmailsMap: GetCanonicalEmailsMap;
calendarData: Required<CalendarWidgetData>;
hasDefaultNotifications: boolean;
createSingleEdit?: boolean;
updateTime?: number;
updatePartstat?: ICAL_ATTENDEE_STATUS;
attendee?: Participant;
deleteIds?: string[];
overwrite: boolean;
}
const updateEventApi = async ({
calendarEvent,
vevent,
api,
getCanonicalEmailsMap,
calendarData,
hasDefaultNotifications,
createSingleEdit = false,
updateTime,
updatePartstat,
attendee,
overwrite,
deleteIds = [],
}: UpdateEventArgs) => {
const {
calendar: { ID: calendarID },
memberID,
addressKeys,
calendarKeys,
} = calendarData;
// organizer mode
if (updateTime !== undefined && updatePartstat) {
const { ID: eventID, Attendees } = calendarEvent;
const token = attendee?.token;
const attendeeID = Attendees.find(({ Token }) => Token === token)?.ID;
if (!attendeeID) {
throw new Error('Missing data for updating participation status');
}
const data = {
Status: toApiPartstat(updatePartstat),
UpdateTime: updateTime,
};
const { Event } = await api<UpdateEventPartApiResponse>(
updateAttendeePartstat(calendarID, eventID, attendeeID, data)
);
return Event;
}
// attendee mode
const veventWithPmAttendees = await withPmAttendees(vevent, getCanonicalEmailsMap, true);
const creationKeys = await getCreationKeys({
calendarEvent: createSingleEdit ? undefined : calendarEvent,
newAddressKeys: addressKeys,
newCalendarKeys: calendarKeys,
});
const data = await createCalendarEvent({
eventComponent: veventWithPmAttendees,
isCreateEvent: !!createSingleEdit,
isSwitchCalendar: false,
hasDefaultNotifications,
isAttendee: true,
...creationKeys,
});
if (createSingleEdit) {
if (!getHasSharedKeyPacket(data) || !getHasSharedEventContent(data)) {
throw new Error('Missing shared data');
}
const Events: CreateCalendarEventSyncData[] = [
{ Event: { Permissions: 1, IsOrganizer: 0, ...data }, Overwrite: overwrite ? 1 : 0 },
];
const {
Responses: [
{
Response: { Code, Event },
},
],
} = await api<SyncMultipleApiResponse>({
...syncMultipleEvents(calendarID, { MemberID: memberID, Events }),
silence: true,
});
if (Code !== API_CODES.SINGLE_SUCCESS || !Event) {
throw new Error('Update unsuccessful');
}
return Event;
}
if (!getHasSharedEventContent(data)) {
throw new Error('Missing shared data');
}
// If we are updating a recurring event with previous modifications, we must delete those first
const deleteEvents = deleteIds.map((id) => ({ ID: id }));
const Events: (UpdateCalendarEventSyncData | DeleteCalendarEventSyncData)[] = [
...deleteEvents,
{ Event: { Permissions: 1, ...data }, ID: calendarEvent.ID },
];
const result = await api<SyncMultipleApiResponse>({
...syncMultipleEvents(calendarID, { MemberID: memberID, Events }),
silence: true,
});
const { Code, Event } = result.Responses.pop()?.Response || {};
if (Code !== API_CODES.SINGLE_SUCCESS || !Event) {
throw new Error('Update unsuccessful');
}
return Event;
};
interface UpdateEventInvitationArgs {
isOrganizerMode: boolean;
invitationIcs: RequireSome<EventInvitation, 'method'>;
invitationApi: RequireSome<EventInvitation, 'calendarEvent'>;
parentInvitationApi?: RequireSome<EventInvitation, 'calendarEvent'>;
calendarData: Required<CalendarWidgetData>;
singleEditData?: CalendarEvent[];
pmData?: PmInviteData;
api: Api;
getCanonicalEmailsMap: GetCanonicalEmailsMap;
message: MessageStateWithData;
contactEmails: ContactEmail[];
ownAddresses: Address[];
overwrite: boolean;
}
export const updateEventInvitation = async ({
isOrganizerMode,
invitationIcs,
invitationApi,
parentInvitationApi,
calendarData,
singleEditData,
pmData,
api,
getCanonicalEmailsMap,
message,
contactEmails,
ownAddresses,
overwrite,
}: UpdateEventInvitationArgs): Promise<{
action: UPDATE_ACTION;
invitation?: RequireSome<EventInvitation, 'calendarEvent' | 'attendee'>;
}> => {
const { method, vevent: veventIcs, attendee: attendeeIcs } = invitationIcs;
const { calendarEvent, vevent: veventApi, attendee: attendeeApi } = invitationApi;
const partstatIcs = attendeeIcs?.partstat;
const partstatApi = attendeeApi?.partstat;
const attendeesApi = veventApi.attendee;
const recurrenceIdIcs = veventIcs['recurrence-id'];
const sequenceDiff = getSequence(veventIcs) - getSequence(veventApi);
if (
calendarData.isCalendarDisabled ||
getIsInvitationOutdated({ invitationIcs, invitationApi, isOrganizerMode }) ||
getIsInvitationFromFuture({ invitationIcs, invitationApi, isOrganizerMode }) ||
getIsEventCancelled(calendarEvent) ||
!attendeeIcs ||
!attendeeApi ||
getIsProtonInvite({
invitationIcs,
calendarEvent,
pmData,
})
) {
// do not update
return { action: NONE };
}
if (isOrganizerMode) {
// Some external providers also want us to update attendee status with a COUNTER method
const updateCounter =
method === ICAL_METHOD.COUNTER &&
partstatIcs &&
[ICAL_ATTENDEE_STATUS.ACCEPTED, ICAL_ATTENDEE_STATUS.DECLINED, ICAL_ATTENDEE_STATUS.TENTATIVE].includes(
partstatIcs
);
if (method === ICAL_METHOD.REPLY || updateCounter) {
if (!veventApi) {
if (!recurrenceIdIcs) {
return { action: NONE };
}
// In the future, create single edit. Not supported for now
return { action: NONE };
}
if (recurrenceIdIcs) {
// Replies to single edits not supported for the moment
return { action: NONE };
}
if (!partstatIcs || !partstatApi || !attendeesApi) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.UPDATING_ERROR);
}
try {
// update attendee partstat if needed
const updateTime = getUnixTime(
veventIcs.dtstamp ? propertyToUTCDate(veventIcs.dtstamp) : message.data.Time
);
if (attendeeApi.updateTime && updateTime <= attendeeApi.updateTime) {
return { action: NONE };
}
const updatedVevent = {
...veventApi,
attendee: modifyAttendeesPartstat(attendeesApi, { [attendeeApi.emailAddress]: partstatIcs }),
};
const updatedCalendarEvent = await updateEventApi({
calendarEvent,
vevent: updatedVevent,
hasDefaultNotifications: getHasDefaultNotifications(calendarEvent),
updateTime,
updatePartstat: attendeeIcs.partstat,
attendee: attendeeApi,
calendarData,
api,
getCanonicalEmailsMap,
overwrite: false,
});
const { invitation: updatedInvitation } = processEventInvitation(
{ vevent: updatedVevent, calendarEvent: updatedCalendarEvent },
message,
contactEmails,
ownAddresses
);
if (!getInvitationHasAttendee(updatedInvitation)) {
throw new Error('Missing attendee after update');
}
return {
action: UPDATE_PARTSTAT,
invitation: { ...updatedInvitation, calendarEvent: updatedCalendarEvent },
};
} catch (error: any) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.UPDATING_ERROR);
}
}
return { action: NONE };
}
// attendee mode
if (method === ICAL_METHOD.REQUEST) {
if (!veventApi) {
return { action: NONE };
}
const hasUpdatedDtstamp = getHasModifiedDtstamp(veventIcs, veventApi);
const hasUpdatedDateTimes = getHasModifiedDateTimes(veventIcs, veventApi);
const hasUpdatedTitle = veventIcs.summary?.value !== veventApi.summary?.value;
const hasUpdatedDescription = veventIcs.description?.value !== veventApi.description?.value;
const hasUpdatedLocation = veventIcs.location?.value !== veventApi.location?.value;
const hasUpdatedRrule = !getIsRruleEqual(veventIcs.rrule, veventApi.rrule);
const hasUpdatedAttendees = getHasModifiedAttendees({ veventIcs, veventApi, attendeeIcs, attendeeApi });
const hasBreakingChange = hasUpdatedDtstamp ? sequenceDiff > 0 : false;
const hasNonBreakingChange = hasUpdatedDtstamp
? hasUpdatedDateTimes ||
hasUpdatedTitle ||
hasUpdatedDescription ||
hasUpdatedLocation ||
hasUpdatedRrule ||
hasUpdatedAttendees
: false;
const action = hasBreakingChange ? RESET_PARTSTAT : hasNonBreakingChange ? KEEP_PARTSTAT : NONE;
if ([KEEP_PARTSTAT, RESET_PARTSTAT].includes(action)) {
// update the api event by the ics one with the appropriate answer
const createSingleEdit = getHasRecurrenceId(veventIcs) && !getHasRecurrenceId(veventApi);
const canCreateSingleEdit = createSingleEdit ? getCanCreateSingleEdit(veventIcs, veventApi) : undefined;
if (createSingleEdit && !canCreateSingleEdit) {
// The parent has been updated. Nothing to do then
return { action: NONE };
}
try {
if (!partstatIcs) {
throw new Error('Missing attendee parameters');
}
const veventIcsWithApiAlarms: VcalVeventComponent = {
...veventIcs,
components: [
...(veventIcs.components || []),
...(veventApi.components || []).filter((component) => getIsAlarmComponent(component)),
],
};
// alarms may need to be dropped when resetting the partstat
const { vevent: updatedVevent, hasDefaultNotifications } = getInvitedVeventWithAlarms({
vevent: veventIcsWithApiAlarms,
oldHasDefaultNotifications: getHasDefaultNotifications(calendarEvent),
partstat: partstatIcs,
calendarSettings: calendarData.calendarSettings,
oldPartstat: partstatApi,
});
const updatedPmVevent = await withPmAttendees(withDtstamp(updatedVevent), getCanonicalEmailsMap, true);
const updatedCalendarEvent = await updateEventApi({
calendarEvent,
vevent: updatedPmVevent,
hasDefaultNotifications,
calendarData,
createSingleEdit,
deleteIds: singleEditData?.map(({ ID }) => ID),
api,
getCanonicalEmailsMap,
overwrite,
});
const { invitation: updatedInvitation } = processEventInvitation(
{ vevent: updatedPmVevent, calendarEvent: updatedCalendarEvent },
message,
contactEmails,
ownAddresses
);
if (!getInvitationHasAttendee(updatedInvitation)) {
throw new Error('Missing attendee after update');
}
return { action, invitation: { ...updatedInvitation, calendarEvent: updatedCalendarEvent } };
} catch (error: any) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.UPDATING_ERROR);
}
}
return { action };
}
if (method === ICAL_METHOD.CANCEL) {
let cancel = false;
if (veventApi) {
if (getIsVeventCancelled(veventApi)) {
return { action: NONE };
}
cancel = true;
} else {
const parentExdates = parentInvitationApi?.vevent.exdate;
if (!recurrenceIdIcs || !parentExdates) {
return { action: NONE };
}
const isCancelled = parentExdates.find((exdate) => {
return +propertyToUTCDate(exdate) === +propertyToUTCDate(recurrenceIdIcs);
});
cancel = !isCancelled;
}
// cancel API event if needed
if (cancel) {
const createSingleEdit = getHasRecurrenceId(veventIcs) && !getHasRecurrenceId(veventApi);
const canCreateSingleEdit = createSingleEdit ? getCanCreateSingleEdit(veventIcs, veventApi) : undefined;
if (createSingleEdit && !canCreateSingleEdit) {
// The parent has been updated. Nothing to do then
return { action: NONE };
}
try {
const updatedVevent = createSingleEdit
? {
...omit(veventIcs, ['rrule']),
status: { value: CANCELLED },
}
: {
...veventApi,
dtstamp: veventIcs.dtstamp,
// on cancellation, sequence might be incremented, only the organizer knows
sequence: { value: veventIcs.sequence?.value || 0 },
status: { value: CANCELLED },
};
const { vevent, hasDefaultNotifications } = getInvitedVeventWithAlarms({
vevent: updatedVevent,
partstat: ICAL_ATTENDEE_STATUS.DECLINED,
});
await updateEventApi({
calendarEvent,
hasDefaultNotifications,
vevent,
calendarData,
createSingleEdit,
api,
getCanonicalEmailsMap,
overwrite,
});
const { invitation: updatedInvitation } = processEventInvitation(
{ vevent: updatedVevent },
message,
contactEmails,
ownAddresses
);
if (!getInvitationHasAttendee(updatedInvitation)) {
throw new Error('Missing attendee after update');
}
return { action: CANCEL, invitation: { ...updatedInvitation, calendarEvent } };
} catch (error: any) {
throw new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.CANCELLATION_ERROR);
}
}
return { action: RESET_PARTSTAT };
}
return { action: NONE };
};
export const deleteCalendarEventFromInvitation = ({
calendarEventID,
calendarData,
api,
}: {
calendarEventID: string;
calendarData: Required<CalendarWidgetData>;
api: Api;
}) => {
return api<SyncMultipleApiResponse>(
syncMultipleEvents(calendarData.calendar.ID, {
MemberID: calendarData.memberID,
Events: [{ ID: calendarEventID }],
})
);
};
export const createCalendarEventFromInvitation = async ({
vevent,
vcalAttendee,
partstat,
api,
getCanonicalEmailsMap,
calendarData,
pmData,
overwrite,
}: {
vevent: VcalVeventComponent;
vcalAttendee: VcalAttendeeProperty;
partstat: ICAL_ATTENDEE_STATUS;
calendarData?: CalendarWidgetData;
pmData?: PmInviteData;
api: Api;
getCanonicalEmailsMap: GetCanonicalEmailsMap;
overwrite: boolean;
}) => {
const { calendar, memberID, addressKeys, calendarKeys, calendarSettings } = calendarData || {};
if (!calendar || !memberID || !addressKeys || !calendarKeys || !calendarSettings) {
throw new Error('Missing data for creating calendar event from invitation');
}
// save attendee answer
const vcalAttendeeToSave = {
...vcalAttendee,
parameters: {
...vcalAttendee.parameters,
partstat,
},
};
// add alarms to event if necessary
const { vevent: veventToSave, hasDefaultNotifications } = getInvitedVeventWithAlarms({
vevent,
partstat,
calendarSettings,
});
const { index: attendeeIndex } = findAttendee(getAttendeeEmail(vcalAttendee), veventToSave.attendee);
if (!veventToSave.attendee || attendeeIndex === undefined || attendeeIndex === -1) {
throw new Error('Missing data for creating calendar event from invitation');
}
if (pmData) {
// we just need to send the new attendee to the API
veventToSave.attendee = [vcalAttendeeToSave];
} else {
veventToSave.attendee[attendeeIndex] = vcalAttendeeToSave;
}
const veventToSaveWithPmAttendees = await withPmAttendees(veventToSave, getCanonicalEmailsMap, true);
const vcalPmAttendeeToSave = pmData
? veventToSaveWithPmAttendees?.attendee?.[0]
: veventToSaveWithPmAttendees?.attendee?.[attendeeIndex];
if (!vcalPmAttendeeToSave) {
throw new Error('Failed to generate PM attendee');
}
// create calendar event
const payload = {
eventComponent: veventToSaveWithPmAttendees,
isCreateEvent: true,
isSwitchCalendar: false,
isInvitation: true,
hasDefaultNotifications,
...(await getCreationKeys({
newAddressKeys: addressKeys,
newCalendarKeys: calendarKeys,
decryptedSharedKeyPacket: pmData?.sharedSessionKey,
})),
};
const data = await createCalendarEvent(payload);
if (!getHasSharedKeyPacket(data) || !getHasSharedEventContent(data)) {
throw new Error('Missing shared data');
}
const Events: (CreateCalendarEventSyncData | CreateLinkedCalendarEventsSyncData)[] = pmData?.sharedEventID
? [
{
Overwrite: overwrite ? 1 : 0,
Event: {
SharedEventID: pmData.sharedEventID,
UID: veventToSave.uid.value,
IsOrganizer: 0,
...omit(data, ['SharedEventContent', 'AttendeesEventContent']),
},
},
]
: [
{
Overwrite: overwrite ? 1 : 0,
Event: { IsOrganizer: 0, Permissions: 1, ...data },
},
];
const {
Responses: [
{
Response: { Code, Event, Error: errorMessage },
},
],
} = await api<SyncMultipleApiResponse>({
...syncMultipleEvents(calendar.ID, { MemberID: memberID, Events }),
silence: true,
});
if (Code !== API_CODES.SINGLE_SUCCESS || !Event) {
throw new Error(errorMessage || 'Creating calendar event from invitation failed');
}
return {
savedEvent: Event,
savedVevent: veventToSaveWithPmAttendees,
savedVcalAttendee: vcalPmAttendeeToSave,
};
};
export const updatePartstatFromInvitation = async ({
veventApi,
calendarEvent,
veventIcs,
vcalAttendee,
attendeeToken,
partstat,
oldPartstat,
timestamp,
calendarData,
singleEditData,
api,
}: {
veventApi: VcalVeventComponent;
calendarEvent: CalendarEvent;
veventIcs: VcalVeventComponent;
vcalAttendee: VcalAttendeeProperty;
attendeeToken?: string;
partstat: ICAL_ATTENDEE_STATUS;
oldPartstat?: ICAL_ATTENDEE_STATUS;
timestamp: number;
calendarData?: CalendarWidgetData;
singleEditData?: CalendarEvent[];
api: Api;
}) => {
const { calendar, memberID, addressKeys, calendarSettings } = calendarData || {};
const primaryAddressKey = getPrimaryKey(addressKeys);
if (
!getHasAttendee(veventApi) ||
!getHasAttendee(veventIcs) ||
!calendar ||
!memberID ||
!primaryAddressKey ||
!calendarSettings
) {
throw new Error('Missing data for updating calendar event from invitation');
}
// update attendee partstat
const { ID: eventID, Attendees } = calendarEvent;
const isSingleEdit = getHasRecurrenceId(veventIcs);
const attendeeID = Attendees.find(({ Token }) => Token === attendeeToken)?.ID;
if (!attendeeID) {
throw new Error('Missing data for updating participation status');
}
const data = {
Status: toApiPartstat(partstat),
UpdateTime: getUnixTime(timestamp),
};
const { Event: updatedEvent } = await api<UpdateEventPartApiResponse>({
...updateAttendeePartstat(calendar.ID, eventID, attendeeID, data),
silence: true,
});
// reset single-edits partstats if necessary (if this step fails, we silently ignore it)
// we also need to drop alarms for the ones that had them
if (!isSingleEdit && singleEditData?.length && attendeeToken) {
try {
const { updatePartstatActions, updatePersonalPartActions } = getResetPartstatActions(
singleEditData,
attendeeToken,
partstat
);
const resetPartstatRequests = updatePartstatActions.map(
({ eventID, calendarID, attendeeID, updateTime, partstat }) =>
() =>
api<UpdateEventPartApiResponse>({
...updateAttendeePartstat(calendarID, eventID, attendeeID, {
Status: toApiPartstat(partstat),
UpdateTime: updateTime,
}),
silence: true,
})
);
const dropAlarmsRequests = updatePersonalPartActions.map(
({ eventID, calendarID }) =>
() =>
api<UpdateEventPartApiResponse>({
...updatePersonalEventPart(calendarID, eventID, { Notifications: [] }),
silence: true,
})
);
// the routes called in requests do not have any specific jail limit
// the limit per user session is 25k requests / 900s
const resetPartstatPromise = processApiRequestsSafe(resetPartstatRequests, 1000, 100 * 1000);
const dropAlarmsPromise = processApiRequestsSafe(dropAlarmsRequests, 1000, 100 * 1000);
await Promise.all([resetPartstatPromise, dropAlarmsPromise]);
} catch (e: any) {
noop();
}
}
// update alarms if necessary (if this step fails, we silently ignore it)
let savedEvent;
const emailAddress = getAttendeeEmail(vcalAttendee);
const veventToUpdate = { ...veventIcs, ...pick(veventApi, ['components', 'exdate']) };
const updatedVevent = {
...veventToUpdate,
attendee: modifyAttendeesPartstat(veventToUpdate.attendee, { [emailAddress]: partstat }),
};
const { vevent: veventToSave, hasDefaultNotifications } = getInvitedVeventWithAlarms({
vevent: updatedVevent,
partstat,
calendarSettings,
oldPartstat,
});
try {
const payload: CreateSinglePersonalEventData = {
Notifications: hasDefaultNotifications ? null : toApiNotifications(veventToSave.components),
};
const { Event } = await api<UpdateEventPartApiResponse>(updatePersonalEventPart(calendar.ID, eventID, payload));
savedEvent = Event;
} catch (e: any) {
noop();
}
const vcalAttendeeToSave = {
...vcalAttendee,
parameters: { ...vcalAttendee.parameters, partstat },
};
return {
savedEvent: savedEvent || updatedEvent,
savedVevent: savedEvent ? veventToSave : updatedVevent,
savedVcalAttendee: vcalAttendeeToSave,
};
};
| 3,849
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/calendar/inviteLink.tsx
|
import { getUnixTime } from 'date-fns';
import { c } from 'ttag';
import { AppLink, SettingsLink } from '@proton/components';
import { CALENDAR_SETTINGS_SECTION_ID, ICAL_ATTENDEE_STATUS, ICAL_METHOD } from '@proton/shared/lib/calendar/constants';
import { getInteroperabilityOperationsPath } from '@proton/shared/lib/calendar/settingsRoutes';
import { propertyToUTCDate } from '@proton/shared/lib/calendar/vcalConverter';
import { APPS, CALENDAR_APP_NAME } from '@proton/shared/lib/constants';
import { RequireSome } from '@proton/shared/lib/interfaces';
import OpenInCalendarButton from '../../components/message/extras/calendar/OpenInCalendarButton';
import { InvitationModel } from './invite';
export const getCalendarEventLink = (model: RequireSome<InvitationModel, 'invitationIcs'>) => {
const {
isOrganizerMode,
isImport,
hasMultipleVevents,
hideLink,
isPartyCrasher,
isOutdated,
isAddressActive,
calendarData,
invitationIcs: { method, attendee: attendeeIcs, vevent: veventIcs },
invitationApi,
hasNoCalendars,
canCreateCalendar,
hasDecryptionError,
} = model;
if (hideLink) {
return null;
}
const hasAlsoReplied =
attendeeIcs?.partstat &&
[ICAL_ATTENDEE_STATUS.ACCEPTED, ICAL_ATTENDEE_STATUS.TENTATIVE, ICAL_ATTENDEE_STATUS.DECLINED].includes(
attendeeIcs?.partstat
);
const canBeAdded = isImport;
const canBeAnswered =
!isOrganizerMode && method === ICAL_METHOD.REQUEST && !isOutdated && isAddressActive && !isImport;
const canBeManaged =
isOrganizerMode &&
(method === ICAL_METHOD.REPLY || (method === ICAL_METHOD.COUNTER && hasAlsoReplied)) &&
!isImport &&
!veventIcs['recurrence-id'];
const canBeSeenUpdated =
[ICAL_METHOD.CANCEL, ICAL_METHOD.COUNTER, ICAL_METHOD.REFRESH].includes(method) ||
(!isOrganizerMode && method === ICAL_METHOD.REQUEST && isOutdated);
const safeCalendarNeedsUserAction = calendarData?.calendarNeedsUserAction && !(isPartyCrasher && !isOrganizerMode);
// the calendar needs a user action to be active
if (safeCalendarNeedsUserAction) {
if (isImport) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>{c('Link')
.t`You need to activate your calendar keys to add this event`}</AppLink>
);
}
if (canBeManaged) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>{c('Link')
.t`You need to activate your calendar keys to manage this invitation`}</AppLink>
);
}
if (canBeAnswered) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>{c('Link')
.t`You need to activate your calendar keys to answer this invitation`}</AppLink>
);
}
if (canBeSeenUpdated && invitationApi) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>
{isOrganizerMode
? c('Link').t`You need to activate your calendar keys to see the updated event`
: c('Link').t`You need to activate your calendar keys to see the updated invitation`}
</AppLink>
);
}
return null;
}
if (isImport && hasMultipleVevents) {
return (
<SettingsLink
path={getInteroperabilityOperationsPath({ sectionId: CALENDAR_SETTINGS_SECTION_ID.IMPORT })}
app={APPS.PROTONCALENDAR}
>
{c('Link')
.t`This ICS file contains more than one event. Please download it and import the events in ${CALENDAR_APP_NAME}`}
</SettingsLink>
);
}
// the invitation is unanswered
if (!invitationApi) {
if (hasDecryptionError) {
// the event exists in the db but couldn't be decrypted
if (canBeManaged) {
return (
<SettingsLink path="/encryption-keys#addresses" app={APPS.PROTONMAIL}>
{c('Link').t`You need to reactivate your keys to manage this invitation`}
</SettingsLink>
);
}
if (canBeSeenUpdated) {
return (
<SettingsLink path="/encryption-keys#addresses" app={APPS.PROTONMAIL}>
{isOrganizerMode
? c('Link').t`You need to reactivate your keys to see the updated event`
: c('Link').t`You need to reactivate your keys to see the updated invitation`}
</SettingsLink>
);
}
}
if (hasNoCalendars && canCreateCalendar && !isPartyCrasher) {
if (canBeAdded) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>
{c('Link').t`Create a new calendar to add this event`}
</AppLink>
);
}
if (canBeAnswered) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>
{c('Link').t`Create a new calendar to answer this invitation`}
</AppLink>
);
}
if (canBeManaged) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>
{c('Link').t`Create a new calendar to manage your invitations`}
</AppLink>
);
}
}
return null;
}
// the invitation has been answered
const calendarID = calendarData?.calendar.ID || '';
const eventID = invitationApi?.calendarEvent.ID;
const recurrenceIDProperty = invitationApi?.vevent['recurrence-id'];
const recurrenceID = recurrenceIDProperty ? getUnixTime(propertyToUTCDate(recurrenceIDProperty)) : undefined;
const linkString = isOutdated
? c('Link').t`Open updated event in ${CALENDAR_APP_NAME}`
: c('Link').t`Open in ${CALENDAR_APP_NAME}`;
return (
<OpenInCalendarButton
linkString={linkString}
calendarID={calendarID}
eventID={eventID}
recurrenceID={recurrenceID}
/>
);
};
| 3,850
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/calendar/summary.ts
|
import { c } from 'ttag';
import { ICAL_ATTENDEE_STATUS, ICAL_METHOD } from '@proton/shared/lib/calendar/constants';
import { getIsVeventCancelled } from '@proton/shared/lib/calendar/vcalHelper';
import { RequireSome } from '@proton/shared/lib/interfaces/utils';
import { InvitationModel, UPDATE_ACTION } from './invite';
const { REPLY, COUNTER, REFRESH, REQUEST, CANCEL, ADD } = ICAL_METHOD;
const { ACCEPTED, TENTATIVE, DECLINED } = ICAL_ATTENDEE_STATUS;
const { KEEP_PARTSTAT, RESET_PARTSTAT } = UPDATE_ACTION;
export const getHasBeenUpdatedText = (model: RequireSome<InvitationModel, 'invitationIcs'>) => {
const { invitationIcs, invitationApi, isOutdated, isFromFuture, updateAction } = model;
const { method } = invitationIcs;
if (isFromFuture) {
return;
}
if (method === REPLY && invitationApi && invitationIcs.attendee?.partstat && isOutdated) {
return c('Calendar invite info').t`This response is out of date.`;
}
if (method === REQUEST && !isOutdated && updateAction && [KEEP_PARTSTAT, RESET_PARTSTAT].includes(updateAction)) {
return c('Calendar invite info').t`This event has been updated.`;
}
};
export const getOrganizerSummaryText = (model: RequireSome<InvitationModel, 'invitationIcs'>) => {
const {
invitationIcs: { method, attendee: attendeeIcs, vevent: veventIcs },
invitationApi,
hasNoCalendars,
hasDecryptionError,
isOutdated,
isFromFuture,
isPartyCrasher,
} = model;
const isSingleEdit = !!veventIcs['recurrence-id'];
if (!attendeeIcs) {
return null;
}
if (method === REPLY) {
if (!attendeeIcs.partstat) {
return null;
}
const { partstat } = attendeeIcs;
const participantName = attendeeIcs.displayName;
if (!invitationApi) {
if (hasNoCalendars) {
return c('Calendar invite info').t`This response is out of date. You have no calendars.`;
}
if (hasDecryptionError) {
// the event exists in the calendar but we couldn't decrypt it
if (partstat === ACCEPTED) {
if (isPartyCrasher) {
return c('Calendar invite info').t`${participantName} accepted an invitation to this event.`;
}
return c('Calendar invite info').t`${participantName} accepted your invitation.`;
}
if (partstat === DECLINED) {
if (isPartyCrasher) {
return c('Calendar invite info').t`${participantName} declined an invitation to this event.`;
}
return c('Calendar invite info').t`${participantName} declined your invitation.`;
}
if (partstat === TENTATIVE) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} tentatively accepted an invitation to this event.`;
}
return c('Calendar invite info').t`${participantName} tentatively accepted your invitation.`;
}
}
return c('Calendar invite info')
.t`This response is out of date. The event does not exist in your calendar anymore.`;
}
if (isFromFuture) {
return c('Calendar invite info')
.t`This response doesn't match your invitation details. Please verify the invitation details in your calendar.`;
}
if (isOutdated) {
if (partstat === ACCEPTED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had accepted an invitation to one occurrence of the event.`;
}
return c('Calendar invite info')
.t`${participantName} had previously accepted your invitation to one occurrence of the event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info').t`${participantName} had accepted an invitation to this event.`;
}
return c('Calendar invite info').t`${participantName} had previously accepted your invitation.`;
}
if (partstat === DECLINED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had declined an invitation to one occurrence of the event.`;
}
return c('Calendar invite info')
.t`${participantName} had previously declined your invitation to one occurrence of the event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info').t`${participantName} had declined an invitation to this event.`;
}
return c('Calendar invite info').t`${participantName} had previously declined your invitation.`;
}
if (partstat === TENTATIVE) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had tentatively accepted an invitation to one occurrence of the event.`;
}
return c('Calendar invite info')
.t`${participantName} had previously tentatively accepted your invitation to one occurrence of the event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had tentatively accepted an invitation to this event.`;
}
return c('Calendar invite info')
.t`${participantName} had previously tentatively accepted your invitation.`;
}
}
if (partstat === ACCEPTED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} accepted an invitation to one occurrence of the event.`;
}
return c('Calendar invite info')
.t`${participantName} accepted your invitation to one occurrence of the event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info').t`${participantName} accepted an invitation to this event.`;
}
return c('Calendar invite info').t`${participantName} accepted your invitation.`;
}
if (partstat === DECLINED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} declined an invitation to one occurrence of the event.`;
}
return c('Calendar invite info')
.t`${participantName} declined your invitation to one occurrence of the event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info').t`${participantName} declined an invitation to this event.`;
}
return c('Calendar invite info').t`${participantName} declined your invitation.`;
}
if (partstat === TENTATIVE) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} tentatively accepted an invitation to one occurrence of the event.`;
}
return c('Calendar invite info')
.t`${participantName} tentatively accepted your invitation to one occurrence of the event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} tentatively accepted an invitation to this event.`;
}
return c('Calendar invite info').t`${participantName} tentatively accepted your invitation.`;
}
}
if (method === COUNTER) {
// due to a scope problem with ttag (https://github.com/ttag-org/ttag-cli/issues/99),
// we need to introduce an artificial return here
return (() => {
const { displayName: participantName, partstat } = attendeeIcs;
if (!invitationApi) {
if (hasNoCalendars) {
if (isSingleEdit) {
return c('Calendar invite info')
.t`${participantName} had proposed a new time for one occurrence of this event. This proposal is out of date. You have no calendars.`;
}
return c('Calendar invite info')
.t`${participantName} had proposed a new time for this event. This proposal is out of date. You have no calendars.`;
}
if (hasDecryptionError) {
// the event exists in the calendar but we couldn't decrypt it
if (partstat === ACCEPTED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} accepted an invitation and proposed a new time for one occurrence of this event.`;
}
return c('Calendar invite info')
.t`${participantName} accepted your invitation and proposed a new time for one occurrence of this event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} accepted an invitation and proposed a new time for this event.`;
}
return c('Calendar invite info')
.t`${participantName} accepted your invitation and proposed a new time for this event.`;
}
if (partstat === DECLINED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} declined an invitation and proposed a new time for one occurrence of this event.`;
}
return c('Calendar invite info')
.t`${participantName} declined your invitation and proposed a new time for one occurrence of this event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} declined an invitation and proposed a new time for this event.`;
}
return c('Calendar invite info')
.t`${participantName} declined your invitation and proposed a new time for this event.`;
}
if (partstat === TENTATIVE) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} tentatively accepted an invitation and proposed a new time for one occurrence of this event.`;
}
return c('Calendar invite info')
.t`${participantName} tentatively accepted your invitation and proposed a new time for one occurrence of this event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} tentatively accepted an invitation and proposed a new time for this event.`;
}
return c('Calendar invite info')
.t`${participantName} tentatively accepted your invitation and proposed a new time for this event.`;
}
if (isSingleEdit) {
return c('Calendar invite info')
.t`${participantName} proposed a new time for one occurrence of this event.`;
}
return c('Calendar invite info').t`${participantName} proposed a new time for this event.`;
}
if (isSingleEdit) {
return c('Calendar invite info')
.t`${participantName} had proposed a new time for one occurrence of this event. This proposal is out of date. The event does not exist in your calendar anymore.`;
}
return c('Calendar invite info')
.t`${participantName} had proposed a new time for this event. This proposal is out of date. The event does not exist in your calendar anymore.`;
}
if (isFromFuture) {
return c('Calendar invite info')
.t`This new time proposal doesn't match your invitation details. Please verify the invitation details in your calendar.`;
}
if (isOutdated) {
if (partstat === ACCEPTED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had accepted an invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date.`;
}
return c('Calendar invite info')
.t`${participantName} had accepted your invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had accepted an invitation and proposed a new time for this event. Answer and proposal are out of date.`;
}
return c('Calendar invite info')
.t`${participantName} had accepted your invitation and proposed a new time for this event. Answer and proposal are out of date.`;
}
if (partstat === DECLINED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had declined an invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date.`;
}
return c('Calendar invite info')
.t`${participantName} had declined your invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had declined an invitation and proposed a new time for this event. Answer and proposal are out of date.`;
}
return c('Calendar invite info')
.t`${participantName} had declined your invitation and proposed a new time for this event. Answer and proposal are out of date.`;
}
if (partstat === TENTATIVE) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had tentatively accepted an invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date.`;
}
return c('Calendar invite info')
.t`${participantName} had tentatively accepted your invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} had tentatively accepted an invitation and proposed a new time for this event. Answer and proposal are out of date.`;
}
return c('Calendar invite info')
.t`${participantName} had tentatively accepted your invitation and proposed a new time for this event. Answer and proposal are out of date.`;
}
if (isSingleEdit) {
return c('Calendar invite info')
.t`${participantName} had proposed a new time for one occurrence of this event. This proposal is out of date.`;
}
return c('Calendar invite info')
.t`${participantName} had proposed a new time for this event. This proposal is out of date.`;
}
if (partstat === ACCEPTED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} accepted an invitation and proposed a new time for one occurrence of this event.`;
}
return c('Calendar invite info')
.t`${participantName} accepted your invitation and proposed a new time for one occurrence of this event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} accepted an invitation and proposed a new time for this event.`;
}
return c('Calendar invite info')
.t`${participantName} accepted your invitation and proposed a new time for this event.`;
}
if (partstat === DECLINED) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} declined an invitation and proposed a new time for one occurrence of this event.`;
}
return c('Calendar invite info')
.t`${participantName} declined your invitation and proposed a new time for one occurrence of this event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} declined an invitation and proposed a new time for this event.`;
}
return c('Calendar invite info')
.t`${participantName} declined your invitation and proposed a new time for this event.`;
}
if (partstat === TENTATIVE) {
if (isSingleEdit) {
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} tentatively accepted an invitation and proposed a new time for one occurrence of this event.`;
}
return c('Calendar invite info')
.t`${participantName} tentatively accepted your invitation and proposed a new time for one occurrence of this event.`;
}
if (isPartyCrasher) {
return c('Calendar invite info')
.t`${participantName} tentatively accepted an invitation and proposed a new time for this event.`;
}
return c('Calendar invite info')
.t`${participantName} tentatively accepted your invitation and proposed a new time for this event.`;
}
if (isSingleEdit) {
return c('Calendar invite info')
.t`${participantName} proposed a new time for one occurrence of this event.`;
}
return c('Calendar invite info').t`${participantName} proposed a new time for this event.`;
})();
}
if (method === REFRESH) {
// due to a scope problem with ttag (https://github.com/ttag-org/ttag-cli/issues/99),
// we need to introduce an artificial return here
return (() => {
const { displayName: participantName } = attendeeIcs;
const genericMessage = c('Calendar invite info').t`${participantName} asked for the latest event updates.`;
if (!invitationApi) {
if (hasNoCalendars) {
return c('Calendar invite info')
.t`${participantName} asked for the latest updates to an event which does not exist anymore. You have no calendars.`;
}
if (hasDecryptionError) {
// the event exists in the calendar but we couldn't decrypt it
return genericMessage;
}
return c('Calendar invite info')
.t`${participantName} asked for the latest updates to an event which does not exist in your calendar anymore.`;
}
if (isFromFuture) {
return c('Calendar invite info')
.t`${participantName} asked for the latest updates to an event which doesn't match your invitation details. Please verify the invitation details in your calendar.`;
}
return genericMessage;
})();
}
};
export const getAttendeeSummaryText = (model: RequireSome<InvitationModel, 'invitationIcs'>) => {
const { invitationIcs, invitationApi, isOutdated } = model;
const { method, attendee: attendeeIcs } = invitationIcs;
const { vevent: veventApi, attendee: attendeeApi } = invitationApi || {};
if (method === REQUEST) {
if (!veventApi) {
return null;
}
if (isOutdated) {
if (getIsVeventCancelled(veventApi)) {
return c('Calendar invite info').t`This invitation is out of date. The event has been canceled.`;
}
return c('Calendar invite info').t`This invitation is out of date. The event has been updated.`;
}
const partstat = (attendeeApi || attendeeIcs)?.partstat;
if (!partstat) {
return null;
}
if (partstat === ACCEPTED) {
return c('Calendar invite info').t`You already accepted this invitation.`;
}
if (partstat === TENTATIVE) {
return c('Calendar invite info').t`You already tentatively accepted this invitation.`;
}
if (partstat === DECLINED) {
return c('Calendar invite info').t`You already declined this invitation.`;
}
}
if (method === CANCEL) {
return c('Calendar invite info').t`This event has been canceled.`;
}
if (method === ADD) {
if (!veventApi) {
return c('Calendar invite info').t`This invitation is out of date. The event has been deleted.`;
}
if (isOutdated) {
if (getIsVeventCancelled(veventApi)) {
return c('Calendar invite info').t`This invitation is out of date. The event has been canceled.`;
}
return c('Calendar invite info').t`This invitation is out of date. The event has been updated.`;
}
// Adding occurrences is not supported for the moment. When we do we can recover the text
// return c('Calendar invite info').t`An occurrence has been added to the event ${veventIcsTitle}`;
return null;
}
};
| 3,851
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/checklist/checkedItemsStorage.test.ts
|
import { deleteCheckedItemsForUser, getSavedCheckedItemsForUser, saveCheckedItemsForUser } from './checkedItemsStorage';
describe('checkedItemsStorage', () => {
it('Should save checked items', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
const savedItems = getSavedCheckedItemsForUser('testUserId');
expect(savedItems).toEqual(['checkedAccount']);
});
it('Should delete data for user', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
deleteCheckedItemsForUser('testUserId');
const savedItems = getSavedCheckedItemsForUser('testUserId');
expect(savedItems).toEqual([]);
});
it('Should return empty array if no data', () => {
const savedItems = getSavedCheckedItemsForUser('testUserId');
expect(savedItems).toEqual([]);
});
it('Should return empty array if no data for user', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
const savedItems = getSavedCheckedItemsForUser('testOtherUserId');
expect(savedItems).toEqual([]);
});
it('Should not override other users data when present in storage', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
saveCheckedItemsForUser('testOtherUserId', ['checkedAccount2, checkedAccount3']);
const savedItems = getSavedCheckedItemsForUser('testUserId');
expect(savedItems).toEqual(['checkedAccount']);
});
it('Should not delete other user data when deleting data for one user', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
saveCheckedItemsForUser('testOtherUserId', ['checkedAccount2, checkedAccount3']);
deleteCheckedItemsForUser('testUserId');
const savedItems = getSavedCheckedItemsForUser('testOtherUserId');
expect(savedItems).toEqual(['checkedAccount2, checkedAccount3']);
});
it('Should return empty array for user not present in storage when multiple other users present', () => {
saveCheckedItemsForUser('testUserId', ['checkedAccount']);
saveCheckedItemsForUser('testOtherUserId', ['checkedAccount2, checkedAccount3']);
const savedItems = getSavedCheckedItemsForUser('testAnotherUserId');
expect(savedItems).toEqual([]);
});
});
| 3,852
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/checklist/checkedItemsStorage.ts
|
import { getItem, setItem } from '@proton/shared/lib/helpers/storage';
export const SESSIONS_STORAGE_KEY = 'checklistCheckedAccounts';
const getData = () => {
return JSON.parse(getItem(SESSIONS_STORAGE_KEY) || '{}');
};
export const saveCheckedItemsForUser = (userId: string, newCheckedItems: string[]) => {
const services = getData();
setItem(SESSIONS_STORAGE_KEY, JSON.stringify({ ...services, [userId]: { items: newCheckedItems } }));
};
export const getSavedCheckedItemsForUser = (userId: string) => {
const services = getData();
return services[userId]?.items ?? [];
};
export const deleteCheckedItemsForUser = (userId: string) => {
const services = getData();
delete services[userId];
setItem(SESSIONS_STORAGE_KEY, JSON.stringify(services));
};
| 3,853
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptedSearch/esAPI.ts
|
import { apiHelper } from '@proton/encrypted-search';
import { getConversation } from '@proton/shared/lib/api/conversations';
import { getEvents, getLatestID } from '@proton/shared/lib/api/events';
import { getMessage } from '@proton/shared/lib/api/messages';
import { Api } from '@proton/shared/lib/interfaces';
import { Message, MessageMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import { Event } from '../../models/event';
/**
* Get the latest event or all events since a specified one
*/
export const queryEvents = async (api: Api, lastEvent?: string, signal?: AbortSignal) => {
if (lastEvent) {
return apiHelper<Event>(api, signal, getEvents(lastEvent), 'getEvents');
}
return apiHelper<Event>(api, signal, getLatestID(), 'getLatestID');
};
/**
* Fetch one message
*/
export const queryMessage = async (api: Api, messageID: string, signal?: AbortSignal) => {
const result = await apiHelper<{ Message: Message }>(api, signal, getMessage(messageID), 'getMessage');
return result?.Message;
};
/**
* Fetch one conversation
*/
export const queryConversation = async (api: Api, conversationID: string, signal?: AbortSignal) => {
const result = await apiHelper<{ Messages: (Message | MessageMetadata)[] }>(
api,
signal,
getConversation(conversationID),
'getConversation'
);
return result?.Messages;
};
| 3,854
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptedSearch/esBuild.ts
|
import { AesGcmCiphertext, apiHelper } from '@proton/encrypted-search';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Api } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { GetMessageKeys } from '../../hooks/message/useGetMessageKeys';
import { ESBaseMessage, ESMessage, ESMessageContent } from '../../models/encryptedSearch';
import { locateBlockquote } from '../message/messageBlockquote';
import { decryptMessage } from '../message/messageDecrypt';
import { toText } from '../parserHtml';
import { queryMessage } from './esAPI';
/**
* Remove the specified tag from the given HTML element
*/
export const removeTag = (element: HTMLElement, tagName: string) => {
let removeTag = true;
while (removeTag) {
const tagInstances = element.getElementsByTagName(tagName);
const tagInstance = tagInstances.item(0);
if (tagInstance) {
tagInstance.remove();
}
removeTag = tagInstances.length !== 0;
}
};
/**
* Remove quoted text and HTML tags from body
*/
export const cleanText = (text: string, includeQuote: boolean) => {
const domParser = new DOMParser();
const { body } = domParser.parseFromString(text, 'text/html');
removeTag(body, 'style');
removeTag(body, 'script');
let content = body.innerHTML;
if (!includeQuote) {
const [noQuoteContent] = locateBlockquote(body);
content = noQuoteContent;
}
// Introduce new lines after every div, because the toText function joins
// the content of consecutive divs together and this might introduce
// unwanted matches. Then remove redundant consecutive new lines
return toText(content.replaceAll('</div>', '</div><br>'))
.replace(/\n{2,}/g, '\n')
.trim();
};
/**
* Turn a range of supersets of the ESBaseMessage interface into an ESBaseMessage object
*/
export const getBaseMessage = (message: Message | ESMessage) => {
const baseMessage: ESBaseMessage = {
ID: message.ID,
ConversationID: message.ConversationID,
Subject: message.Subject,
Unread: message.Unread,
Sender: message.Sender,
Flags: message.Flags,
AddressID: message.AddressID,
IsReplied: message.IsReplied,
IsRepliedAll: message.IsRepliedAll,
IsForwarded: message.IsForwarded,
ToList: message.ToList,
CCList: message.CCList,
BCCList: message.BCCList,
Size: message.Size,
NumAttachments: message.NumAttachments,
ExpirationTime: message.ExpirationTime,
LabelIDs: message.LabelIDs,
Time: message.Time,
Order: message.Order,
AttachmentInfo: message.AttachmentInfo,
SnoozeTime: message.SnoozeTime,
};
return baseMessage;
};
/**
* Extract the ExternalID from the In-Reply-To header of the given message
*/
export const getExternalID = ({ ParsedHeaders }: Message) => {
let ExternalID = ParsedHeaders['In-Reply-To'];
if (typeof ExternalID === 'string') {
if (ExternalID[0] === '<' && ExternalID[ExternalID.length - 1] === '>') {
ExternalID = ExternalID.slice(1, ExternalID.length - 1);
}
return ExternalID;
}
};
const EXTERNAL_ID_QUERY_CACHE = new Map<string, Promise<{ Total: number } | undefined>>();
const getExternalIdQueryKey = (ExternalID: string, ConversationID: string) => `${ExternalID}-${ConversationID}`;
/**
* Check whether the given ExternalID exists in the given conversation
*/
export const externalIDExists = async (ExternalID: string, ConversationID: string, api: Api) => {
const cacheKey = getExternalIdQueryKey(ExternalID, ConversationID);
let promise = EXTERNAL_ID_QUERY_CACHE.get(cacheKey);
if (!promise) {
promise = apiHelper<{ Total: number }>(
api,
undefined,
{
method: 'get',
url: 'mail/v4/messages',
params: {
ExternalID,
ConversationID,
},
},
'externalIDExists'
);
EXTERNAL_ID_QUERY_CACHE.set(cacheKey, promise);
}
const response = await promise;
return !!response && response.Total > 0;
};
/**
* Check whether quoted content has to be indexed or not by checking
* whether the ExternalID inside the given message's In-Reply-To header
* exists in the user's mailbox
*/
const shouldIndexQuotedContent = async (message: Message, api: Api) => {
const ExternalID = getExternalID(message);
if (typeof ExternalID === 'string') {
return !(await externalIDExists(ExternalID, message.ConversationID, api));
}
return true;
};
/**
* Fetches a message and return a ESMessage
*/
export const fetchMessage = async (
messageID: string,
api: Api,
getMessageKeys: GetMessageKeys,
signal?: AbortSignal
): Promise<ESMessageContent | undefined> => {
const message = await queryMessage(api, messageID, signal);
if (!message) {
return;
}
const keys = await getMessageKeys(message);
const decryptionResult = await decryptMessage(message, keys.privateKeys);
let decryptedSubject: string | undefined;
let decryptedBody: string | undefined;
let mimetype: MIME_TYPES | undefined;
if (!decryptionResult.errors) {
({ decryptedSubject, decryptedBody, mimetype } = decryptionResult);
} else {
// Decryption can legitimately fail if there are inactive keys. In this
// case the above three variables are left undefined
return {};
}
const includeQuote = await shouldIndexQuotedContent(message, api);
const cleanDecryptedBody =
typeof decryptedBody === 'string'
? (mimetype || message.MIMEType) === MIME_TYPES.DEFAULT
? cleanText(decryptedBody, includeQuote)
: decryptedBody
: undefined;
return {
decryptedBody: cleanDecryptedBody,
decryptedSubject,
};
};
export const prepareCiphertext = (itemToStore: ESMessage, aesGcmCiphertext: AesGcmCiphertext) => {
const { ID, Time, Order, LabelIDs } = itemToStore;
return {
ID,
Time,
Order,
LabelIDs,
aesGcmCiphertext,
};
};
| 3,855
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptedSearch/esSearch.ts
|
import { normalizeKeyword } from '@proton/encrypted-search';
import { Recipient } from '@proton/shared/lib/interfaces';
import { ESMessage, NormalizedSearchParams } from '../../models/encryptedSearch';
import { Filter, SearchParameters, Sort } from '../../models/tools';
import { isExpired } from '../expiration';
/**
* Remove wildcard, normalise keyword and recipients
*/
export const normaliseSearchParams = (
searchParams: SearchParameters,
labelID: string,
filter?: Filter,
sort?: Sort
) => {
const { wildcard, keyword, to, from, ...otherParams } = searchParams;
let normalizedKeywords: string[] | undefined;
if (keyword) {
normalizedKeywords = normalizeKeyword(keyword);
}
const normalisedSearchParams: NormalizedSearchParams = {
labelID,
search: {
from: from ? from.toLocaleLowerCase() : undefined,
to: to ? to.toLocaleLowerCase() : undefined,
...otherParams,
},
normalizedKeywords,
filter: filter || {},
sort: sort || { sort: 'Time', desc: true },
};
return normalisedSearchParams;
};
/**
* Test whether a given message fulfills every metadata requirement
*/
export const testMetadata = (
normalisedSearchParams: NormalizedSearchParams,
messageToSearch: ESMessage,
recipients: string[],
sender: string[]
) => {
const { search, labelID, filter } = normalisedSearchParams;
const { address, from, to, begin, end } = search || {};
const { AddressID, Time, LabelIDs, NumAttachments, Unread } = messageToSearch;
if (
!LabelIDs.includes(labelID) ||
(address && AddressID !== address) ||
isExpired(messageToSearch) ||
(begin && Time < begin) ||
(end && Time > end) ||
(from && !sender.some((string) => string.includes(from))) ||
(to && !recipients.some((string) => string.includes(to))) ||
(filter?.Attachments && NumAttachments === 0) ||
(typeof filter?.Unread !== 'undefined' && filter?.Unread !== Unread)
) {
return false;
}
return true;
};
/**
* Check whether only sorting changed and, if so, only sort existing results
* rather than executing a new search
*/
export const shouldOnlySortResults = (
normalisedSearchParams: NormalizedSearchParams,
previousNormSearchParams: NormalizedSearchParams
) => {
const {
labelID,
filter,
search: { address, from, to, begin, end },
normalizedKeywords,
} = normalisedSearchParams;
const {
labelID: prevLabelID,
filter: prevFilter,
search: { address: prevAddress, from: prevFrom, to: prevTo, begin: prevBegin, end: prevEnd },
normalizedKeywords: prevNormalisedKeywords,
} = previousNormSearchParams;
// In case search parameters are different, then a new search is needed
if (
labelID !== prevLabelID ||
address !== prevAddress ||
from !== prevFrom ||
to !== prevTo ||
begin !== prevBegin ||
end !== prevEnd ||
!!normalizedKeywords !== !!prevNormalisedKeywords ||
filter?.Attachments !== prevFilter?.Attachments ||
filter?.Unread !== prevFilter?.Unread
) {
return false;
}
// Same goes for keywords
if (normalizedKeywords && prevNormalisedKeywords) {
if (normalizedKeywords.length !== prevNormalisedKeywords.length) {
return false;
}
for (let i = 0; i < normalizedKeywords.length; i++) {
if (normalizedKeywords[i] !== prevNormalisedKeywords[i]) {
return false;
}
}
}
return true;
};
/**
* Serialize a recipient
*/
export const transformRecipients = (recipients: Recipient[]) => [
...recipients.map((recipient) => recipient.Address.toLocaleLowerCase()),
...recipients.map((recipient) => recipient.Name.toLocaleLowerCase()),
];
| 3,856
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptedSearch/esSync.ts
|
import {
ESEvent,
ESTimepoint,
ES_SYNC_ACTIONS,
EventsObject,
hasReactivatedKey,
openESDB,
} from '@proton/encrypted-search';
import { EVENT_ACTIONS } from '@proton/shared/lib/constants';
import { LabelCount } from '@proton/shared/lib/interfaces';
import { MAIL_EVENTLOOP_NAME } from '../../constants';
import { ESBaseMessage } from '../../models/encryptedSearch';
import { Event } from '../../models/event';
import { getBaseMessage } from './esBuild';
import { getTotalMessages } from './esUtils';
const eventConversionObject = Object.fromEntries([
[EVENT_ACTIONS.CREATE, ES_SYNC_ACTIONS.CREATE],
[EVENT_ACTIONS.UPDATE, ES_SYNC_ACTIONS.UPDATE_CONTENT],
[EVENT_ACTIONS.UPDATE_DRAFT, ES_SYNC_ACTIONS.UPDATE_CONTENT],
[EVENT_ACTIONS.UPDATE_FLAGS, ES_SYNC_ACTIONS.UPDATE_METADATA],
[EVENT_ACTIONS.DELETE, ES_SYNC_ACTIONS.DELETE],
]);
export const convertEventType = (event: Event, numAddresses: number): ESEvent<ESBaseMessage> | undefined => {
const { EventID, Refresh, Messages: MessageEvents, Addresses: AddressEvents } = event;
if (!EventID) {
return;
}
const attemptReDecryption = hasReactivatedKey({ AddressEvents, numAddresses });
const Items = !MessageEvents
? undefined
: MessageEvents.map(({ ID, Action, Message }) => {
return {
ID,
Action: eventConversionObject[Action],
ItemMetadata: !!Message ? getBaseMessage(Message) : undefined,
};
});
let eventsToStore: EventsObject = {};
eventsToStore[MAIL_EVENTLOOP_NAME] = EventID;
return {
Refresh,
Items,
attemptReDecryption,
eventsToStore,
};
};
/**
* Return the IDs in the metadata table that are not in the content table
*/
export const findRecoveryPoint = async (userID: string) => {
const esDB = await openESDB(userID);
if (!esDB) {
return;
}
const contentIDs = new Set(await esDB.getAllKeys('content'));
const metadataIDs = await esDB.getAllKeysFromIndex('metadata', 'temporal');
metadataIDs.reverse();
const result: {
timepoint?: ESTimepoint;
contentLen: number;
metadataLen: number;
} = {
contentLen: contentIDs.size,
metadataLen: metadataIDs.length,
};
for (let i = 0; i < metadataIDs.length; i++) {
if (!contentIDs.has(metadataIDs[i])) {
if (i === 0) {
return result;
}
// The recoveryPoint that content indexing expects refers to the last
// indexed content, not the first missing one
const ciphertext = await esDB.get('metadata', metadataIDs[i - 1]);
esDB.close();
if (ciphertext) {
result.timepoint = ciphertext.timepoint;
return result;
}
}
}
esDB.close();
};
export const getTotal = (getMessageCounts: () => Promise<LabelCount[]>) => async () => {
const messageCounts = await getMessageCounts();
return getTotalMessages(messageCounts);
};
| 3,857
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptedSearch/esUtils.ts
|
import { History, Location } from 'history';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { isMobile } from '@proton/shared/lib/helpers/browser';
import { LabelCount, UserModel } from '@proton/shared/lib/interfaces';
import { LABEL_IDS_TO_HUMAN } from '../../constants';
import { isSearch as checkIsSearch } from '../elements';
import {
extractSearchParameters,
filterFromUrl,
getParamsFromPathname,
pageFromUrl,
setSortInUrl,
sortFromUrl,
} from '../mailboxUrl';
import { normaliseSearchParams } from './esSearch';
/**
* Read the current total amount of messages
*/
export const getTotalMessages = async (messageCounts: LabelCount[]) => {
return messageCounts.find((labelCount) => labelCount?.LabelID === MAILBOX_LABEL_IDS.ALL_MAIL)?.Total || 0;
};
/**
* Determine the label ID of the folders specified in the URL
*/
const getLabelID = (location: Location) => {
const { params } = getParamsFromPathname(location.pathname);
const { labelID: humanLabelID } = params;
let labelID = '';
let label: keyof typeof LABEL_IDS_TO_HUMAN;
for (label in LABEL_IDS_TO_HUMAN) {
if (humanLabelID === (LABEL_IDS_TO_HUMAN[label] as any)) {
labelID = label;
}
}
if (labelID === '') {
labelID = humanLabelID;
}
return labelID;
};
/**
* Parse search parameters from URL
*/
export const parseSearchParams = (location: Location) => {
const searchParameters = extractSearchParameters(location);
const isSearch = checkIsSearch(searchParameters);
return {
isSearch,
page: pageFromUrl(location),
esSearchParams: isSearch
? normaliseSearchParams(
searchParameters,
getLabelID(location),
filterFromUrl(location),
sortFromUrl(location)
)
: undefined,
};
};
/**
* Reset sort in URL, e.g because ES doesn't support SIZE sort
*/
export const resetSort = (history: History) => {
history.push(setSortInUrl(history.location, { sort: 'Time', desc: true }));
};
export const isEncryptedSearchAvailable = (user: UserModel, isESUserInterfaceAvailable: boolean) => {
if (isMobile()) {
return false;
}
if (user.isPaid) {
return true;
}
return isESUserInterfaceAvailable;
};
// Do not prefix with ES: to not be cleared by removeESFlags function
export const getESFreeBlobKey = (userID: string) => `${userID}:InitialIndexing`;
| 3,858
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptedSearch/index.ts
|
export * from './esAPI';
export * from './esBuild';
export * from './esSearch';
export * from './esSync';
export * from './esUtils';
export * from './mailESCallbacks';
| 3,859
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/encryptedSearch/mailESCallbacks.tsx
|
import { History } from 'history';
import {
CachedItem,
ESCallbacks,
ESEvent,
ESItemInfo,
ESStatusBooleans,
ESTimepoint,
ES_BACKGROUND_METADATA_BATCH,
ES_MAX_METADATA_BATCH,
ES_MAX_PARALLEL_ITEMS,
EncryptedItemWithInfo,
EventsObject,
RecordProgress,
apiHelper,
buildContentDB,
checkVersionedESDB,
encryptItem,
esSentryReport,
executeContentOperations,
metadataIndexingProgress,
readLastEvent,
readMetadataItem,
readNumContent,
testKeywords,
} from '@proton/encrypted-search';
import { queryMessageMetadata } from '@proton/shared/lib/api/messages';
import { MAILBOX_LABEL_IDS, MIME_TYPES } from '@proton/shared/lib/constants';
import { EVENT_ERRORS } from '@proton/shared/lib/errors';
import { hasBit } from '@proton/shared/lib/helpers/bitset';
import { Api, LabelCount, UserModel } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { getRecipients } from '@proton/shared/lib/mail/messages';
import isTruthy from '@proton/utils/isTruthy';
import { MAIL_EVENTLOOP_NAME } from '../../constants';
import { GetMessageKeys } from '../../hooks/message/useGetMessageKeys';
import {
ESBaseMessage,
ESMessage,
ESMessageContent,
MetadataRecoveryPoint,
NormalizedSearchParams,
} from '../../models/encryptedSearch';
import { Event } from '../../models/event';
import { decryptMessage } from '../message/messageDecrypt';
import { queryConversation, queryEvents, queryMessage } from './esAPI';
import { cleanText, externalIDExists, fetchMessage, getBaseMessage, getExternalID } from './esBuild';
import { shouldOnlySortResults, testMetadata, transformRecipients } from './esSearch';
import { convertEventType, findRecoveryPoint, getTotal } from './esSync';
import { parseSearchParams as parseSearchParamsMail, resetSort } from './esUtils';
interface Props {
getMessageKeys: GetMessageKeys;
getMessageCounts: () => Promise<LabelCount[]>;
api: Api;
user: UserModel;
history: History;
numAddresses: number;
}
export const getItemInfo = (item: ESBaseMessage | ESMessage): ESItemInfo => ({
ID: item.ID,
timepoint: [item.Time, item.Order],
});
export const getESCallbacks = ({
getMessageKeys,
getMessageCounts,
api,
user,
history,
numAddresses,
}: Props): ESCallbacks<ESBaseMessage, NormalizedSearchParams, ESMessageContent> => {
const { ID: userID } = user;
const getSearchInterval = (esSearchParameters: NormalizedSearchParams) => ({
begin: esSearchParameters.begin,
end: esSearchParameters.end,
});
const fetchESItemContent = (itemID: string, abortSignal?: AbortSignal) =>
fetchMessage(itemID, api, getMessageKeys, abortSignal);
// We need to keep the recovery point for metadata indexing in memory
// for cases where IDB couldn't be instantiated but we still want to
// index content
let metadataRecoveryPoint: MetadataRecoveryPoint | undefined;
const queryItemsMetadata = async (
signal: AbortSignal,
isBackgroundIndexing?: boolean
): Promise<{
resultMetadata?: ESBaseMessage[];
setRecoveryPoint?: (setIDB?: boolean) => Promise<void>;
}> => {
const messagesPromises: Promise<ESBaseMessage[] | undefined>[] = [];
const Messages: ESBaseMessage[] = [];
const numPagesFetched = isBackgroundIndexing ? ES_BACKGROUND_METADATA_BATCH : ES_MAX_METADATA_BATCH;
let recoveryPoint: MetadataRecoveryPoint | undefined = metadataRecoveryPoint;
// Note that indexing, and therefore an instance of this function,
// can exist even without an IDB, because we can index in memory only.
// Therefore, we have to check if an IDB exists before querying it
const esdbExists = await checkVersionedESDB(userID);
if (!recoveryPoint && esdbExists) {
recoveryPoint = await metadataIndexingProgress.readRecoveryPoint(userID);
}
const total = await getTotal(getMessageCounts)();
const numPages = Math.ceil(total / ES_MAX_PARALLEL_ITEMS);
let Page = 0;
while (Page < numPagesFetched && Page < numPages) {
messagesPromises[Page] = apiHelper<{ Messages: Message[] }>(
api,
signal,
queryMessageMetadata({
PageSize: ES_MAX_PARALLEL_ITEMS,
Location: MAILBOX_LABEL_IDS.ALL_MAIL,
Sort: 'Time',
Desc: 1,
Page,
End: recoveryPoint?.End,
EndID: recoveryPoint?.EndID,
}),
'queryMessageMetadata'
).then((result) => {
if (!result) {
return;
}
return result.Messages.map((message) => getBaseMessage(message));
});
Page++;
}
if (messagesPromises.length) {
const awaitedMessages = await Promise.all(messagesPromises);
// We only want to return messages metadata up until the first
// undefined, which means a failed batch, to avoid leaving holes
// in the indexe metadata
for (const batch of awaitedMessages) {
if (!batch) {
break;
}
Messages.push(...batch);
}
}
if (signal.aborted) {
return {};
}
// Fetching is over
if (!Messages.length) {
return { resultMetadata: [] };
}
const lastMessage = Messages[Messages.length - 1];
const newRecoveryPoint = {
End: lastMessage.Time,
EndID: lastMessage.ID,
};
return {
resultMetadata: Messages,
setRecoveryPoint: esdbExists
? async (setIDB: boolean = true) => {
metadataRecoveryPoint = newRecoveryPoint;
if (setIDB) {
await metadataIndexingProgress.setRecoveryPoint(userID, newRecoveryPoint);
}
}
: undefined,
};
};
const checkIsReverse = (esSearchParams: NormalizedSearchParams) => esSearchParams.sort.desc;
const getKeywords = (esSearchParams: NormalizedSearchParams) => esSearchParams.normalizedKeywords;
const getSearchParams = () => {
const { isSearch, esSearchParams } = parseSearchParamsMail(history.location);
return {
isSearch,
esSearchParams,
};
};
const getPreviousEventID = async (): Promise<EventsObject> => {
const event = await queryEvents(api);
if (!event || !event.EventID) {
return {};
}
let eventsToStore: EventsObject = {};
eventsToStore[MAIL_EVENTLOOP_NAME] = event.EventID;
return eventsToStore;
};
const getEventFromIDB = async (
previousEventsObject?: EventsObject
): Promise<{
newEvents: ESEvent<ESBaseMessage>[];
shouldRefresh: boolean;
eventsToStore: EventsObject;
}> => {
let lastEventID: string;
if (previousEventsObject) {
lastEventID = previousEventsObject[MAIL_EVENTLOOP_NAME];
} else {
const storedEventID = await readLastEvent(userID, MAIL_EVENTLOOP_NAME);
if (!storedEventID) {
throw new Error('Event ID from IDB not found');
}
lastEventID = storedEventID;
}
const initialEvent = await queryEvents(api, lastEventID);
if (!initialEvent) {
throw new Error('Event fetch failed');
}
// We want to sync all items, potentially in multiple batches if the More flag
// is set. Even it isn't, we still fetch a further batch and, if the event ID hasn't
// changed, we can be sure nothing else has happened and the syncing process is considered
// successful
let keepSyncing = true;
let index = 0;
const newEvents: Event[] = [initialEvent];
while (keepSyncing) {
try {
const nextEventToCheck = newEvents[index++];
const newEventToCheck = await queryEvents(api, nextEventToCheck.EventID);
if (!newEventToCheck || !newEventToCheck.EventID) {
throw new Error('No event found');
}
keepSyncing = nextEventToCheck.More === 1 || newEventToCheck.EventID !== nextEventToCheck.EventID;
if (keepSyncing) {
newEvents.push(newEventToCheck);
}
} catch (error: any) {
esSentryReport('getEventFromIDB: queryEvents', { error });
return getEventFromIDB();
}
}
const { EventID } = newEvents[newEvents.length - 1];
if (!EventID) {
throw new Error('Last event has no ID');
}
let eventsToStore: EventsObject = {};
eventsToStore[MAIL_EVENTLOOP_NAME] = EventID;
const esEvents: ESEvent<ESBaseMessage>[] = newEvents
.map((event) => convertEventType(event, numAddresses))
.filter(isTruthy);
return {
newEvents: esEvents,
shouldRefresh: esEvents.some((event) => {
return hasBit(event.Refresh, EVENT_ERRORS.MAIL);
}),
eventsToStore,
};
};
const searchKeywords = (
keywords: string[],
itemToSearch: CachedItem<ESBaseMessage, ESMessageContent>,
hasApostrophe: boolean
) => {
const { metadata, content } = itemToSearch;
const recipients = transformRecipients(getRecipients(metadata));
const sender = transformRecipients([metadata.Sender]);
let result = testKeywords(keywords, [metadata.Subject, ...recipients, ...sender], hasApostrophe);
if (!content) {
return result;
}
const { decryptedBody, decryptedSubject } = content;
return result || testKeywords(keywords, [decryptedSubject || '', decryptedBody || ''], hasApostrophe);
};
const applyFilters = (esSearchParams: NormalizedSearchParams, metadata: ESBaseMessage) => {
const { Sender } = metadata;
const recipients = transformRecipients(getRecipients(metadata));
const sender = transformRecipients([Sender]);
return testMetadata(esSearchParams, metadata, recipients, sender);
};
// If a message is deleted, ideally we would like to re-index all messages that have its
// ExternalID in their In-Reply-To header (for simplicity we only check those in the same
// conversation). However, by the time the deletion event is processed by the client, the
// deleted message no longer exists on the server therefore we have no way of knowing its
// ExternalID, because we don't store this information in the index. Therefore, we re-index
// the content of all messages newer than the deleted one and within the same conversation
// whose In-Reply-To header exists but doesn't belong to the mailbox
const onContentDeletion = async (ID: string, indexKey: CryptoKey) => {
const metadata = await readMetadataItem<ESBaseMessage>(userID, ID, indexKey);
if (!metadata) {
return;
}
const { ConversationID, Time: deletedTime, Order: deletedOrder } = metadata;
const messages = (await queryConversation(api, ConversationID)) || []; // We fallback to [] because the conversation may not exist anymore
const messagesToAdd: EncryptedItemWithInfo[] = (
await Promise.all(
messages.map(async (message) => {
const { ID: messageID, Time, Order } = message;
if (Time < deletedTime || (Time === deletedTime && Order < deletedOrder)) {
return;
}
// When querying a conversation, one message is already populated with all fields,
// while all others have only metadata
let contentMessage: Message;
if (Object.hasOwn(message, 'ParsedHeaders')) {
contentMessage = message as Message;
} else {
const fullMessage = await queryMessage(api, messageID);
if (!fullMessage) {
throw new Error('Failed message fetching of item to reindex');
}
contentMessage = fullMessage;
}
const ExternalID = getExternalID(contentMessage);
if (typeof ExternalID === 'string') {
const shouldReindex = !(await externalIDExists(ExternalID, ConversationID, api));
if (shouldReindex) {
const keys = await getMessageKeys(contentMessage);
const decryptionResult = await decryptMessage(contentMessage, keys.privateKeys);
let decryptedSubject: string | undefined;
let decryptedBody: string | undefined;
let mimetype: MIME_TYPES | undefined;
if (!decryptionResult.errors) {
({ decryptedSubject, decryptedBody, mimetype } = decryptionResult);
} else {
return;
}
const cleanDecryptedBody =
typeof decryptedBody === 'string'
? (mimetype || contentMessage.MIMEType) === MIME_TYPES.DEFAULT
? cleanText(decryptedBody, true)
: decryptedBody
: undefined;
const aesGcmCiphertext = await encryptItem(
{
decryptedBody: cleanDecryptedBody,
decryptedSubject,
},
indexKey
);
const timepoint: ESTimepoint = [Time, Order];
return { ID: messageID, timepoint, aesGcmCiphertext };
}
}
})
)
).filter(isTruthy);
if (messagesToAdd.length) {
await executeContentOperations(userID, [], messagesToAdd);
}
};
/**
* When an old key is activated, try to correct any previous decryption errors
*/
const correctDecryptionErrors = async (
userID: string,
indexKey: CryptoKey,
abortIndexingRef: React.MutableRefObject<AbortController>,
esStatus: ESStatusBooleans,
recordProgress: RecordProgress
) => {
const recoveryPoint = await findRecoveryPoint(userID);
if (!esStatus.contentIndexingDone || !recoveryPoint) {
// There are no items for which decryption failed
return 0;
}
const { timepoint, contentLen, metadataLen } = recoveryPoint;
const total = metadataLen - contentLen;
void recordProgress([0, total], 'content');
const recordProgressLocal = (progress: number) => recordProgress(progress, 'content');
await buildContentDB(
userID,
indexKey,
abortIndexingRef,
recordProgressLocal,
fetchESItemContent,
timepoint,
false
);
const count = (await readNumContent(userID)) || 0;
return count - contentLen;
};
return {
getItemInfo,
fetchESItemContent,
queryItemsMetadata,
applyFilters,
checkIsReverse,
shouldOnlySortResults,
getTotalItems: getTotal(getMessageCounts),
getKeywords,
getSearchParams,
resetSort: () => resetSort(history),
getPreviousEventID,
getEventFromIDB,
searchKeywords,
getSearchInterval,
onContentDeletion,
correctDecryptionErrors,
};
};
| 3,860
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/eo/eoUrl.ts
|
export type EOUrlParams = {
id?: string;
};
| 3,861
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/eo/message.ts
|
import { CryptoProxy } from '@proton/crypto';
import { Recipient } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { EOMessage } from '../../logic/eo/eoType';
import { MessageState } from '../../logic/messages/messagesTypes';
export const eoDecrypt = async (encryptedValue: string, password: string) => {
const { data } = await CryptoProxy.decryptMessage({ armoredMessage: encryptedValue, passwords: [password] });
return data;
};
export const convertEOtoMessageState = (eoMessage: EOMessage, localID: string): MessageState => {
return {
localID,
data: {
ConversationID: 'eoConversation',
Subject: eoMessage.Subject,
Sender: eoMessage.Sender,
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
ToList: eoMessage.ToList,
CCList: eoMessage.CCList,
BCCList: [] as Recipient[],
Time: eoMessage.Time,
NumAttachments: eoMessage.NumAttachments,
ExpirationTime: eoMessage.ExpirationTime,
Body: eoMessage.Body,
Attachments: eoMessage.Attachments,
LabelIDs: ['0'],
MIMEType: eoMessage.MIMEType,
EORecipient: { Name: eoMessage.Recipient, Address: eoMessage.Recipient } as Recipient,
} as Message,
} as MessageState;
};
| 3,862
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/cleanMessage.tsx
|
import { Recipient } from '@proton/shared/lib/interfaces/Address';
import { MessageWithOptionalBody } from '../../logic/messages/messagesTypes';
/**
* Remove duplicate recipients from a recipient list
*/
const uniqueRecipientList = (recipients: Recipient[]) => {
const seenAddresses = new Set<string>();
return recipients.reduce<Recipient[]>((acc, recipient) => {
if (seenAddresses.has(recipient.Address)) {
return acc;
}
seenAddresses.add(recipient.Address);
acc.push(recipient);
return acc;
}, []);
};
/**
* Remove duplicate emails from a message
*/
export const uniqueMessageRecipients = (message: MessageWithOptionalBody) => {
const newToList = uniqueRecipientList(message.ToList as Recipient[]);
const newCCList = uniqueRecipientList(message.CCList as Recipient[]);
const newBCCList = uniqueRecipientList(message.BCCList as Recipient[]);
return { ...message, ToList: newToList, CCList: newCCList, BCCList: newBCCList };
};
export const removeMessageRecipients = (message: MessageWithOptionalBody, emailAddresses: string[]) => {
const newToList = message.ToList?.filter(({ Address }) => !emailAddresses?.includes(Address as string));
const newCCList = message.CCList?.filter(({ Address }) => !emailAddresses?.includes(Address as string));
const newBCCList = message.BCCList?.filter(({ Address }) => !emailAddresses?.includes(Address as string));
return { ...message, ToList: newToList, CCList: newCCList, BCCList: newBCCList };
};
| 3,863
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/icon.test.ts
|
import { PublicKeyReference } from '@proton/crypto';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { KeyTransparencyActivation } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { SIGNATURE_START, VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import {
ENCRYPTION_PREFERENCES_ERROR_TYPES,
EncryptionPreferencesError,
} from '@proton/shared/lib/mail/encryptionPreferences';
import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings';
import { MessageState, MessageVerification } from '../../logic/messages/messagesTypes';
import { STATUS_ICONS_FILLS, StatusIcon, X_PM_HEADERS } from '../../models/crypto';
import {
getReceivedStatusIcon,
getSendStatusIcon,
getSentStatusIcon,
getSentStatusIconInfo,
getStatusIconName,
} from './icon';
const { NOT_SIGNED, NOT_VERIFIED, SIGNED_AND_VALID, SIGNED_AND_INVALID } = VERIFICATION_STATUS;
const fakeKey1: PublicKeyReference = {
getFingerprint() {
return 'fakeKey1';
},
getUserIDs: () => ['<user@pm.me>'],
} as PublicKeyReference;
describe('icon', () => {
describe('getSendStatusIcon', () => {
const ktActivation = KeyTransparencyActivation.DISABLED;
it('should return a blue plain lock when sending to internal users without pinned keys', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PM,
mimeType: MIME_TYPES.DEFAULT,
hasApiKeys: true,
hasPinnedKeys: false,
isPublicKeyPinned: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'End-to-end encrypted',
});
});
it('should return a blue lock with checkmark when sending to internal users with a pinned key', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PM,
mimeType: MIME_TYPES.DEFAULT,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'End-to-end encrypted to verified recipient',
});
});
it('should return an error sign when sending to internal users with pinned keys, but the pinned key is not used', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PM,
mimeType: MIME_TYPES.DEFAULT,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: false,
encryptionDisabled: false,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_NOT_PINNED,
'test error'
),
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-danger',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.FAIL,
text: 'test error',
});
});
it('should return a green plain lock when sending to WKD users without pinned keys', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_INLINE,
mimeType: MIME_TYPES.PLAINTEXT,
hasApiKeys: true,
hasPinnedKeys: false,
isPublicKeyPinned: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'End-to-end encrypted',
});
});
it('should return a green lock with checkmark when sending to WKD users with a pinned key', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'End-to-end encrypted to verified recipient',
});
});
it('should return ar error sign when sending to WKD users with pinned keys, but the pinned key is not used', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: false,
encryptionDisabled: false,
error: new EncryptionPreferencesError(
ENCRYPTION_PREFERENCES_ERROR_TYPES.PRIMARY_NOT_PINNED,
'test error'
),
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-danger',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.FAIL,
text: 'test error',
});
});
it('should return a green lock with warning sign when sending to WKD users without pinned keys with warnings', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: true,
hasPinnedKeys: false,
isPublicKeyPinned: false,
encryptionDisabled: false,
warnings: ['warning test 1', 'warning test 2'],
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.WARNING,
text: "End-to-end encrypted. Recipient's key validation failed: warning test 1; warning test 2",
});
});
it('should return a green lock with warning sign when sending to WKD users with pinned keys with warnings', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: true,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
warnings: ['warning test 1', 'warning test 2'],
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.WARNING,
text: "End-to-end encrypted. Recipient's key validation failed: warning test 1; warning test 2",
});
});
it('should return a green open lock for external PGP messages only signed', () => {
const sendPreferences = {
encrypt: false,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: false,
hasPinnedKeys: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.SIGN,
text: 'PGP-signed',
});
});
it('should return a green lock with pencil sign for external PGP-encrypted (and signed) messages', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_INLINE,
mimeType: MIME_TYPES.PLAINTEXT,
hasApiKeys: false,
hasPinnedKeys: true,
isPublicKeyPinned: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.SIGN,
text: 'PGP-encrypted',
});
});
it('should return a green lock with checkmark for external PGP messages if encrypted with a pinned key', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: false,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'PGP-encrypted to verified recipient',
});
});
it('should return a green lock with warning sign for external PGP messages with warnings on the pinned key', () => {
const sendPreferences = {
encrypt: true,
sign: true,
pgpScheme: PACKAGE_TYPE.SEND_PGP_MIME,
mimeType: MIME_TYPES.MIME,
hasApiKeys: false,
hasPinnedKeys: true,
isPublicKeyPinned: true,
encryptionDisabled: false,
warnings: ['warning test 1', 'warning test 2'],
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.WARNING,
text: "PGP-encrypted. Recipient's key validation failed: warning test 1; warning test 2",
});
});
it('should return nothing when sending unencrypted and unsigned', () => {
const sendPreferences = {
encrypt: false,
sign: false,
pgpScheme: PACKAGE_TYPE.SEND_CLEAR,
mimeType: MIME_TYPES.MIME,
hasApiKeys: false,
hasPinnedKeys: false,
isPublicKeyPinned: false,
encryptionDisabled: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toBeUndefined();
});
describe('when encryption is disabled', () => {
it('should return a black plain lock with "Zero-access" message', () => {
const sendPreferences = {
encryptionDisabled: true,
encrypt: false,
sign: false,
pgpScheme: PACKAGE_TYPE.SEND_CLEAR,
mimeType: MIME_TYPES.DEFAULT,
hasApiKeys: false,
hasPinnedKeys: false,
isPublicKeyPinned: false,
};
expect(getSendStatusIcon(sendPreferences, ktActivation)).toMatchObject({
colorClassName: 'color-norm',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Zero-access encrypted. Recipient has disabled end-to-end encryption on their account.',
});
});
});
});
describe('getSentStatusIcon for imported sent message', () => {
it('should display black padlock icon', () => {
const globalIcon = getSentStatusIcon({
mapAuthentication: {},
mapEncryption: {},
contentEncryption: X_PM_HEADERS.ON_DELIVERY,
emailAddress: undefined,
isImported: true,
});
expect(globalIcon?.colorClassName).toBe('color-norm');
});
});
describe('getSentStatusIcon for individual recipients', () => {
const email = 'test@pm.me';
const getIconFromHeaders = (headers: { [key: string]: string }, emailAddress: string) => {
const message = {
data: {
ParsedHeaders: headers,
},
} as unknown as MessageState;
const { mapStatusIcon } = getSentStatusIconInfo(message) || {};
return mapStatusIcon[emailAddress];
};
it('should return no lock for messages sent by you neither encrypted nor authenticated', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=none',
'X-Pm-Recipient-Encryption': 'test%40pm.me=none',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toEqual(undefined);
});
it('should return a green plain lock for messages sent by Proton Mail encrypted but not authenticated to PGP recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=none',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-inline',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Encrypted by Proton Mail to PGP recipient',
});
});
it('should return a green lock with pencil for messages sent by you authenticated but not encrypted to PGP recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-inline',
'X-Pm-Recipient-Encryption': 'test%40pm.me=none',
'X-Pm-Content-Encryption': 'on-compose',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: false,
fill: STATUS_ICONS_FILLS.SIGN,
text: 'PGP-signed',
});
});
it('should return a blue lock with check-mark for messages sent by you encrypted to a Proton Mail recipient with pinned keys', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm-pinned',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'End-to-end encrypted to verified recipient',
});
});
it('should return a green plain lock for messages sent by you encrypted and authenticated to PGP recipient with pinned keys', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-mime-pinned',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'End-to-end encrypted to verified PGP recipient',
});
});
it('should return a blue plain lock for messages sent by you encrypted and authenticated to Proton Mail recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'End-to-end encrypted',
});
});
it('should return a blue plain lock for messages sent by Proton Mail encrypted and authenticated to Proton Mail recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Encrypted by Proton Mail',
});
});
it('should return a blue lock with check mark for messages sent by Proton Mail encrypted and authenticated to Proton Mail recipient with pinned keys', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm-pinned',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'Encrypted by Proton Mail to verified recipient',
});
});
it('should return a green plain lock for messages sent by Proton Mail encrypted and authenticated to PGP recipient with pinned keys', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-mime-pinned',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'Encrypted by Proton Mail to verified PGP recipient',
});
});
it('should return a blue plain lock for messages sent by you encrypted-to-outside', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-eo',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-eo',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'End-to-end encrypted',
});
});
it('should return undefined when the headers are missing', () => {
const headers = {};
const icon = getIconFromHeaders(headers, email);
expect(icon).toEqual(undefined);
});
it('should return undefined when the headers do not contain the email address', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption': 'testing%40pm.me=pgp-pm',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers, email);
expect(icon).toEqual(undefined);
});
});
describe('getSentStatusIcon for aggregated icon', () => {
const getIconFromHeaders = (headers: { [key: string]: string }) => {
const message = {
data: {
ParsedHeaders: headers,
},
} as unknown as MessageState;
const { globalIcon } = getSentStatusIconInfo(message);
return globalIcon;
};
it('should return a blue lock with checkmark when sending to all pinned with some internal', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-pm',
'X-Pm-Recipient-Encryption':
'test%40pm.me=pgp-mime-pinned;test2%40pm.me=pgp-inline-pinned;test3%40pm.me=pgp-pm-pinned',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'Sent by you with end-to-end encryption to verified recipients',
});
});
it('should return a green lock with checkmark when sending to all pinned external', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime;test2%40pm.me=pgp-inline',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-mime-pinned;test2%40pm.me=pgp-inline-pinned;',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.CHECKMARK,
text: 'Sent by Proton Mail with zero-access encryption to verified recipients',
});
});
it('should return a blue plain lock with checkmark when sending EO', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-eo',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-eo;',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Sent by you with end-to-end encryption',
});
});
it('should return a green plain lock when sending to some not pinned external', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-mime;test2%40pm.me=pgp-inline',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-mime-pinned;test2%40pm.me=pgp-inline;',
'X-Pm-Content-Encryption': 'on-delivery',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-success',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Sent by Proton Mail with zero-access encryption',
});
});
it('should return a blue plain lock when sending encrypted to mixed recipients', () => {
const headers = {
'X-Pm-Recipient-Authentication': 'test%40pm.me=pgp-pm;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-eo',
'X-Pm-Recipient-Encryption': 'test%40pm.me=pgp-pm-pinned;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-eo',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Sent by you with end-to-end encryption',
});
});
it('should fall back to a blue lock when the email was not sent encrypted to some recipient', () => {
const headers = {
'X-Pm-Recipient-Authentication':
'test%40pm.me=pgp-pm;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-eo;test4%40pm.me=none',
'X-Pm-Recipient-Encryption':
'test%40pm.me=pgp-pm-pinned;test2%40pm.me=pgp-inline;test3%40pm.me=pgp-eo;test4%40pm.me=none',
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Stored with zero-access encryption',
});
});
it('should fall back to a blue lock when some headers are missing', () => {
const headers = {
'X-Pm-Content-Encryption': 'end-to-end',
};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Stored with zero-access encryption',
});
});
it('should fall back to a blue lock when there are no headers', () => {
const headers = {};
const icon = getIconFromHeaders(headers);
expect(icon).toMatchObject({
colorClassName: 'color-info',
isEncrypted: true,
fill: STATUS_ICONS_FILLS.PLAIN,
text: 'Stored with zero-access encryption',
});
});
});
describe('getReceivedStatusIcon', () => {
it.each`
origin | encryption | pinnedKeys | pinnedKeysVerified | verificationStatus | colorClassName | iconName | text
${'internal'} | ${'on-delivery'} | ${[]} | ${false} | ${NOT_VERIFIED} | ${'color-info'} | ${'lock-filled'} | ${'Sent by Proton Mail with zero-access encryption'}
${'internal'} | ${'end-to-end'} | ${[]} | ${false} | ${NOT_SIGNED} | ${'color-info'} | ${'lock-filled'} | ${'End-to-end encrypted message'}
${'internal'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${NOT_SIGNED} | ${'color-info'} | ${'lock-exclamation-filled'} | ${'Sender could not be verified: Message not signed'}
${'internal'} | ${'end-to-end'} | ${[]} | ${false} | ${NOT_VERIFIED} | ${'color-info'} | ${'lock-filled'} | ${'End-to-end encrypted and signed message'}
${'internal'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_VALID} | ${'color-info'} | ${'lock-check-filled'} | ${'End-to-end encrypted message from verified sender'}
${'internal'} | ${'end-to-end'} | ${[fakeKey1]} | ${false} | ${SIGNED_AND_VALID} | ${'color-info'} | ${'lock-exclamation-filled'} | ${"Sender's trusted keys verification failed"}
${'internal'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_INVALID} | ${'color-info'} | ${'lock-exclamation-filled'} | ${'Sender verification failed'}
${'external'} | ${'end-to-end'} | ${[]} | ${false} | ${NOT_SIGNED} | ${'color-success'} | ${'lock-filled'} | ${'PGP-encrypted message'}
${'external'} | ${'end-to-end'} | ${[]} | ${false} | ${NOT_VERIFIED} | ${'color-success'} | ${'lock-pen-filled'} | ${'PGP-encrypted and signed message'}
${'external'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_VALID} | ${'color-success'} | ${'lock-check-filled'} | ${'PGP-encrypted message from verified sender'}
${'external'} | ${'end-to-end'} | ${[fakeKey1]} | ${false} | ${SIGNED_AND_VALID} | ${'color-success'} | ${'lock-exclamation-filled'} | ${"Sender's trusted keys verification failed"}
${'external'} | ${'end-to-end'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_INVALID} | ${'color-success'} | ${'lock-exclamation-filled'} | ${'Sender verification failed'}
${'external'} | ${'on-delivery'} | ${[]} | ${false} | ${NOT_VERIFIED} | ${'color-success'} | ${'lock-open-pen-filled'} | ${'PGP-signed message'}
${'external'} | ${'on-delivery'} | ${[fakeKey1]} | ${true} | ${SIGNED_AND_VALID} | ${'color-success'} | ${'lock-open-check-filled'} | ${'PGP-signed message from verified sender'}
${'external'} | ${'on-delivery'} | ${[fakeKey1]} | ${false} | ${SIGNED_AND_VALID} | ${'color-success'} | ${'lock-open-exclamation-filled'} | ${"Sender's trusted keys verification failed"}
${'external'} | ${'on-delivery'} | ${[fakeKey1]} | ${false} | ${SIGNED_AND_INVALID} | ${'color-success'} | ${'lock-open-exclamation-filled'} | ${'PGP-signed message. Sender verification failed'}
${'external'} | ${'on-delivery'} | ${[]} | ${false} | ${NOT_SIGNED} | ${'color-norm'} | ${'lock-filled'} | ${'Stored with zero-access encryption'}
`(
'should use color $colorClassName, lock $iconName when origin $origin, encryption $encryption, verified pinned keys $pinnedKeysVerified and verification status $verificationStatus',
({
origin,
encryption,
pinnedKeys,
pinnedKeysVerified,
verificationStatus,
colorClassName,
iconName,
text,
}) => {
const headers = {
'X-Pm-Origin': origin,
'X-Pm-Content-Encryption': encryption,
} as any;
const message = {
Time: SIGNATURE_START.USER + 10 * 1000,
ParsedHeaders: headers,
} as Message;
const verification = {
senderPinnedKeys: pinnedKeys,
verificationStatus,
pinnedKeysVerified,
} as MessageVerification;
const icon = getReceivedStatusIcon(message, verification, KeyTransparencyActivation.DISABLED);
const statusIconName = getStatusIconName(icon as StatusIcon);
expect(icon?.colorClassName).toBe(colorClassName);
expect(icon?.text).toBe(text);
expect(statusIconName).toBe(iconName);
}
);
});
});
| 3,864
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/icon.ts
|
import { c, msgid } from 'ttag';
import { KEY_VERIFICATION_ERROR_MESSAGE } from '@proton/shared/lib/api/helpers/getPublicKeysEmailHelper';
import { MAIL_APP_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { KT_VERIFICATION_STATUS, KeyTransparencyActivation } from '@proton/shared/lib/interfaces';
import { SendPreferences } from '@proton/shared/lib/interfaces/mail/crypto';
import { SIGNATURE_START, VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings';
import { getParsedHeadersFirstValue, hasProtonSender, inSigningPeriod } from '@proton/shared/lib/mail/messages';
import { MessageState, MessageVerification, MessageWithOptionalBody } from '../../logic/messages/messagesTypes';
import { MapStatusIcons, STATUS_ICONS_FILLS, StatusIcon, X_PM_HEADERS } from '../../models/crypto';
// The logic for determining the status icons can be found in Confluence under the title
// Encryption status for outgoing and incoming email
const { SEND_PM, SEND_EO, SEND_PGP_INLINE, SEND_PGP_MIME } = PACKAGE_TYPE;
const { NOT_VERIFIED, NOT_SIGNED, SIGNED_AND_INVALID, SIGNED_AND_VALID } = VERIFICATION_STATUS;
const { PLAIN, CHECKMARK, SIGN, WARNING, FAIL } = STATUS_ICONS_FILLS;
const {
NONE,
PGP_INLINE,
PGP_INLINE_PINNED,
PGP_MIME,
PGP_MIME_PINNED,
PGP_PM,
PGP_PM_PINNED,
PGP_EO,
INTERNAL,
EXTERNAL,
END_TO_END,
ON_COMPOSE,
ON_DELIVERY,
} = X_PM_HEADERS;
export interface MessageViewIcons {
globalIcon?: StatusIcon;
mapStatusIcon: MapStatusIcons;
}
const getMapEmailHeaders = (headers?: string): { [key: string]: X_PM_HEADERS } => {
if (!headers) {
return {};
}
const splitHeaders = headers.split(';').map((str) => decodeURIComponent(str.trim()));
return splitHeaders.reduce<{ [key: string]: X_PM_HEADERS }>((acc, header) => {
const match = header.match(/(.*)=(.*)/);
if (!match) {
return acc;
}
const [, emailAddress, emailHeader] = match;
acc[emailAddress] = emailHeader as X_PM_HEADERS;
return acc;
}, {});
};
export const getSendStatusIcon = (
sendPreferences: SendPreferences,
ktActivation: KeyTransparencyActivation
): StatusIcon | undefined => {
const { encrypt, pgpScheme, hasApiKeys, isPublicKeyPinned, warnings, error, ktVerificationResult } =
sendPreferences;
const ktActivated = ktActivation === KeyTransparencyActivation.SHOW_UI;
const validationErrorsMessage = warnings?.join('; ');
const warningsText = validationErrorsMessage
? c('Key validation warning').t`Recipient's key validation failed: ${validationErrorsMessage}`
: undefined;
if (error) {
// Special text for KT errors in composer
const errorMessage =
error.message === KEY_VERIFICATION_ERROR_MESSAGE
? c('loc_nightly: Composer email icon').t`Unable to send to this address at this time`
: error.message;
return { colorClassName: 'color-danger', isEncrypted: false, fill: FAIL, text: errorMessage };
}
if (sendPreferences.encryptionDisabled) {
return {
colorClassName: 'color-norm',
isEncrypted: false,
fill: PLAIN,
text: c('email_forwarding_2023: Composer email icon')
.t`Zero-access encrypted. Recipient has disabled end-to-end encryption on their account.`,
};
}
const ktVerificationStatus = ktVerificationResult?.status;
if (pgpScheme === SEND_PM) {
const result = { colorClassName: 'color-info', isEncrypted: true };
if (ktActivated && ktVerificationStatus === KT_VERIFICATION_STATUS.UNVERIFIED_KEYS) {
return {
...result,
fill: WARNING,
text: c('loc_nightly: Composer email icon').t`End-to-end encrypted without Key Transparency`,
};
}
if (isPublicKeyPinned) {
return {
...result,
fill: CHECKMARK,
text: c('Composer email icon').t`End-to-end encrypted to verified recipient`,
};
}
return {
...result,
fill: PLAIN,
text: c('Composer email icon').t`End-to-end encrypted`,
};
}
if (pgpScheme === SEND_EO) {
return {
colorClassName: 'color-info',
isEncrypted: true,
fill: PLAIN,
text: c('Composer email icon').t`End-to-end encrypted`,
};
}
if ([SEND_PGP_INLINE, SEND_PGP_MIME].includes(pgpScheme)) {
// sign must be true to fall in here
const result = { colorClassName: 'color-success', isEncrypted: encrypt };
if (warningsText) {
if (hasApiKeys) {
return {
...result,
fill: WARNING,
text: c('Composer email icon').t`End-to-end encrypted. ${warningsText}`,
};
}
return {
...result,
fill: WARNING,
text: c('Composer email icon').t`PGP-encrypted. ${warningsText}`,
};
}
if (encrypt) {
if (isPublicKeyPinned) {
if (hasApiKeys) {
return {
...result,
fill: CHECKMARK,
text: c('Composer email icon').t`End-to-end encrypted to verified recipient`,
};
}
return {
...result,
fill: CHECKMARK,
text: c('Composer email icon').t`PGP-encrypted to verified recipient`,
};
}
if (hasApiKeys) {
return { ...result, fill: PLAIN, text: c('Composer email icon').t`End-to-end encrypted` };
}
return { ...result, fill: SIGN, text: c('Composer email icon').t`PGP-encrypted` };
}
return { ...result, fill: SIGN, text: c('Composer email icon').t`PGP-signed` };
}
};
interface Params {
mapAuthentication: { [key: string]: X_PM_HEADERS };
mapEncryption: { [key: string]: X_PM_HEADERS };
contentEncryption: X_PM_HEADERS;
emailAddress?: string;
isImported: boolean;
}
export const getSentStatusIcon = ({
mapAuthentication,
mapEncryption,
contentEncryption,
emailAddress,
isImported,
}: Params): StatusIcon | undefined => {
if (!emailAddress) {
// we return the aggregated send icon in this case
const encryptions = Object.values(mapEncryption);
const hasHeaderInfo = !!encryptions.length;
const allExternal =
hasHeaderInfo && !encryptions.some((encryption) => [PGP_PM, PGP_PM_PINNED, PGP_EO].includes(encryption));
const allPinned =
hasHeaderInfo &&
!encryptions.some(
(encryption) => ![PGP_PM_PINNED, PGP_MIME_PINNED, PGP_INLINE_PINNED].includes(encryption)
);
const allEncrypted = hasHeaderInfo && !encryptions.some((encryption) => encryption === NONE);
if (allPinned) {
const text =
contentEncryption === END_TO_END
? c('Sent email icon').ngettext(
msgid`Sent by you with end-to-end encryption to verified recipient`,
`Sent by you with end-to-end encryption to verified recipients`,
encryptions.length
)
: c('Sent email icon').ngettext(
msgid`Sent by ${MAIL_APP_NAME} with zero-access encryption to verified recipient`,
`Sent by ${MAIL_APP_NAME} with zero-access encryption to verified recipients`,
encryptions.length
);
return {
colorClassName: allExternal ? 'color-success' : 'color-info',
isEncrypted: true,
fill: CHECKMARK,
text,
};
}
if (allEncrypted) {
return {
colorClassName: allExternal ? 'color-success' : 'color-info',
isEncrypted: true,
fill: PLAIN,
text:
contentEncryption === END_TO_END
? c('Sent email icon').t`Sent by you with end-to-end encryption`
: c('Sent email icon').t`Sent by ${MAIL_APP_NAME} with zero-access encryption`,
};
}
return {
colorClassName: isImported ? 'color-norm' : 'color-info',
isEncrypted: true,
fill: PLAIN,
text: c('Sent email icon').t`Stored with zero-access encryption`,
};
}
const [authentication, encryption] = [mapAuthentication[emailAddress], mapEncryption[emailAddress]];
if (encryption === NONE && [PGP_INLINE, PGP_MIME].includes(authentication)) {
if (contentEncryption !== ON_COMPOSE) {
return;
}
return {
colorClassName: 'color-success',
isEncrypted: false,
fill: SIGN,
text: c('Sent email icon').t`PGP-signed`,
};
}
if ([PGP_INLINE, PGP_MIME].includes(encryption) && [NONE, PGP_INLINE, PGP_MIME].includes(authentication)) {
return {
colorClassName: 'color-success',
isEncrypted: true,
fill: PLAIN,
text:
contentEncryption === END_TO_END
? c('Sent email icon').t`End-to-end encrypted to PGP recipient`
: c('Sent email icon').t`Encrypted by ${MAIL_APP_NAME} to PGP recipient`,
};
}
if (
[PGP_INLINE_PINNED, PGP_MIME_PINNED].includes(encryption) &&
[NONE, PGP_INLINE, PGP_MIME].includes(authentication)
) {
return {
colorClassName: 'color-success',
isEncrypted: true,
fill: CHECKMARK,
text:
contentEncryption === END_TO_END
? c('Sent email icon').t`End-to-end encrypted to verified PGP recipient`
: c('Sent email icon').t`Encrypted by ${MAIL_APP_NAME} to verified PGP recipient`,
};
}
if (authentication === PGP_EO && encryption === PGP_EO) {
return {
colorClassName: 'color-info',
isEncrypted: true,
fill: PLAIN,
text:
contentEncryption === END_TO_END
? c('Sent email icon').t`End-to-end encrypted`
: c('Sent email icon').t`Encrypted by ${MAIL_APP_NAME}`,
};
}
if (encryption === PGP_PM && [NONE, PGP_PM].includes(authentication)) {
return {
colorClassName: 'color-info',
isEncrypted: true,
fill: PLAIN,
text:
contentEncryption === END_TO_END
? c('Sent email icon').t`End-to-end encrypted`
: c('Sent email icon').t`Encrypted by ${MAIL_APP_NAME}`,
};
}
if (encryption === PGP_PM_PINNED && [NONE, PGP_PM].includes(authentication)) {
return {
colorClassName: 'color-info',
isEncrypted: true,
fill: CHECKMARK,
text:
contentEncryption === END_TO_END
? c('Sent email icon').t`End-to-end encrypted to verified recipient`
: c('Sent email icon').t`Encrypted by ${MAIL_APP_NAME} to verified recipient`,
};
}
};
export const getSentStatusIconInfo = (message: MessageState): MessageViewIcons => {
if (!message.data?.ParsedHeaders) {
return { mapStatusIcon: {} };
}
const mapAuthentication = getMapEmailHeaders(
getParsedHeadersFirstValue(message.data, 'X-Pm-Recipient-Authentication')
);
const mapEncryption = getMapEmailHeaders(getParsedHeadersFirstValue(message.data, 'X-Pm-Recipient-Encryption'));
const contentEncryption = getParsedHeadersFirstValue(message.data, 'X-Pm-Content-Encryption') as X_PM_HEADERS;
const isImported = getParsedHeadersFirstValue(message.data, 'X-Pm-Origin') === 'import';
const globalIcon = getSentStatusIcon({ mapAuthentication, mapEncryption, contentEncryption, isImported });
const mapStatusIcon = Object.keys(mapAuthentication).reduce<MapStatusIcons>((acc, emailAddress) => {
acc[emailAddress] = getSentStatusIcon({
mapAuthentication,
mapEncryption,
contentEncryption,
emailAddress,
isImported,
});
return acc;
}, {});
return { globalIcon, mapStatusIcon };
};
const getInternalMessageText = (verificationStatus: VERIFICATION_STATUS | undefined): string => {
switch (verificationStatus) {
case NOT_SIGNED:
return c('loc_nightly: Received email icon').t`End-to-end encrypted message with no signature`;
case SIGNED_AND_VALID:
case SIGNED_AND_INVALID:
return c('loc_nightly: Received email icon').t`End-to-end encrypted signed message`;
default:
return c('loc_nightly: Received email icon').t`End-to-end encrypted message`;
}
};
const getReceivedStatusIconInternalWithKT = (
message: MessageWithOptionalBody,
verification: MessageVerification,
endToEndEncrypted: boolean
): StatusIcon | undefined => {
if (!endToEndEncrypted) {
return {
colorClassName: 'color-norm',
isEncrypted: false,
fill: PLAIN,
text: c('loc_nightly: Received email icon').t`Stored with zero-access encryption`,
};
}
const {
verificationStatus,
senderPinnedKeys,
pinnedKeysVerified,
signingPublicKey,
signingPublicKeyIsPinned,
signingPublicKeyIsCompromised,
ktVerificationResult,
apiKeysErrors,
} = verification;
const ktVerificationStatus = ktVerificationResult?.status;
const hasPinnedKeys = !!senderPinnedKeys?.length;
const messageEncryptionDetails = getInternalMessageText(verificationStatus);
const result = { colorClassName: 'color-info', isEncrypted: true, messageEncryptionDetails };
const verificationErrorsMessage = verification.verificationErrors
?.map(({ message }) => message)
.filter(Boolean)
.join('; ');
const warningResult = {
...result,
text: c('loc_nightly: Signature verification warning').t`Sender verification failed`,
fill: WARNING,
};
if (apiKeysErrors?.length) {
// Special text for KT errors in message details
const errorMessage =
apiKeysErrors[0] === KEY_VERIFICATION_ERROR_MESSAGE
? c('loc_nightly: Composer email icon').t`Unable to verify sender at this time.`
: apiKeysErrors[0];
return {
...warningResult,
senderVerificationDetails: {
description: errorMessage,
},
};
}
if (verificationErrorsMessage) {
return {
...warningResult,
senderVerificationDetails: {
description: c('loc_nightly: Sender verification error')
.t`Sender verification failed: ${verificationErrorsMessage}.`,
},
};
}
if (verificationStatus === NOT_SIGNED) {
if (hasProtonSender(message) && message.Time < SIGNATURE_START.BULK) {
// Don't show a warning on official emails
return {
...result,
text: messageEncryptionDetails,
fill: PLAIN,
};
}
return warningResult;
}
if (!signingPublicKey) {
return {
...warningResult,
senderVerificationDetails: {
description: c('loc_nightly: Sender verification error').t`Unable to retrieve sender key.`,
},
};
}
if (hasPinnedKeys && !signingPublicKeyIsPinned) {
return {
...warningResult,
senderVerificationDetails: {
description: c('loc_nightly: Sender verification error')
.t`Signing key is not in the list of trusted keys.`,
},
};
}
if (!hasPinnedKeys && ktVerificationStatus === KT_VERIFICATION_STATUS.UNVERIFIED_KEYS) {
return {
...warningResult,
senderVerificationDetails: {
description: c('loc_nightly: Sender verification error')
.t`Signing key not protected by Key Transparency.`,
showKeyTransparencyLearnMore: true,
},
};
}
if (signingPublicKeyIsCompromised) {
return {
...warningResult,
senderVerificationDetails: {
description: c('loc_nightly: Sender verification error')
.t`Signing key marked as compromised by sender.`,
},
};
}
if (verificationStatus === SIGNED_AND_INVALID) {
return {
...warningResult,
senderVerificationDetails: {
description: c('loc_nightly: Sender verification error').t`Message signature is invalid`,
},
};
}
if (hasPinnedKeys && !pinnedKeysVerified) {
return {
...warningResult,
senderVerificationDetails: {
description: c('loc_nightly: Signature verification warning').t`Sender's keys must be trusted again.`,
},
};
}
if (verificationStatus === SIGNED_AND_VALID) {
if (hasPinnedKeys) {
return {
...result,
text: c('loc_nightly: Received email icon').t`End-to-end encrypted message from verified sender.`,
fill: CHECKMARK,
senderVerificationDetails: {
description: c('loc_nightly: Signature verification success')
.t`Sender verified with a trusted key.`,
},
};
}
if (
ktVerificationStatus === KT_VERIFICATION_STATUS.VERIFIED_KEYS &&
!ktVerificationResult?.keysChangedRecently
) {
return {
...result,
text: messageEncryptionDetails,
fill: PLAIN,
senderVerificationDetails: {
description: c('loc_nightly: Signature verification success')
.t`Sender verified with Key Transparency.`,
showKeyTransparencyLearnMore: true,
},
};
}
}
return {
...result,
text: messageEncryptionDetails,
fill: PLAIN,
};
};
export const getReceivedStatusIcon = (
message: MessageWithOptionalBody | undefined,
verification: MessageVerification | undefined,
ktActivation: KeyTransparencyActivation
): StatusIcon | undefined => {
if (!message?.ParsedHeaders || verification?.verificationStatus === undefined) {
return;
}
const origin = message.ParsedHeaders['X-Pm-Origin'];
const encryption = message.ParsedHeaders['X-Pm-Content-Encryption'];
const { verificationStatus, pinnedKeysVerified, senderPinnedKeys } = verification;
const hasPinnedKeys = !!senderPinnedKeys?.length;
if (origin === INTERNAL) {
if (ktActivation === KeyTransparencyActivation.SHOW_UI) {
return getReceivedStatusIconInternalWithKT(message, verification, encryption === END_TO_END);
}
const result = { colorClassName: 'color-info', isEncrypted: true };
if (encryption === END_TO_END) {
const verificationErrorsMessage = verification.verificationErrors
?.map(({ message }) => message)
.filter(Boolean)
.join('; ');
const warningsText = (() => {
const expectSigned = inSigningPeriod(message) || hasPinnedKeys;
if (verificationStatus === NOT_SIGNED && expectSigned) {
return c('Signature verification warning').t`Sender could not be verified: Message not signed`;
}
if (verificationErrorsMessage) {
return c('Signature verification warning')
.t`Sender verification failed: ${verificationErrorsMessage}`;
}
return undefined;
})();
if (warningsText) {
return { ...result, fill: WARNING, text: warningsText };
}
if (verificationStatus === NOT_SIGNED) {
return {
...result,
fill: PLAIN,
text: c('Received email icon').t`End-to-end encrypted message`,
};
}
if (verificationStatus === NOT_VERIFIED) {
return {
...result,
fill: PLAIN,
text: c('Received email icon').t`End-to-end encrypted and signed message`,
};
}
if (verificationStatus === SIGNED_AND_INVALID) {
return {
...result,
fill: WARNING,
text: c('Signature verification warning').t`Sender verification failed`,
};
}
if (verificationStatus === SIGNED_AND_VALID) {
if (hasPinnedKeys && !pinnedKeysVerified) {
return {
...result,
fill: WARNING,
text: c('Signature verification warning').t`Sender's trusted keys verification failed`,
};
}
return {
...result,
fill: CHECKMARK,
text: c('Received email icon').t`End-to-end encrypted message from verified sender`,
};
}
return { ...result, fill: PLAIN, text: c('Received email icon').t`End-to-end encrypted message` };
}
if (encryption === ON_DELIVERY) {
return {
...result,
fill: PLAIN,
text: c('Received email icon').t`Sent by ${MAIL_APP_NAME} with zero-access encryption`,
};
}
}
if (origin === EXTERNAL) {
if (encryption === END_TO_END) {
const result = { colorClassName: 'color-success', isEncrypted: true };
const verificationErrorsMessage = verification.verificationErrors
?.map(({ message }) => message)
.filter(Boolean)
.join('; ');
const warningsText = verificationErrorsMessage
? c('Signature verification warning')
.t`PGP-encrypted message. Sender verification failed: ${verificationErrorsMessage}`
: undefined;
if (warningsText) {
return { ...result, fill: WARNING, text: warningsText };
}
if (verificationStatus === NOT_SIGNED) {
return {
...result,
fill: PLAIN,
text: c('Received email icon').t`PGP-encrypted message`,
};
}
if (verificationStatus === NOT_VERIFIED) {
return {
...result,
fill: SIGN,
text: c('Received email icon').t`PGP-encrypted and signed message`,
};
}
if (verificationStatus === SIGNED_AND_INVALID) {
return {
...result,
fill: WARNING,
text: c('Signature verification warning').t`Sender verification failed`,
};
}
if (verificationStatus === SIGNED_AND_VALID) {
if (hasPinnedKeys && !pinnedKeysVerified) {
return {
...result,
fill: WARNING,
text: c('Signature verification warning').t`Sender's trusted keys verification failed`,
};
}
return {
...result,
fill: CHECKMARK,
text: c('Received email icon').t`PGP-encrypted message from verified sender`,
};
}
return { ...result, fill: PLAIN, text: c('Received email icon').t`PGP-encrypted message` };
}
if (encryption === ON_DELIVERY) {
if (verificationStatus === NOT_SIGNED) {
return {
colorClassName: 'color-norm',
isEncrypted: false,
fill: PLAIN,
text: c('Received email icon').t`Stored with zero-access encryption`,
};
}
const result = { colorClassName: 'color-success', isEncrypted: false };
const verificationErrorsMessage = verification.verificationErrors
?.map(({ message }) => message)
.filter(Boolean)
.join('; ');
const warningsText = verificationErrorsMessage
? c('Signature verification warning')
.t`PGP-signed message. Sender verification failed: ${verificationErrorsMessage}`
: undefined;
if (warningsText) {
return { ...result, fill: WARNING, text: warningsText };
}
if (verificationStatus === NOT_VERIFIED) {
return {
...result,
fill: SIGN,
text: c('Received email icon').t`PGP-signed message`,
};
}
if (verificationStatus === SIGNED_AND_VALID) {
if (hasPinnedKeys && !pinnedKeysVerified) {
return {
...result,
fill: WARNING,
text: c('Signature verification warning').t`Sender's trusted keys verification failed`,
};
}
return {
...result,
fill: CHECKMARK,
text: c('Received email icon').t`PGP-signed message from verified sender`,
};
}
if (verificationStatus === SIGNED_AND_INVALID) {
return {
...result,
fill: WARNING,
text: c('Received email icon').t`PGP-signed message. Sender verification failed`,
};
}
}
}
return {
colorClassName: 'color-norm',
isEncrypted: false,
fill: PLAIN,
text: c('Received email icon').t`Stored with zero-access encryption`,
};
};
export const getStatusIconName = ({ isEncrypted, fill }: Pick<Partial<StatusIcon>, 'isEncrypted' | 'fill'>) => {
if (fill === PLAIN) {
return 'lock-filled';
}
if (fill === CHECKMARK) {
return isEncrypted ? 'lock-check-filled' : 'lock-open-check-filled';
}
if (fill === SIGN) {
return isEncrypted ? 'lock-pen-filled' : 'lock-open-pen-filled';
}
if (fill === WARNING) {
return isEncrypted ? 'lock-exclamation-filled' : 'lock-open-exclamation-filled';
}
if (fill === FAIL) {
return 'exclamation-circle';
}
return '';
};
export const getSendIconHref = ({ isEncrypted, fill }: Pick<Partial<StatusIcon>, 'isEncrypted' | 'fill'>) => {
if (fill === CHECKMARK || fill === WARNING) {
return getKnowledgeBaseUrl('/digital-signature');
}
if (isEncrypted) {
return undefined;
}
return getKnowledgeBaseUrl('/proton-mail-encryption-explained');
};
| 3,865
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageAttachPublicKey.ts
|
import { CryptoProxy } from '@proton/crypto';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { MessageState, MessageStateWithData, PublicPrivateKey } from '../../logic/messages/messagesTypes';
import { upload } from '../attachment/attachmentUploader';
interface KeyInfoForFile {
fingerprint: string;
publicKeyArmored: string;
}
const ENCRYPTION_SIZE_SLACK = 0.2;
/**
* Checks if the given blob equals the attachment that is already uploaded.
* Size matching is done with some slack to take into account the difference between plaintext and encryption.
*
* The size can differ because the attachment is already encrypted
*/
const blobEqualsAttachment = (file: File, attachment: Attachment) =>
attachment.Name === (file.name as string) &&
attachment.MIMEType === file.type &&
file.size > (1 - ENCRYPTION_SIZE_SLACK) * (attachment.Size || 0) &&
file.size < (1 + ENCRYPTION_SIZE_SLACK) * (attachment.Size || 0);
/**
* Generate a blob corresponding to the public key that is passed in. The name is extracted from the message the
* key will be attached to.
*/
const fileFromKeyInfo = (message: MessageState, { publicKeyArmored, fingerprint }: KeyInfoForFile) => {
const name = `publickey - ${message.data?.Sender?.Address} - 0x${fingerprint.slice(0, 8).toUpperCase()}.asc`;
return new File([publicKeyArmored], name, { type: 'application/pgp-keys' });
};
/**
* Attaches the senders public key to the message
*/
export const attachPublicKey = async (message: MessageStateWithData, messageKeys: PublicPrivateKey, uid: string) => {
const attachments = message.data?.Attachments || [];
const privateKey = messageKeys.privateKeys?.[0];
const info = {
fingerprint: privateKey.getFingerprint(),
publicKeyArmored: await CryptoProxy.exportPublicKey({ key: privateKey }),
};
const file = fileFromKeyInfo(message, info);
const attachmentExists = attachments.some((attachment) => blobEqualsAttachment(file, attachment));
if (attachmentExists) {
return undefined;
}
const [uploadInfo] = upload([file], message, messageKeys, ATTACHMENT_DISPOSITION.ATTACHMENT, uid);
const uploadResult = await uploadInfo.resultPromise;
return uploadResult.attachment;
};
| 3,866
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageBlockquote.test.ts
|
import mails from './__fixtures__/messageBlockquote.fixtures';
import { locateBlockquote } from './messageBlockquote';
/**
* Creating a whole document each time is needed because locate blockquote is using xpath request
* which will fail if the content is not actually in the document
*/
const createDocument = (content: string) => {
const newDocument = document.implementation.createHTMLDocument();
newDocument.body.innerHTML = content;
return newDocument.body;
};
describe('messageBlockquote', () => {
Object.entries(mails as { [name: string]: string }).forEach(([name, content]) => {
it(`should find the blockquote in the mail ${name}`, () => {
const [, blockquote] = locateBlockquote(createDocument(content));
expect(blockquote.length).not.toBe(0);
});
});
it(`should correctly detect proton blockquote with default font and no signature`, () => {
const content = `
<div style="font-family: verdana; font-size: 20px;">
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty" style="font-family: verdana; font-size: 20px;">
<div class="protonmail_signature_block-user protonmail_signature_block-empty"></div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty"></div>
</div>
<div style="font-family: verdana; font-size: 20px;"><br></div>
<div class="protonmail_quote">
On Tuesday, January 4th, 2022 at 17:13, Swiip - Test account <swiip.test@protonmail.com> wrote:<br>
<blockquote class="protonmail_quote" type="cite">
<div style="font-family: verdana; font-size: 20px;">
<div style="font-family: verdana; font-size: 20px;">test</div>
<div class="protonmail_signature_block protonmail_signature_block-empty" style="font-family: verdana; font-size: 20px;">
<div class="protonmail_signature_block-user protonmail_signature_block-empty"></div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty"></div>
</div>
</div>
</blockquote><br>
</div>
</div>`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).not.toContain('On Tuesday');
expect(after).toContain('On Tuesday');
});
it(`should take the last element containing text in case of siblings blockquotes`, () => {
const content = `
Email content
<div class="protonmail_quote">
blockquote1
</div>
<div class="protonmail_quote">
blockquote2
</div>`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).toContain('Email content');
expect(before).toContain('blockquote1');
expect(before).not.toContain('blockquote2');
expect(after).toContain('blockquote2');
expect(after).not.toContain('blockquote1');
});
it(`should take the last element containing an image in case of siblings blockquotes`, () => {
const content = `
Email content
<div class="protonmail_quote">
blockquote1
</div>
<div class="protonmail_quote">
<span class="proton-image-anchor" />
</div>`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).toContain('Email content');
expect(before).toContain('blockquote1');
expect(before).not.toContain('proton-image-anchor');
expect(after).toContain('proton-image-anchor');
expect(after).not.toContain('blockquote1');
});
it(`should display nothing in blockquote when there is text after blockquotes`, () => {
const content = `
Email content
<div class="protonmail_quote">
blockquote1
</div>
text after blockquote`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).toContain('Email content');
expect(before).toContain('blockquote1');
expect(before).toContain('text after blockquote');
expect(after).toEqual('');
});
it(`should display nothing in blockquote when there is an image after blockquotes`, () => {
const content = `
Email content
<div class="protonmail_quote">
blockquote1
</div>
<span class="proton-image-anchor" />`;
const [before, after] = locateBlockquote(createDocument(content));
expect(before).toContain('Email content');
expect(before).toContain('blockquote1');
expect(before).toContain('proton-image-anchor');
expect(after).toEqual('');
});
});
| 3,867
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageBlockquote.ts
|
import { parseStringToDOM } from '@proton/shared/lib/helpers/dom';
import { ORIGINAL_MESSAGE } from '@proton/shared/lib/mail/messages';
export const BLOCKQUOTE_SELECTORS = [
'.protonmail_quote', // Proton Mail
// Gmail creates both div.gmail_quote and blockquote.gmail_quote. The div
// version marks text but does not cause indentation, but both should be
// considered quoted text.
'.gmail_quote', // Gmail
'div.gmail_extra', // Gmail
'div.yahoo_quoted', // Yahoo Mail
'blockquote.iosymail', // Yahoo iOS Mail
'.tutanota_quote', // Tutanota Mail
'.zmail_extra', // Zoho
'.skiff_quote', // Skiff Mail
'blockquote[data-skiff-mail]', // Skiff Mail
'#divRplyFwdMsg', // Outlook Mail
'div[id="mail-editor-reference-message-container"]', // Outlook
'div[id="3D\\"divRplyFwdMsg\\""]', // Office365
'hr[id=replySplit]',
'.moz-cite-prefix',
'div[id=isForwardContent]',
'blockquote[id=isReplyContent]',
'div[id=mailcontent]',
'div[id=origbody]',
'div[id=reply139content]',
'blockquote[id=oriMsgHtmlSeperator]',
'blockquote[type="cite"]',
'[name="quote"]', // gmx
];
const BLOCKQUOTE_TEXT_SELECTORS = [ORIGINAL_MESSAGE];
const BLOCKQUOTE_SELECTOR = BLOCKQUOTE_SELECTORS.map((selector) => `${selector}:not(:empty)`).join(',');
// When we try to determine what part of the body is the blockquote,
// We want to check that there is no text or no "important" element after the element we're testing
const ELEMENTS_AFTER_BLOCKQUOTES = [
'.proton-image-anchor', // At this point we already replaced images with an anchor, but we want to keep them
];
/**
* Returns content before and after match in the source
* Beware, String.prototype.split does almost the same but will not if there is several match
*/
export const split = (source: string, match: string): [string, string] => {
const index = source.indexOf(match);
if (index === -1) {
return [source, ''];
}
return [source.slice(0, index), source.slice(index + match.length)];
};
const searchForContent = (element: Element, text: string) => {
const xpathResult = element.ownerDocument?.evaluate(
`//*[text()='${text}']`,
element,
null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE,
null
);
const result: Element[] = [];
let match = null;
// eslint-disable-next-line no-cond-assign
while ((match = xpathResult?.iterateNext())) {
result.push(match as Element);
}
return result;
};
/**
* Try to locate the eventual blockquote present in the document no matter the expeditor of the mail
* Return the HTML content splitted at the blockquote start
*/
export const locateBlockquote = (inputDocument: Element | undefined): [content: string, blockquote: string] => {
if (!inputDocument) {
return ['', ''];
}
const body = inputDocument.querySelector('body');
const tmpDocument = body || inputDocument;
const parentHTML = tmpDocument.innerHTML || '';
let result: [string, string] | null = null;
const testBlockquote = (blockquote: Element) => {
const blockquoteHTML = blockquote.outerHTML || '';
const [beforeHTML = '', afterHTML = ''] = split(parentHTML, blockquoteHTML);
const after = parseStringToDOM(afterHTML);
// The "real" blockquote will be determined based on the fact:
// - That there is no text after the current blockquote element
// - That there is no "important" element after the current blockquote element
const hasImageAfter = after.body.querySelector(ELEMENTS_AFTER_BLOCKQUOTES.join(','));
const hasTextAfter = after.body?.textContent?.trim().length;
if (!hasImageAfter && !hasTextAfter) {
return [beforeHTML, blockquoteHTML] as [string, string];
}
return null;
};
// Standard search with a composed query selector
const blockquotes = [...tmpDocument.querySelectorAll(BLOCKQUOTE_SELECTOR)];
blockquotes.forEach((blockquote) => {
if (result === null) {
result = testBlockquote(blockquote);
}
});
// Second search based on text content with xpath
if (result === null) {
BLOCKQUOTE_TEXT_SELECTORS.forEach((text) => {
if (result === null) {
searchForContent(tmpDocument, text).forEach((blockquote) => {
if (result === null) {
result = testBlockquote(blockquote);
}
});
}
});
// document.ownerDocument?.evaluate;
}
return result || [parentHTML, ''];
};
| 3,868
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageContent.test.ts
|
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Address, MailSettings, UserSettings } from '@proton/shared/lib/interfaces';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { PM_SIGNATURE } from '@proton/shared/lib/mail/mailSettings';
import { data, fromFields, recipients } from '../../components/composer/quickReply/tests/QuickReply.test.data';
import { addressID, messageID, subject } from '../../components/message/tests/Message.test.helpers';
import { MESSAGE_ACTIONS } from '../../constants';
import { MessageDecryption, MessageState } from '../../logic/messages/messagesTypes';
import { generateKeys, releaseCryptoProxy, setupCryptoProxyForTesting } from '../test/crypto';
import { clearAll, removeLineBreaks } from '../test/helper';
import { createDocument } from '../test/message';
import { getContentWithBlockquotes, getContentWithoutBlockquotes } from './messageContent';
import { generateBlockquote } from './messageDraft';
const getMessage = (isPlainText: boolean, isReferenceMessage: boolean, content: string) => {
return {
localID: isReferenceMessage ? messageID : 'messageToCleanID',
data: {
ID: isReferenceMessage ? messageID : 'messageToCleanID',
AddressID: addressID,
Subject: subject,
Sender: isReferenceMessage ? recipients.fromRecipient : recipients.meRecipient,
ReplyTos: isReferenceMessage ? [recipients.fromRecipient] : [recipients.meRecipient],
ToList: isReferenceMessage ? [recipients.meRecipient] : [recipients.fromRecipient],
MIMEType: isPlainText ? MIME_TYPES.PLAINTEXT : MIME_TYPES.DEFAULT,
Attachments: [] as Attachment[],
Time: Date.now() / 1000,
} as Message,
decryption: {
decryptedBody: content,
} as MessageDecryption,
messageDocument: {
initialized: true,
plainText: isPlainText ? content : undefined,
document: isPlainText ? undefined : createDocument(content),
},
} as MessageState;
};
const getFakeNow = new Date(2021, 0, 1, 0, 0, 0);
describe('messageContent', () => {
const mailSettings = {
PMSignature: PM_SIGNATURE.ENABLED,
} as MailSettings;
const userSettings = {} as UserSettings;
let addresses: Address[] = [];
const plaintextReferenceMessageBody = 'Hello this is the reference message';
const plaintextReplyContent = 'Hello this is the reply';
const plainTextContent = `${plaintextReplyContent} ${data.protonSignature}
On Friday, January 1st, 2021 at 12:00 AM, ${fromFields.fromName} <${fromFields.fromAddress}> wrote:
> ${plaintextReferenceMessageBody}`;
const htmlReferenceMessageBody = '<div>Hello this is the reference message</div>';
const htmlReplyContent = '<div>Hello this is the reply<div>';
const htmlTextContent = `${htmlReplyContent} ${data.protonSignature}
<div class=\"protonmail_quote\">
On Friday, January 1st, 2021 at 12:00 AM, ${fromFields.fromName} <${fromFields.fromAddress}> wrote:<br><br>
<blockquote class=\"protonmail_quote\" type=\"cite\">
<div>Hello this is the reference message</div>
</blockquote><br>
</div>`;
describe('getContentWithoutBlockquotes', function () {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(async () => {
jest.useFakeTimers().setSystemTime(getFakeNow.getTime());
const toKeys = await generateKeys('user', fromFields.meAddress);
addresses = [
{
Email: fromFields.meAddress,
HasKeys: 1,
ID: addressID,
Receive: 1,
Status: 1,
Send: 1,
Keys: [
{
Primary: 1,
PrivateKey: toKeys.privateKeyArmored,
PublicKey: toKeys.publicKeyArmored,
},
],
} as Address,
] as Address[];
});
afterEach(() => {
clearAll();
jest.useRealTimers();
});
it('should remove blockquotes from plaintext message', async () => {
const referenceMessage = getMessage(true, true, plaintextReferenceMessageBody);
const messageToClean = getMessage(true, false, plainTextContent);
const contentWithoutBlockquotes = getContentWithoutBlockquotes(
messageToClean,
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
const expectedContent = `${plaintextReplyContent} ${data.protonSignature}`;
// Only the content + the protonSignature should remain
expect((contentWithoutBlockquotes || '').trim()).toEqual(expectedContent);
});
it('should remove blockquotes from HTML message', async () => {
const referenceMessage = getMessage(false, true, htmlReferenceMessageBody);
const messageToCleanBlockquotes = generateBlockquote(
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
const messageToCleanBody = `${htmlReplyContent} ${data.protonSignature} ${messageToCleanBlockquotes}`;
const messageToClean = getMessage(false, false, messageToCleanBody);
const contentWithoutBlockquotes = getContentWithoutBlockquotes(
messageToClean,
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
const expectedContent = `${htmlReplyContent} ${data.protonSignature}`;
// Only the content + the protonSignature should remain
expect((contentWithoutBlockquotes || '').trim()).toEqual(expectedContent);
});
});
describe('getContentWithBlockquotes', function () {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(async () => {
jest.useFakeTimers().setSystemTime(getFakeNow.getTime());
});
afterEach(() => {
clearAll();
jest.useRealTimers();
});
it('should generate content with blockquote string for a plaintext message', async () => {
const referenceMessage = getMessage(true, true, plaintextReferenceMessageBody);
const replyContent = `${plaintextReplyContent} ${data.protonSignature}`;
const contentWithBlockquotes = getContentWithBlockquotes(
replyContent,
true,
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
expect(removeLineBreaks(contentWithBlockquotes)).toEqual(removeLineBreaks(plainTextContent));
});
it('should generate content with blockquote string for an HTML message', async () => {
const referenceMessage = getMessage(false, true, htmlReferenceMessageBody);
const replyContent = `${htmlReplyContent} ${data.protonSignature}`;
const contentWithBlockquotes = getContentWithBlockquotes(
replyContent,
false,
referenceMessage,
mailSettings,
userSettings,
addresses,
MESSAGE_ACTIONS.NEW
);
expect(removeLineBreaks(contentWithBlockquotes)).toEqual(removeLineBreaks(htmlTextContent));
});
});
});
| 3,869
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageContent.ts
|
import { checkContrast } from '@proton/shared/lib/helpers/dom';
import { Address, MailSettings, UserSettings } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { isPlainText as testIsPlainText } from '@proton/shared/lib/mail/messages';
import { MESSAGE_IFRAME_ROOT_ID } from '../../components/message/constants';
import { MESSAGE_ACTIONS } from '../../constants';
import { MessageState, PartialMessageState } from '../../logic/messages/messagesTypes';
import { parseInDiv } from '../dom';
import { findSender } from '../message/messageRecipients';
import { toText } from '../parserHtml';
import { textToHtml } from '../textToHtml';
import { locateBlockquote } from './messageBlockquote';
import { generateBlockquote } from './messageDraft';
export const getPlainTextContent = (message: PartialMessageState) => {
return message.messageDocument?.plainText || '';
};
export const getDocumentContent = (document: Element | undefined) => {
const root = document?.querySelector('body') || document;
return root?.innerHTML || '';
};
/**
* Get current processed message document html content
*/
export const getContent = (message: PartialMessageState) => {
if (testIsPlainText(message.data)) {
return getPlainTextContent(message);
}
return getDocumentContent(message.messageDocument?.document);
};
export const setPlainTextContent = (message: MessageState, content: string) => {
if (message.messageDocument) {
message.messageDocument.plainText = content;
} else {
message.messageDocument = { plainText: content };
}
};
export const setDocumentContent = (document: Element | undefined, content: string) => {
if (document) {
document.innerHTML = content;
} else {
document = parseInDiv(content);
}
return document;
};
/**
* Set current processed message document html
*/
export const setContent = (message: MessageState, content: string) => {
if (testIsPlainText(message.data)) {
setPlainTextContent(message, content);
} else {
const document = setDocumentContent(message.messageDocument?.document, content);
if (message.messageDocument) {
message.messageDocument.document = document;
} else {
message.messageDocument = { document };
}
}
};
export const exportPlainText = (content: string) => {
/*
* The replace removes any characters that are produced by the copying process (like zero width characters)
* See: http://www.berklix.org/help/majordomo/#quoted we want to avoid sending unnecessary quoted printable encodings
*/
return toText(content, true).replace(/\u200B/g, '');
};
/**
* Generates/Gets the plaintext body from the message. If the message is not composed in plaintext, it will downconvert
* the html body to plaintext if downconvert is set. If downconvert is disabled it will return false.
*/
export const getPlainText = (message: MessageState, downconvert: boolean) => {
if (testIsPlainText(message.data)) {
return getPlainTextContent(message);
}
if (!downconvert) {
return undefined;
}
return exportPlainText(getContent(message));
};
/**
* Convert the body of a message in plain text to an HTML version
*/
export const plainTextToHTML = (
message: Partial<Message> | undefined,
plainTextContent: string | undefined,
mailSettings: MailSettings | undefined,
userSettings: UserSettings | undefined,
addresses: Address[]
) => {
const sender = findSender(addresses, message);
return textToHtml(plainTextContent, sender?.Signature || '', mailSettings, userSettings);
};
export const querySelectorAll = (message: Partial<MessageState> | undefined, selector: string) => [
...((message?.messageDocument?.document?.querySelectorAll(selector) || []) as HTMLElement[]),
];
export const canSupportDarkStyle = (iframe: HTMLIFrameElement | null) => {
const container = iframe?.contentDocument?.getElementById(MESSAGE_IFRAME_ROOT_ID);
const window = iframe?.contentWindow;
if (!container || !window) {
return false;
}
const colorSchemeMetaTag = container.querySelector('meta[name="color-scheme"]');
// If the meta tag color-scheme is present, we assume that the email supports dark mode
if (colorSchemeMetaTag?.getAttribute('content')?.includes('dark')) {
return true;
}
const supportedColorSchemesMetaTag = container.querySelector('meta[name="supported-color-schemes"]');
// If the meta tag supported-color-schemes is present, we assume that the email supports dark mode
if (supportedColorSchemesMetaTag?.getAttribute('content')?.includes('dark')) {
return true;
}
const styleTag = container.querySelector('style');
const styleTextContent = styleTag?.textContent;
// If the media query prefers-color-scheme is present, we assume that the email supports dark mode
if (styleTextContent?.includes('color-scheme') || styleTextContent?.includes('prefers-color-scheme')) {
return true;
}
const contrastResult = checkContrast(container, window);
return contrastResult;
};
export const getContentWithoutBlockquotes = (
message: MessageState,
referenceMessage: MessageState,
mailSettings: MailSettings,
userSettings: UserSettings,
addresses: Address[],
action: MESSAGE_ACTIONS
) => {
if (testIsPlainText(message.data)) {
const blockquotes = generateBlockquote(referenceMessage || {}, mailSettings, userSettings, addresses, action);
const plainBlockquotes = toText(blockquotes);
return message.messageDocument?.plainText?.replace(plainBlockquotes, '');
}
const [contentBeforeBlockquotes] = locateBlockquote(message.messageDocument?.document);
return contentBeforeBlockquotes;
};
export const getContentWithBlockquotes = (
content: string,
isPlainText: boolean,
referenceMessage: MessageState,
mailSettings: MailSettings,
userSettings: UserSettings,
addresses: Address[],
action: MESSAGE_ACTIONS
) => {
const blockquotes = generateBlockquote(referenceMessage || {}, mailSettings, userSettings, addresses, action);
if (isPlainText) {
const plainBlockquotes = toText(blockquotes);
return `${content}${plainBlockquotes}`;
} else {
return `${content}${blockquotes.toString()}`;
}
};
| 3,870
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageDataUrl.ts
|
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { generateProtonWebUID } from '@proton/shared/lib/helpers/uid';
import { MessageState } from '../../logic/messages/messagesTypes';
import { generateCid, setEmbeddedAttr } from './messageEmbeddeds';
// Reference Angular/src/app/composer/services/extractDataURI.js
/**
* Convert data-uri to blob
*/
const dataUrlToFile = (fileName: string, dataUrl: string) => {
const [mime = '', byte = ''] = dataUrl.split(',');
// separate out the mime component
const mimeString = mime.split(':')[1].split(';')[0];
try {
// write the bytes of the string to an ArrayBuffer
const data = base64StringToUint8Array(decodeURIComponent(byte));
// write the ArrayBuffer to a blob, and you're done
return new File([data], fileName, { type: mimeString });
} catch {
// Leave the image inline as-is, if the image fails to be parsed
return new File([byte], fileName, { type: mimeString });
}
};
/**
* Transform every data-uri in the message content to embedded attachment
*/
export const replaceDataUrl = (message: MessageState) => {
if (!message.messageDocument?.document) {
return [];
}
return [...message.messageDocument?.document.querySelectorAll('img')]
.map((image) => ({ image, src: image.src || '' }))
.filter(({ src }) => /data:image/.test(src)) // only data:uri image
.filter(({ src }) => src.includes(',')) // remove invalid data:uri
.map(({ image, src }) => {
const cid = generateCid(generateProtonWebUID(), message.data?.Sender?.Address || '');
const fileName = image.alt || `image${Date.now()}`;
const file = dataUrlToFile(fileName, src);
setEmbeddedAttr(cid, '', image);
image.removeAttribute('src');
return { cid, file };
});
};
| 3,871
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageDecrypt.ts
|
import { c } from 'ttag';
import {
CryptoProxy,
WorkerProcessMIMEResult as MimeProcessResult,
PrivateKeyReference,
PublicKeyReference,
WorkerDecryptionResult,
} from '@proton/crypto';
import { stringToUtf8Array, utf8ArrayToString } from '@proton/crypto/lib/utils';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { Address } from '@proton/shared/lib/interfaces';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import {
getDate,
getParsedHeadersFirstValue,
getSender,
isAutoForwardee,
isMIME,
} from '@proton/shared/lib/mail/messages';
import { MessageErrors } from '../../logic/messages/messagesTypes';
import { convert } from '../attachment/attachmentConverter';
const { NOT_VERIFIED, NOT_SIGNED } = VERIFICATION_STATUS;
// decrypted data is always a string for legacy message, regardless of 'format' input option
interface MaybeLegacyDecryptResult extends WorkerDecryptionResult<string | Uint8Array> {}
const binaryToString = (data: Uint8Array) =>
utf8ArrayToString(data)
.replace(/\r\n/g, '\n')
// nbsp can be contained in message body and "crash" DOMPurify
.replace(/\u00A0/g, ' ');
export interface DecryptMessageResult {
decryptedBody: string;
decryptedRawContent: Uint8Array;
attachments?: Attachment[];
decryptedSubject?: string;
signature?: Uint8Array;
errors?: MessageErrors;
mimetype?: MIME_TYPES;
}
const decryptMimeMessage = async (
message: Message,
privateKeys: PrivateKeyReference[],
getAttachment?: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined,
onUpdateAttachment?: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void,
password?: string
): Promise<DecryptMessageResult> => {
const headerFilename = c('Encrypted Headers').t`Encrypted Headers filename`;
const sender = getSender(message)?.Address;
let decryption: MaybeLegacyDecryptResult;
let processing: MimeProcessResult;
try {
if (!password) {
decryption = await CryptoProxy.decryptMessageLegacy({
armoredMessage: message.Body,
messageDate: getDate(message),
decryptionKeys: privateKeys,
verificationKeys: [],
format: 'binary',
});
} else {
decryption = await CryptoProxy.decryptMessageLegacy({
armoredMessage: message.Body,
messageDate: getDate(message),
passwords: [...password],
format: 'binary',
});
}
const decryptedStringData =
decryption.data instanceof Uint8Array ? binaryToString(decryption.data) : decryption.data;
try {
processing = await CryptoProxy.processMIME({
data: decryptedStringData,
headerFilename,
sender,
});
} catch (e) {
console.log('Failed to process decrypted MIME message:', decryptedStringData);
throw e;
}
const decryptedRawContent =
decryption.data instanceof Uint8Array ? decryption.data : stringToUtf8Array(decryption.data);
return {
decryptedBody: processing.body,
decryptedRawContent,
attachments: !onUpdateAttachment
? undefined
: convert(message, processing.attachments, 0, onUpdateAttachment),
decryptedSubject: processing.encryptedSubject,
signature: decryption.signatures[0],
mimetype: processing.mimeType as MIME_TYPES,
};
} catch (error: any) {
return {
decryptedBody: '',
decryptedRawContent: new Uint8Array(),
attachments: [],
errors: {
decryption: [error],
},
};
}
};
const decryptLegacyMessage = async (
message: Message,
privateKeys: PrivateKeyReference[],
password?: string
): Promise<DecryptMessageResult> => {
let result: MaybeLegacyDecryptResult;
try {
if (!password) {
result = await CryptoProxy.decryptMessageLegacy({
armoredMessage: message.Body,
messageDate: getDate(message),
decryptionKeys: privateKeys,
verificationKeys: [],
format: 'binary',
config: {
allowForwardedMessages: isAutoForwardee(message),
},
});
} else {
result = await CryptoProxy.decryptMessageLegacy({
armoredMessage: message.Body,
messageDate: getDate(message),
passwords: [password],
format: 'binary',
});
}
const {
data,
signatures: [signature],
} = result;
// Very old messages outputs as string
const decryptedBody = data instanceof Uint8Array ? binaryToString(data) : data;
const decryptedRawContent = data instanceof Uint8Array ? data : stringToUtf8Array(data);
return { decryptedBody, decryptedRawContent, signature };
} catch (error: any) {
return {
decryptedBody: '',
decryptedRawContent: new Uint8Array(),
errors: {
decryption: [error],
},
};
}
};
/**
* Decrypt a message body of any kind: plaintext/html multipart/simple
* Willingly not dealing with public keys and signature verification
* It will be done separately when public keys will be ready
*/
export const decryptMessage = async (
message: Message,
privateKeys: PrivateKeyReference[],
getAttachment?: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined,
onUpdateAttachment?: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void,
password?: string
): Promise<DecryptMessageResult> => {
if (isMIME(message)) {
return decryptMimeMessage(message, privateKeys, getAttachment, onUpdateAttachment, password);
}
return decryptLegacyMessage(message, privateKeys, password);
};
/**
* Verify the extracted `signature` of a decryption result against its `decryptedRawContent`
* Also parse mime messages to look for embedded signature
* The `publicKeys` are the public keys on which the compare the signature
* The `message` is only used to detect mime format
*/
export const verifyMessage = async (
decryptedRawContent: Uint8Array,
cryptoSignature: Uint8Array | undefined,
message: Message,
publicKeys: PublicKeyReference[]
): Promise<{
verified: VERIFICATION_STATUS;
signature?: Uint8Array;
verificationErrors?: Error[];
}> => {
try {
let cryptoVerified: VERIFICATION_STATUS | undefined;
let mimeSignature: Uint8Array | undefined;
let mimeVerified: VERIFICATION_STATUS | undefined;
const contentType = getParsedHeadersFirstValue(message, 'Content-Type');
if (publicKeys.length && cryptoSignature) {
const cryptoVerify = await CryptoProxy.verifyMessage({
binaryData: decryptedRawContent,
binarySignature: cryptoSignature,
verificationKeys: publicKeys,
});
cryptoVerified = cryptoVerify.verified;
}
if (contentType === MIME_TYPES.MIME) {
const mimeVerify = await CryptoProxy.processMIME({
data: binaryToString(decryptedRawContent),
verificationKeys: publicKeys,
});
[mimeSignature] = mimeVerify.signatures;
mimeVerified = mimeVerify.verified;
}
if (!cryptoSignature && !mimeSignature) {
return { verified: NOT_SIGNED, signature: undefined };
}
if (!publicKeys.length) {
return { verified: NOT_VERIFIED, signature: cryptoSignature };
}
if (cryptoSignature) {
return { verified: cryptoVerified as VERIFICATION_STATUS, signature: cryptoSignature };
}
// mimeSignature can't be undefined at this point
return { verified: mimeVerified as VERIFICATION_STATUS, signature: mimeSignature };
} catch (error: any) {
return {
verified: NOT_VERIFIED,
verificationErrors: [error],
};
}
};
/**
* Try to get the key responsible for the message encryption from user's keys
* keyFound contains the address, the key and keyIds of the key in case we need to display which key is needed to the user
* matchingKey is the keyID of the key that we need to store in localStorage
*/
export const getMessageDecryptionKeyIDFromAddress = async (address: Address, message: Message) => {
const { encryptionKeyIDs } = await CryptoProxy.getMessageInfo({
armoredMessage: message.Body,
});
for (const { PrivateKey: armoredKey } of address.Keys) {
const { keyIDs: addressKeyIDs } = await CryptoProxy.getKeyInfo({ armoredKey });
const matchingKeyID = addressKeyIDs.find((keyID) => encryptionKeyIDs.includes(keyID));
if (matchingKeyID) {
return matchingKeyID;
}
}
};
| 3,872
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageDraft.test.ts
|
import { addPlusAlias } from '@proton/shared/lib/helpers/email';
import { Address, MailSettings, Recipient, UserSettings } from '@proton/shared/lib/interfaces';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { FORWARDED_MESSAGE, FW_PREFIX, RE_PREFIX, formatSubject } from '@proton/shared/lib/mail/messages';
import { MESSAGE_ACTIONS } from '../../constants';
import { MessageState, MessageStateWithData } from '../../logic/messages/messagesTypes';
import { formatFullDate } from '../date';
import {
createNewDraft,
generatePreviousMessageInfos,
getBlockquoteRecipientsString,
handleActions,
} from './messageDraft';
const ID = 'ID';
const Time = 0;
const Subject = 'test';
const addressID = 'addressID';
const recipient1 = { Address: 'test1@proton.me' };
const recipient2 = { Address: 'test2@proton.me' };
const recipient3 = { Address: 'test3@proton.me' };
const recipient4 = { Address: 'test4@proton.me' };
const recipient5 = { Address: 'test5@proton.me' };
const message = {
ID,
Time,
Subject,
ToList: [recipient1],
CCList: [recipient2],
BCCList: [recipient3],
ReplyTos: [recipient4],
};
const allActions = [MESSAGE_ACTIONS.NEW, MESSAGE_ACTIONS.REPLY, MESSAGE_ACTIONS.REPLY_ALL, MESSAGE_ACTIONS.FORWARD];
const notNewActions = [MESSAGE_ACTIONS.REPLY, MESSAGE_ACTIONS.REPLY_ALL, MESSAGE_ACTIONS.FORWARD];
const action = MESSAGE_ACTIONS.NEW;
const mailSettings = {} as MailSettings;
const userSettings = {} as UserSettings;
const address = {
ID: 'addressid',
DisplayName: 'name',
Email: 'email',
Status: 1,
Receive: 1,
Send: 1,
Signature: 'signature',
} as Address;
const addresses: Address[] = [address];
describe('messageDraft', () => {
describe('formatSubject', () => {
const listRe = ['Subject', 'Re: Subject', 'Fw: Subject', 'Fw: Re: Subject', 'Re: Fw: Subject'];
const listFw = ['Subject', 'Re: Subject', 'Fw: Subject', 'Fw: Re: Subject', 'Re: Fw: Subject'];
it('should add the RE only if id does not start with it', () => {
const [subject, reply, forward, fwreply, reforward] = listRe;
expect(formatSubject(subject, RE_PREFIX)).toBe(`${RE_PREFIX} ${subject}`);
expect(formatSubject(reply, RE_PREFIX)).toBe(reply);
expect(formatSubject(forward, RE_PREFIX)).toBe(`${RE_PREFIX} ${forward}`);
expect(formatSubject(fwreply, RE_PREFIX)).toBe(`${RE_PREFIX} ${fwreply}`);
expect(formatSubject(reforward, RE_PREFIX)).toBe(reforward);
});
it('should add the Fw only if id does not start with it', () => {
const [subject, reply, forward, fwreply, reforward] = listFw;
expect(formatSubject(subject, FW_PREFIX)).toBe(`${FW_PREFIX} ${subject}`);
expect(formatSubject(reply, FW_PREFIX)).toBe(`${FW_PREFIX} ${reply}`);
expect(formatSubject(forward, FW_PREFIX)).toBe(forward);
expect(formatSubject(fwreply, FW_PREFIX)).toBe(fwreply);
expect(formatSubject(reforward, FW_PREFIX)).toBe(`${FW_PREFIX} ${reforward}`);
});
});
describe('handleActions', () => {
it('should return empty values on copy empty input', () => {
const result = handleActions(MESSAGE_ACTIONS.NEW);
expect(result.data?.Subject).toEqual('');
expect(result.data?.ToList).toEqual([]);
expect(result.data?.CCList).toEqual([]);
expect(result.data?.BCCList).toEqual([]);
});
it('should copy values', () => {
const result = handleActions(MESSAGE_ACTIONS.NEW, {
data: {
Subject,
ToList: [recipient1],
CCList: [recipient2],
BCCList: [recipient3],
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(Subject);
expect(result.data?.ToList).toEqual([recipient1]);
expect(result.data?.CCList).toEqual([recipient2]);
expect(result.data?.BCCList).toEqual([recipient3]);
});
it('should prepare a reply for received message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4]);
});
it('should prepare a reply for sent message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_SENT,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient1]);
});
it('should prepare a reply for received and sent message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_SENT | MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient1]);
});
it('should prepare a reply all for received message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY_ALL, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4]);
expect(result.data?.CCList).toEqual([recipient1, recipient2]);
expect(result.data?.BCCList).toEqual(undefined);
});
it('should prepare a reply all for sent message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY_ALL, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_SENT,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient1]);
expect(result.data?.CCList).toEqual([recipient2]);
expect(result.data?.BCCList).toEqual([recipient3]);
});
it('should prepare a reply all for received and sent message', () => {
const result = handleActions(MESSAGE_ACTIONS.REPLY_ALL, {
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_SENT | MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient1]);
expect(result.data?.CCList).toEqual([recipient2]);
expect(result.data?.BCCList).toEqual([recipient3]);
});
it('should keep other user addresses in the CC list on reply all', () => {
// The email is received on recipient1 (addressID) and recipient5 is another userAddress on which we received the email
// When we reply to this message, recipient1 must be removed from CCList, and recipient5 must be present
const message = {
ID,
Time,
Subject,
ToList: [recipient1, recipient5],
CCList: [recipient2],
BCCList: [recipient3],
ReplyTos: [recipient4],
AddressID: addressID,
};
const result = handleActions(
MESSAGE_ACTIONS.REPLY_ALL,
{
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData,
[
{ ID: addressID, Email: recipient1.Address } as Address,
{ ID: 'otherID', Email: recipient5.Address } as Address,
] as Address[]
);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4]);
expect(result.data?.CCList).toEqual([recipient5, recipient2]);
expect(result.data?.BCCList).toEqual(undefined);
});
it('should prepare recipient list correctly on reply all to alias addresses', () => {
const recipient1Alias = { Address: addPlusAlias(recipient1.Address, 'alias') };
const recipient2Alias = { Address: 'test2.2@proton.me' };
const recipient3Alias = { Address: addPlusAlias(recipient3.Address, 'alias') };
const recipient4Alias = { Address: 'test4.4@proton.me' };
const message = {
ID,
Time,
Subject,
ToList: [recipient1Alias],
CCList: [recipient2Alias],
BCCList: [recipient3Alias],
ReplyTos: [recipient4Alias],
AddressID: addressID,
};
const result = handleActions(
MESSAGE_ACTIONS.REPLY_ALL,
{
data: {
...message,
Flags: MESSAGE_FLAGS.FLAG_RECEIVED,
},
} as MessageStateWithData,
[{ ID: addressID, Email: recipient1.Address } as Address] as Address[]
);
expect(result.data?.Subject).toEqual(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4Alias]);
expect(result.data?.CCList).toEqual([recipient2Alias]);
expect(result.data?.BCCList).toEqual(undefined);
});
it('should prepare a forward', () => {
const result = handleActions(MESSAGE_ACTIONS.FORWARD, { data: message } as MessageStateWithData);
expect(result.data?.Subject).toEqual(`${FW_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([]);
expect(result.data?.CCList).toEqual(undefined);
expect(result.data?.BCCList).toEqual(undefined);
});
});
describe('createNewDraft', () => {
it('should use insertSignature', () => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.messageDocument?.document?.innerHTML).toContain(address.Signature);
});
// TODO: Feature to implement
// it('should parse text', () => {
// expect(textToHtmlMail.parse).toHaveBeenCalledTimes(1);
// expect(textToHtmlMail.parse).toHaveBeenCalledWith(MESSAGE_BODY_PLAIN);
// });
// it('should not parse text', () => {
// expect(textToHtmlMail.parse).not.toHaveBeenCalled();
// });
it('should load the sender', () => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.data?.AddressID).toBe(address.ID);
});
it('should add ParentID when not a copy', () => {
notNewActions.forEach((action) => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.draftFlags?.ParentID).toBe(ID);
});
});
it('should set a value to recipient lists', () => {
allActions.forEach((action) => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.data?.ToList?.length).toBeDefined();
expect(result.data?.CCList?.length).toBeDefined();
expect(result.data?.BCCList?.length).toBeDefined();
});
});
// TODO: Feature to be implemented
// it('should set a value to Attachments', () => {
// expect(item.Attachments).toEqual(DEFAULT_MESSAGE_COPY.Attachments);
// });
it('should use values from handleActions', () => {
const result = createNewDraft(
MESSAGE_ACTIONS.REPLY_ALL,
{ data: { ...message, Flags: MESSAGE_FLAGS.FLAG_RECEIVED } } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.data?.Subject).toBe(`${RE_PREFIX} ${Subject}`);
expect(result.data?.ToList).toEqual([recipient4]);
expect(result.data?.CCList).toEqual([recipient1, recipient2]);
expect(result.data?.BCCList).toEqual([]);
});
it('should use values from findSender', () => {
const result = createNewDraft(
action,
{ data: message } as MessageStateWithData,
mailSettings,
userSettings,
addresses,
jest.fn()
);
expect(result.data?.AddressID).toBe(address.ID);
expect(result.data?.Sender?.Address).toBe(address.Email);
expect(result.data?.Sender?.Name).toBe(address.DisplayName);
});
});
describe('getBlockquoteRecipientsString', () => {
it('should return the expected recipient string for blockquotes', () => {
const recipientList = [
{ Name: 'Display Name', Address: 'address@protonmail.com' },
{ Name: '', Address: 'address2@protonmail.com' },
{ Address: 'address3@protonmail.com' },
] as Recipient[];
const expectedString = `Display Name <address@protonmail.com>, address2@protonmail.com <address2@protonmail.com>, address3@protonmail.com <address3@protonmail.com>`;
expect(getBlockquoteRecipientsString(recipientList)).toEqual(expectedString);
});
});
describe('generatePreviousMessageInfos', () => {
const messageSubject = 'Subject';
const meRecipient = { Name: 'me', Address: 'me@protonmail.com' };
const toRecipient = { Name: 'toRecipient', Address: 'toRecipient@protonmail.com' };
const ccRecipient = { Address: 'ccRecipient@protonmail.com' };
const sender = { Name: 'sender', Address: 'sender@protonmail.com' } as Recipient;
const toList = [meRecipient, toRecipient] as Recipient[];
const ccList = [ccRecipient] as Recipient[];
const generateMessage = (hasCCList = true) => {
return {
localID: ID,
data: {
ID,
Subject: messageSubject,
Sender: sender,
ToList: toList,
CCList: hasCCList ? ccList : undefined,
},
} as MessageState;
};
it('should return the correct message blockquotes info for a reply', () => {
const referenceMessage = generateMessage();
const messageBlockquotesInfos = generatePreviousMessageInfos(referenceMessage, MESSAGE_ACTIONS.REPLY);
const expectedString = `On ${formatFullDate(new Date(0))}, ${referenceMessage.data?.Sender
.Name} <${referenceMessage.data?.Sender.Address}> wrote:<br><br>`;
expect(messageBlockquotesInfos).toEqual(expectedString);
});
it('should return the correct message blockquotes info for a forward', () => {
const referenceMessage = generateMessage();
const messageBlockquotesInfos = generatePreviousMessageInfos(referenceMessage, MESSAGE_ACTIONS.FORWARD);
const expectedString = `${FORWARDED_MESSAGE}<br>
From: ${referenceMessage.data?.Sender.Name} <${referenceMessage.data?.Sender.Address}><br>
Date: On ${formatFullDate(new Date(0))}<br>
Subject: ${messageSubject}<br>
To: ${meRecipient.Name} <${meRecipient.Address}>, ${toRecipient.Name} <${toRecipient.Address}><br>
CC: ${ccRecipient.Address} <${ccRecipient.Address}><br><br>`;
expect(messageBlockquotesInfos).toEqual(expectedString);
});
it('should return the correct message blockquotes info for a forward with no CC', () => {
const referenceMessage = generateMessage(false);
const messageBlockquotesInfos = generatePreviousMessageInfos(referenceMessage, MESSAGE_ACTIONS.FORWARD);
const expectedString = `${FORWARDED_MESSAGE}<br>
From: ${referenceMessage.data?.Sender.Name} <${referenceMessage.data?.Sender.Address}><br>
Date: On ${formatFullDate(new Date(0))}<br>
Subject: ${messageSubject}<br>
To: ${meRecipient.Name} <${meRecipient.Address}>, ${toRecipient.Name} <${toRecipient.Address}><br>
<br>`;
expect(messageBlockquotesInfos).toEqual(expectedString);
});
});
});
| 3,873
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageDraft.ts
|
import { c } from 'ttag';
import { generateUID } from '@proton/components';
import { defaultFontStyle } from '@proton/components/components/editor/helpers';
import { WorkerDecryptionResult } from '@proton/crypto';
import { MIME_TYPES } from '@proton/shared/lib/constants';
import { setBit } from '@proton/shared/lib/helpers/bitset';
import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email';
import { Address, MailSettings, UserSettings } from '@proton/shared/lib/interfaces';
import { Recipient } from '@proton/shared/lib/interfaces/Address';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import {
DRAFT_ID_PREFIX,
FORWARDED_MESSAGE,
FW_PREFIX,
RE_PREFIX,
formatSubject,
getOriginalTo,
isPlainText,
isSent,
isSentAndReceived,
} from '@proton/shared/lib/mail/messages';
import unique from '@proton/utils/unique';
import { MESSAGE_ACTIONS } from '../../constants';
import { MessageStateWithData, PartialMessageState } from '../../logic/messages/messagesTypes';
import { getFromAddress } from '../addresses';
import { convertToFile } from '../attachment/attachmentConverter';
import { formatFullDate } from '../date';
import { parseInDiv } from '../dom';
import { getDate } from '../elements';
import { exportPlainText, getDocumentContent, plainTextToHTML } from './messageContent';
import { getEmbeddedImages, getRemoteImages, restoreImages, updateImages } from './messageImages';
import { insertSignature } from './messageSignature';
// Reference: Angular/src/app/message/services/messageBuilder.js
export const CLASSNAME_BLOCKQUOTE = 'protonmail_quote';
/**
* Copy embeddeds images from the reference message
*/
export const keepImages = (message: PartialMessageState) => {
const embeddedImages = getEmbeddedImages(message);
const remoteImages = getRemoteImages(message);
const Attachments = embeddedImages.map((image) => image.attachment);
const messageImages = updateImages(message.messageImages, undefined, remoteImages, embeddedImages);
return { Attachments, messageImages };
};
/**
* Format and build a new message
* TODO: Define if referenceMessage could ever be defined
*/
const newCopy = (
{
data: { Subject = '', ToList = [], CCList = [], BCCList = [] } = {},
decryption: { decryptedSubject = '' } = {},
}: PartialMessageState = {},
useEncrypted = false
): PartialMessageState => {
return {
data: { Subject: useEncrypted ? decryptedSubject : Subject, ToList, CCList, BCCList },
};
};
/**
* Format and build a reply
*/
export const reply = (referenceMessage: PartialMessageState, useEncrypted = false): PartialMessageState => {
const Subject = formatSubject(
useEncrypted ? referenceMessage.decryption?.decryptedSubject : referenceMessage.data?.Subject,
RE_PREFIX
);
const ToList =
isSent(referenceMessage.data) || isSentAndReceived(referenceMessage.data)
? referenceMessage.data?.ToList
: referenceMessage.data?.ReplyTos;
const { Attachments, messageImages } = keepImages(referenceMessage);
return {
data: { Subject, ToList, Attachments },
messageImages,
};
};
/**
* Format and build a replyAll
*/
export const replyAll = (
referenceMessage: PartialMessageState,
useEncrypted = false,
addresses: Address[]
): PartialMessageState => {
const { data = {}, decryption: { decryptedSubject = '' } = {} } = referenceMessage;
const Subject = formatSubject(useEncrypted ? decryptedSubject : data.Subject, RE_PREFIX);
const { Attachments, messageImages } = keepImages(referenceMessage);
if (isSent(referenceMessage.data) || isSentAndReceived(referenceMessage.data)) {
return {
data: { Subject, ToList: data.ToList, CCList: data.CCList, BCCList: data.BCCList, Attachments },
messageImages,
};
}
const ToList = data.ReplyTos;
const CCListAll: Recipient[] = unique([...(data.ToList || []), ...(data.CCList || [])]);
// Keep other user addresses in the CC list, but remove the address on which the user received the message (using ref message addressID)
const userAddress = canonicalizeInternalEmail(
addresses.find((address) => address.ID === data.AddressID)?.Email || ''
);
const CCList: Recipient[] = CCListAll.filter(({ Address }) => canonicalizeInternalEmail(Address) !== userAddress);
return { data: { Subject, ToList, CCList, Attachments }, messageImages };
};
/**
* Format and build a forward
*/
const forward = (referenceMessage: PartialMessageState, useEncrypted = false): PartialMessageState => {
const { data, decryption: { decryptedSubject = '' } = {} } = referenceMessage;
const Subject = formatSubject(useEncrypted ? decryptedSubject : data?.Subject, FW_PREFIX);
const Attachments = data?.Attachments;
const { messageImages } = keepImages(referenceMessage);
return { data: { Subject, ToList: [], Attachments }, messageImages };
};
export const handleActions = (
action: MESSAGE_ACTIONS,
referenceMessage: PartialMessageState = {},
addresses: Address[] = []
): PartialMessageState => {
// TODO: I would prefere manage a confirm modal from elsewhere
// const useEncrypted = !!referenceMessage.encryptedSubject && (await promptEncryptedSubject(currentMsg));
const useEncrypted = !!referenceMessage?.decryption?.decryptedSubject;
switch (action) {
case MESSAGE_ACTIONS.REPLY:
return reply(referenceMessage, useEncrypted);
case MESSAGE_ACTIONS.REPLY_ALL:
return replyAll(referenceMessage, useEncrypted, addresses);
case MESSAGE_ACTIONS.FORWARD:
return forward(referenceMessage, useEncrypted);
case MESSAGE_ACTIONS.NEW:
default:
return newCopy(referenceMessage, useEncrypted);
}
};
export const getBlockquoteRecipientsString = (recipients: Recipient[] = []) => {
return recipients
.map((recipient) => {
return `${recipient?.Name || recipient?.Address} <${recipient?.Address}>`;
})
.join(', ');
};
export const generatePreviousMessageInfos = (referenceMessage: PartialMessageState, action: MESSAGE_ACTIONS) => {
const senderString = getBlockquoteRecipientsString([referenceMessage.data?.Sender] as Recipient[]);
const date = formatFullDate(getDate(referenceMessage?.data as Message, ''));
if (action === MESSAGE_ACTIONS.FORWARD) {
const ccString = getBlockquoteRecipientsString(referenceMessage.data?.CCList as Recipient[]);
const toString = getBlockquoteRecipientsString(referenceMessage.data?.ToList as Recipient[]);
const ccRecipients = (referenceMessage.data?.CCList?.length || 0) > 0 ? `CC: ${ccString}<br>` : '';
const subject = referenceMessage.data?.Subject;
/*
* translator: String inserted in draft blockquotes when forwarding a message
* ${senderString} is a string containing the sender of the message you're forwarding
* Full sentence for reference: "From: Display Name <address@protonmail.com>"
*/
const fromString = c('forwardmessage').t`From: ${senderString}`;
/*
* translator: String inserted in draft blockquotes when forwarding a message
* ${date} is the localized date "Thursday, October 27th, 2022 at 12:31", for example
* Full sentence for reference: "Date: On Thursday, October 27th, 2022 at 12:31"
*/
const dateString = c('forwardmessage').t`Date: On ${date}`;
/*
* translator: String inserted in draft blockquotes when forwarding a message
* ${subject} is a string containing the subject of the message you're forwarding
*/
const subjectString = c('forwardmessage').t`Subject: ${subject}`;
/*
* translator: String inserted in draft blockquotes when forwarding a message
* ${toString} is a string containing the recipients of the message you're forwarding
* Full sentence for reference: "To: Display Name <address@protonmail.com>"
*/
const recipientString = c('forwardmessage').t`To: ${toString}`;
return `${FORWARDED_MESSAGE}<br>
${fromString}<br>
${dateString}<br>
${subjectString}<br>
${recipientString}<br>
${ccRecipients}<br>`;
} else {
/*
* translator: String inserted in draft blockquotes when replying to a message
* ${date} is the localized date "Thursday, October 27th, 2022 at 12:31", for example
* ${senderString} is a string containing the sender of the message you're replying to
* Full sentence for reference: "On Thursday, October 27th, 2022 at 12:31, Display Name <address@protonmail.com> wrote:"
*/
const previously = c('Message').t`On ${date}, ${senderString} wrote:`;
return `${previously}<br><br>`;
}
};
/**
* Generate blockquote of the referenced message to the content of the new mail
*/
export const generateBlockquote = (
referenceMessage: PartialMessageState,
mailSettings: MailSettings,
userSettings: UserSettings,
addresses: Address[],
action: MESSAGE_ACTIONS
) => {
const previousContent = referenceMessage.errors?.decryption
? referenceMessage.data?.Body
: isPlainText(referenceMessage.data)
? plainTextToHTML(
referenceMessage.data as Message,
referenceMessage.decryption?.decryptedBody,
mailSettings,
userSettings,
addresses
)
: getDocumentContent(restoreImages(referenceMessage.messageDocument?.document, referenceMessage.messageImages));
const previousMessageInfos = generatePreviousMessageInfos(referenceMessage, action);
return `<div class="${CLASSNAME_BLOCKQUOTE}">
${previousMessageInfos}
<blockquote class="${CLASSNAME_BLOCKQUOTE}" type="cite">
${previousContent}
</blockquote><br>
</div>`;
};
export const createNewDraft = (
action: MESSAGE_ACTIONS,
referenceMessage: PartialMessageState | undefined,
mailSettings: MailSettings,
userSettings: UserSettings,
addresses: Address[],
getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined,
isOutside = false,
isQuickReply = false
): PartialMessageState => {
const MIMEType = isOutside
? (mailSettings.DraftMIMEType as unknown as MIME_TYPES)
: referenceMessage?.data?.MIMEType || (mailSettings.DraftMIMEType as unknown as MIME_TYPES);
const { RightToLeft } = mailSettings;
let Flags = 0;
if (mailSettings.AttachPublicKey) {
Flags = setBit(Flags, MESSAGE_FLAGS.FLAG_PUBLIC_KEY);
}
const {
data: { Subject = '', ToList = [], CCList = [], BCCList = [], Attachments: reusedAttachments = [] } = {},
messageImages,
} = handleActions(action, referenceMessage, addresses);
// If there were some pgp attachments, need to upload them as "initialAttachments"
const [Attachments, pgpAttachments] = convertToFile(reusedAttachments, getAttachment);
const originalTo = getOriginalTo(referenceMessage?.data);
const originalFrom = referenceMessage?.data?.Sender?.Address;
const originalAddress =
isSent(referenceMessage?.data) || isSentAndReceived(referenceMessage?.data) ? originalFrom : originalTo;
const originalAddressID = referenceMessage?.data?.AddressID;
const initialAttachments = [...(referenceMessage?.draftFlags?.initialAttachments || []), ...pgpAttachments];
const senderAddress = getFromAddress(addresses, originalAddress, referenceMessage?.data?.AddressID);
const AddressID = senderAddress?.ID || ''; // Set the AddressID from previous message to convert attachments on reply / replyAll / forward
// When writing an EO message, we cannot use the Sender which has an external address, so we need to use the Recipient which is a PM address
const Sender = isOutside
? { Name: referenceMessage?.data?.Sender?.Name || '', Address: referenceMessage?.data?.Sender?.Address || '' }
: senderAddress
? { Name: senderAddress.DisplayName, Address: senderAddress.Email }
: { Name: '', Address: '' };
const ParentID = action === MESSAGE_ACTIONS.NEW ? undefined : referenceMessage?.data?.ID;
let content =
action === MESSAGE_ACTIONS.NEW
? referenceMessage?.decryption?.decryptedBody
? referenceMessage?.decryption?.decryptedBody
: ''
: generateBlockquote(referenceMessage || {}, mailSettings, userSettings, addresses, action);
const fontStyle = defaultFontStyle(mailSettings);
content =
action === MESSAGE_ACTIONS.NEW && referenceMessage?.decryption?.decryptedBody
? insertSignature(content, senderAddress?.Signature, action, mailSettings, userSettings, fontStyle, true)
: insertSignature(content, senderAddress?.Signature, action, mailSettings, userSettings, fontStyle);
const plain = isPlainText({ MIMEType });
const document = plain ? undefined : parseInDiv(content);
// Prevent nested ternary
const getPlainTextContent = (content: string) => {
const exported = exportPlainText(content);
return exported === '' ? '' : `\n\n${exported}`;
};
const plainText = plain ? getPlainTextContent(content) : undefined;
return {
localID: generateUID(DRAFT_ID_PREFIX),
data: {
ToList,
CCList,
BCCList,
Subject,
PasswordHint: '',
Attachments,
MIMEType,
RightToLeft,
Flags,
Sender,
AddressID,
Unread: 0,
},
messageDocument: {
initialized: true,
document,
plainText,
},
draftFlags: {
ParentID,
action,
originalTo,
originalFrom,
originalAddressID,
originalMessageFlags: referenceMessage?.data?.Flags,
initialAttachments,
isQuickReply,
},
messageImages,
};
};
export const cloneDraft = (draft: MessageStateWithData): MessageStateWithData => {
return {
...draft,
data: { ...draft.data },
messageDocument: {
...draft.messageDocument,
document: draft.messageDocument?.document?.cloneNode(true) as Element,
},
};
};
export const isNewDraft = (localID: string | undefined) => !!localID?.startsWith(DRAFT_ID_PREFIX);
| 3,874
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageEmbeddeds.test.tsx
|
import { stringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { MessageEmbeddedImage, MessageImage, PartialMessageState } from '../../logic/messages/messagesTypes';
import { createDocument } from '../test/message';
import {
createBlob,
createEmbeddedImageFromUpload,
embeddableTypes,
findCIDsInContent,
findEmbedded,
generateCid,
insertActualEmbeddedImages,
insertBlobImages,
isEmbeddable,
markEmbeddedImagesAsLoaded,
matchSameCidOrLoc,
readContentIDandLocation,
removeEmbeddedHTML,
replaceEmbeddedAttachments,
setEmbeddedAttr,
trimQuotes,
} from './messageEmbeddeds';
const contentID = 'my-content-id';
const contentLocation = 'my-content-location';
const attachmentID = 'attachmentID';
const attachment = {
Headers: {
'content-id': contentID,
'content-location': contentLocation,
},
ID: attachmentID,
} as Attachment;
describe('messageEmbeddeds', () => {
describe('trimQuotes', () => {
it('should trim quotes', () => {
const string1 = `'string'`;
const string2 = `"string"`;
const string3 = `<string>`;
const expected = 'string';
expect(trimQuotes(string1)).toEqual(expected);
expect(trimQuotes(string2)).toEqual(expected);
expect(trimQuotes(string3)).toEqual(expected);
});
});
describe('isEmbeddable', () => {
it('should be an embeddable file', () => {
const types = embeddableTypes;
types.forEach((type) => {
expect(isEmbeddable(type)).toBeTruthy();
});
});
it('should not be an embeddable file', () => {
const types = ['something', 'application/json', 'image/webp'];
types.forEach((type) => {
expect(isEmbeddable(type)).toBeFalsy();
});
});
});
describe('readContentIDandLocation', () => {
it('should read attachment content id and content location headers', () => {
const { cid, cloc } = readContentIDandLocation(attachment);
expect(cid).toEqual(contentID);
expect(cloc).toEqual(contentLocation);
});
it('should read content id and content location headers with line breaks', () => {
const contentID = `my-content
-id`;
const contentLocation = `my
-content-location`;
const headers = {
'content-id': contentID,
'content-location': contentLocation,
};
const { cid, cloc } = readContentIDandLocation({ Headers: headers });
expect(cid).toEqual('my-content-id');
expect(cloc).toEqual('my-content-location');
});
});
describe('matchSameCidOrLoc', () => {
it('should match the image with cid', () => {
const image = {
cid: contentID,
} as MessageEmbeddedImage;
expect(matchSameCidOrLoc(image, contentID, '')).toBeTruthy();
});
it('should match the image with cloc', () => {
const image = {
cloc: contentLocation,
} as MessageEmbeddedImage;
expect(matchSameCidOrLoc(image, '', contentLocation)).toBeTruthy();
});
it('should not match the image with cloc or cid', () => {
const image = {
cid: 'something',
cloc: 'something else',
} as MessageEmbeddedImage;
expect(matchSameCidOrLoc(image, contentID, contentLocation)).toBeFalsy();
});
});
describe('generateCid', () => {
it('should generate cid', () => {
const input = 'something';
const email = 'test@pm.me';
expect(generateCid(input, email)).toMatch(/([0-9]|[a-z]){8}@pm\.me/);
});
});
describe('setEmbeddedAttr', () => {
it('should set element cid', () => {
const el = document.createElement('img');
setEmbeddedAttr(contentID, contentLocation, el);
const expectedAttr = `cid:${contentID}`;
expect(el.getAttribute('data-embedded-img')).toEqual(expectedAttr);
});
it('should set element cloc', () => {
const el = document.createElement('img');
setEmbeddedAttr('', contentLocation, el);
const expectedAttr = `cloc:${contentLocation}`;
expect(el.getAttribute('data-embedded-img')).toEqual(expectedAttr);
});
it('should not set element attribute', () => {
const el = document.createElement('img');
setEmbeddedAttr('', '', el);
expect(el.getAttribute('data-embedded-img')).toBeNull();
});
});
describe('createBlob', () => {
beforeEach(() => {
global.URL.createObjectURL = jest.fn(() => 'url');
});
it('should create a blob', () => {
const data = stringToUint8Array('data');
const attachment = { MIMEType: 'image/png' } as Attachment;
const blob = createBlob(attachment, data);
expect(blob).toEqual('url');
});
});
describe('createEmbeddedImageFromUpload', () => {
const expectedImage = {
type: 'embedded',
cid: contentID,
cloc: contentLocation,
tracker: undefined,
attachment,
status: 'loaded',
} as MessageEmbeddedImage;
// Ignore generated id for testing
const { id, ...embeddedImage } = createEmbeddedImageFromUpload(attachment);
expect(embeddedImage).toEqual(expectedImage);
});
describe('finEmbedded', () => {
it.each`
attribute | value
${'src'} | ${`${contentID}`}
${'src'} | ${`cid:${contentID}`}
${'data-embedded-img'} | ${`${contentID}`}
${'data-embedded-img'} | ${`cid:${contentID}`}
${'data-src'} | ${`cid:${contentID}`}
${'proton-src'} | ${`cid:${contentID}`}
`('should find cid image', ({ attribute, value }) => {
const string = `<div>
<img src="random">
<img ${attribute}="${value}"/>
<span>something</span>
</div>`;
const document = createDocument(string);
const expectedImg = window.document.createElement('img');
expectedImg.setAttribute(attribute, value);
expect(findEmbedded(contentID, contentLocation, document)).toEqual([expectedImg]);
});
it('should find cloc images', () => {
const string = `<div>
<img src="random">
<img proton-src="${contentLocation}"/>
<span>something</span>
</div>`;
const document = createDocument(string);
const expectedImg = window.document.createElement('img');
expectedImg.setAttribute('proton-src', contentLocation);
expect(findEmbedded('', contentLocation, document)).toEqual([expectedImg]);
});
it('should not find images', () => {
const string = `<div>
<img src="random">
<span>something</span>
</div>`;
const document = createDocument(string);
expect(findEmbedded(contentID, contentLocation, document)).toEqual([]);
});
});
describe('findCIDsInContent', () => {
it('should find a cid in content', () => {
const string = `<div>
<img src="random" data-embedded-img="${contentID}">
<span>something</span>
</div>`;
expect(findCIDsInContent(string)).toBeTruthy();
});
it('should not a cid in content', () => {
const string = `<div>
<img src="random">
<span>something</span>
</div>`;
expect(findCIDsInContent(string)).toBeTruthy();
});
});
describe('insertActualEmbeddedImages', () => {
it('should insert cid image', function () {
const string = `<div>
<img src="random" data-embedded-img="cid:${contentID}">
<span>something</span>
</div>`;
const document = createDocument(string);
insertActualEmbeddedImages(document);
expect(document.querySelector('img')?.getAttribute('src')).toEqual(`cid:${contentID}`);
const imageWithDataAttribute = document.querySelector('img[data-embedded-img]');
expect(imageWithDataAttribute).toBeNull();
});
it('should insert cloc image', function () {
const string = `<div>
<img src="random" data-embedded-img="cloc:${contentLocation}">
<span>something</span>
</div>`;
const document = createDocument(string);
insertActualEmbeddedImages(document);
expect(document.querySelector('img')?.getAttribute('src')).toEqual(`${contentLocation}`);
const imageWithDataAttribute = document.querySelector('img[data-embedded-img]');
expect(imageWithDataAttribute).toBeNull();
});
});
describe('replaceEmbeddedAttachments', () => {
it('should replace embedded attachments', () => {
const message = {
messageImages: {
hasEmbeddedImages: true,
images: [{ cid: contentID, type: 'embedded' } as MessageEmbeddedImage] as MessageImage[],
},
} as PartialMessageState;
const res = replaceEmbeddedAttachments(message, [attachment]);
const expected = {
attachment: {
Headers: {
'content-id': contentID,
'content-location': contentLocation,
},
ID: attachmentID,
} as Attachment,
cid: contentID,
type: 'embedded',
} as MessageEmbeddedImage;
expect(res.images).toEqual([expected]);
});
});
describe('remoteEmbeddedHTML', () => {
it('should remove embedded attachment from the document', () => {
const string = `<div>
<img src="random" data-embedded-img="${contentID}">
<span>something</span>
</div>`;
const document = createDocument(string);
removeEmbeddedHTML(document, attachment);
expect(document.querySelector('img')).toBeNull();
});
});
describe('insertBlobImages', () => {
it('should insert blob image', () => {
const url = 'https://image.com/img.png';
const string = `<div>
<img proton-src="${url}" data-embedded-img="${contentID}">
<span>something</span>
</div>`;
const document = createDocument(string);
const embeddedImages = [
{ cid: contentID, type: 'embedded', url } as MessageEmbeddedImage,
] as MessageEmbeddedImage[];
insertBlobImages(document, embeddedImages);
const image = document.querySelector('img');
expect(image?.getAttribute('proton-src')).toBeNull();
expect(image?.getAttribute('src')).toEqual(url);
});
});
describe('markEmbeddedImagesAsLoaded', () => {
it('should mark embedded images as loaded', () => {
const blobURL = 'blobURL';
const embeddedImages = [
{
cid: contentID,
type: 'embedded',
attachment: { ID: attachmentID } as Attachment,
} as MessageEmbeddedImage,
] as MessageEmbeddedImage[];
const loadResults: { attachment: Attachment; blob: string }[] = [{ attachment, blob: blobURL }];
const res = markEmbeddedImagesAsLoaded(embeddedImages, loadResults);
const expected = [
{
attachment: { ID: attachmentID },
cid: contentID,
status: 'loaded',
type: 'embedded',
url: blobURL,
},
] as MessageEmbeddedImage[];
expect(res).toEqual(expected);
});
});
});
| 3,875
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageEmbeddeds.ts
|
import { getEmailParts } from '@proton/shared/lib/helpers/email';
import generateUID from '@proton/shared/lib/helpers/generateUID';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import unique from '@proton/utils/unique';
import { ENCRYPTED_STATUS } from '../../constants';
import { LoadEmbeddedResults, MessageEmbeddedImage, PartialMessageState } from '../../logic/messages/messagesTypes';
import { hash, removeLineBreaks, toUnsignedString } from '../string';
import { querySelectorAll } from './messageContent';
import { getEmbeddedImages, updateImages } from './messageImages';
const urlCreator = () => window.URL || window.webkitURL;
export const embeddableTypes = ['image/gif', 'image/jpeg', 'image/png', 'image/bmp'];
/**
* Removes enclosing quotes ("", '', <>) from a string
*/
export const trimQuotes = (input: string) => {
const value = `${input || ''}`.trim(); // input can be a number
if (['"', "'", '<'].indexOf(value.charAt(0)) > -1 && ['"', "'", '>'].indexOf(value.charAt(value.length - 1)) > -1) {
return value.substring(1, value.length - 1);
}
return value;
};
/**
* Is a file type embeddable or not
*/
export const isEmbeddable = (fileType: string) => embeddableTypes.includes(fileType);
/**
* Read CID of the attachment (through its header)
*/
export const readContentIDandLocation = ({ Headers = {} }: Attachment = {}) => {
let cid = '';
let cloc = '';
if (Headers['content-id']) {
cid = removeLineBreaks(trimQuotes(Headers['content-id']));
}
// We can find an image without cid so base64 the location
if (Headers['content-location']) {
cloc = removeLineBreaks(trimQuotes(Headers['content-location']));
}
return { cid, cloc };
};
export const matchSameCidOrLoc = (image: MessageEmbeddedImage, cid: string, cloc: string) =>
(cid !== '' && image.cid === cid) || (cloc !== '' && image.cloc === cloc);
/**
* Generate CID from input and email
*/
export const generateCid = (input: string, email: string) => {
const hashValue = toUnsignedString(hash(input), 4);
const [, domain] = getEmailParts(email);
return `${hashValue}@${domain}`;
};
export const setEmbeddedAttr = (cid: string, cloc: string, element: Element) => {
if (cid) {
element.setAttribute('data-embedded-img', `cid:${cid}`);
} else if (cloc) {
element.setAttribute('data-embedded-img', `cloc:${cloc}`);
}
};
/**
* Create a Blob and its URL for an attachment
*/
export const createBlob = (attachment: Attachment, data: Uint8Array | string) => {
const blob = new Blob([data], { type: attachment.MIMEType });
return urlCreator().createObjectURL(blob);
};
/**
* Prepare MessageEmbeddedImage structure based on an upload result
*/
export const createEmbeddedImageFromUpload = (attachment: Attachment): MessageEmbeddedImage => {
const { cid, cloc } = readContentIDandLocation(attachment);
return {
type: 'embedded',
id: generateUID('embedded'),
cid,
cloc,
tracker: undefined,
attachment,
status: 'loaded',
};
};
/**
* Find embedded element in div
*/
export const findEmbedded = (cid: string, cloc: string, document: Element) => {
let selector: string[] = [];
// If cid and cloc are an empty string, it can give a false positive
if (!cid && !cloc) {
return [];
}
if (cid) {
selector = [
`img[src="${cid}"]`,
`img[src="cid:${cid}"]`,
`img[data-embedded-img="${cid}"]`,
`img[data-embedded-img="cid:${cid}"]`,
`img[data-src="cid:${cid}"]`,
`img[proton-src="cid:${cid}"]`,
];
}
if (cloc) {
selector = [...selector, `img[proton-src="${cloc}"]`];
}
return querySelectorAll({ messageDocument: { document } }, selector.join(', '));
};
/**
* Find CIDs in content diff from the editor to detect embedded deletion
* (with compat mode for old embedded)
*/
export const findCIDsInContent = (content: string) =>
(content.match(/(rel=("([^"]|"")*"))|(data-embedded-img=("([^"]|"")*"))/g) || [])
.filter((key) => key !== 'rel="noreferrer nofollow noopener"') // we don't care about links
.filter((key) => key !== 'rel="noopener noreferrer"') // we don't care about links
.map((key) => key.replace(/rel="|data-embedded-img="/, ''))
.map((key) => key.slice(4, -1)); // Assume it's starts by "cid:"
/**
* Insert actual src="cid:..." into embedded image elements
*/
export const insertActualEmbeddedImages = (document: Element) => {
querySelectorAll({ messageDocument: { document } }, '[data-embedded-img]').forEach((element) => {
const cidOrCloc = element.getAttribute('data-embedded-img');
element.removeAttribute('data-embedded-img');
element.removeAttribute('proton-src');
element.removeAttribute('src');
if (cidOrCloc?.startsWith('cid')) {
element.setAttribute('src', `cid:${cidOrCloc.slice(4)}`);
} else if (cidOrCloc?.startsWith('cloc')) {
element.setAttribute('src', cidOrCloc.slice(5));
}
});
};
/**
* Replace attachments in embedded images with new ones
*/
export const replaceEmbeddedAttachments = (
message: PartialMessageState,
attachments: Attachment[] | undefined = []
) => {
const embeddedImages = getEmbeddedImages(message);
const newEmbeddedImages = embeddedImages.map((image) => {
const attachment = attachments.find((attachment) => {
const { cid, cloc } = readContentIDandLocation(attachment);
return matchSameCidOrLoc(image, cid, cloc);
});
if (attachment) {
return { ...image, attachment };
}
return image;
});
return updateImages(message.messageImages, undefined, undefined, newEmbeddedImages);
};
/**
* Remove an embedded attachment from the document
*/
export const removeEmbeddedHTML = (document: Element, attachment: Attachment) => {
const { cid, cloc } = readContentIDandLocation(attachment);
const elements = findEmbedded(cid, cloc, document);
elements.map((node) => node.remove());
};
/**
* Set blob url src on embedded images of the document
*/
export const insertBlobImages = (document: Element, embeddedImages: MessageEmbeddedImage[]) => {
embeddedImages.forEach((embeddedImage) => {
const { cid, cloc, url } = embeddedImage;
if (url) {
findEmbedded(cid, cloc, document).forEach((element) => {
element.removeAttribute('proton-src');
element.setAttribute('src', url);
});
}
});
};
/**
* Based on the loadResults, update the embeddedImages with a url and the loaded state
*/
export const markEmbeddedImagesAsLoaded = (
embeddedImages: MessageEmbeddedImage[],
loadResults: { attachment: Attachment; blob: string }[]
) => {
return embeddedImages.map((image) => {
const result = loadResults.find((loadResult) => loadResult.attachment.ID === image.attachment.ID);
if (result) {
return { ...image, url: result?.blob, status: 'loaded' as 'loaded' };
}
return image;
});
};
/**
* Download and decrypt embedded images
*/
export const decryptEmbeddedImages = (
images: MessageEmbeddedImage[],
onLoadEmbeddedImages: (attachments: Attachment[]) => Promise<LoadEmbeddedResults>
) => {
const attachments = unique(
images
.filter(({ status }) => status === 'not-loaded')
.filter((info) => info.attachment.KeyPackets || info.attachment.Encrypted === ENCRYPTED_STATUS.PGP_MIME)
.map((image) => (image as MessageEmbeddedImage).attachment)
);
const updatedImages = images.map((image) => {
if (attachments.includes(image.attachment) && image.status === 'not-loaded') {
return { ...image, status: 'loading' } as MessageEmbeddedImage;
}
return image;
});
const downloadPromise = onLoadEmbeddedImages(attachments);
return { updatedImages, downloadPromise };
};
| 3,876
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageExpandable.test.ts
|
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { findMessageToExpand } from './messageExpandable';
describe('messageExpandable', () => {
it('should return last message if not a custom label and all are reads', () => {
const labelID = MAILBOX_LABEL_IDS.INBOX;
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[2]);
});
it('should return last unread message if not a custom label and all are not reads', () => {
const labelID = MAILBOX_LABEL_IDS.INBOX;
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 1 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 1 },
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[1]);
});
it('should return last unread message if in starred label', () => {
const labelID = MAILBOX_LABEL_IDS.STARRED;
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, LabelIDs: [labelID], Unread: 1 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, LabelIDs: [labelID], Unread: 1 },
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[1]);
});
it('should return last unread message if in starred label', () => {
const labelID = 'my custom label';
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, Unread: 0 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, LabelIDs: [labelID], Unread: 1 },
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED, LabelIDs: [labelID], Unread: 1 },
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[1]);
});
it('should return last message if in draft label', () => {
const labelID = MAILBOX_LABEL_IDS.DRAFTS;
const messages = [
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_REPLIED }, // draft
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_REPLIED }, // draft
{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_RECEIVED }, // not draft
] as Message[];
expect(findMessageToExpand(labelID, messages)).toBe(messages[1]);
});
it('should return empty for a conversation with only a draft', () => {
const labelID = 'custom';
const messages = [{ ID: '', ConversationID: '', Flags: MESSAGE_FLAGS.FLAG_REPLIED }] as Message[];
expect(findMessageToExpand(labelID, messages)).toBeUndefined();
});
});
| 3,877
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageExpandable.ts
|
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { isDraft, isSentAutoReply } from '@proton/shared/lib/mail/messages';
import { PLACEHOLDER_ID_PREFIX } from '../../hooks/usePlaceholders';
import { hasLabel } from '../elements';
import { isCustomLabelOrFolder } from '../labels';
// Reference: Angular/src/app/message/services/findExpandableMessage.js
/**
* Filter the list of message to find the first readable message
* - iterate backwards
* - check if the previous item is read
* - if the previous isRead === 1, break the iteration
*/
const getFirstMessageToRead = (messages: Message[]): Message | undefined => {
// A conversation can contains only one draft
if (messages.length === 0) {
return;
}
// Else we open the first message unread beginning to the end list
let index = messages.length;
let contains = false;
while (--index > 0) {
if (messages[index - 1].Unread === 0) {
// Is read
contains = true;
break;
}
}
const position = contains ? index : 0;
return messages[position];
};
const getLast = (messages: Message[]): Message | undefined => {
if (messages.length === 0) {
return;
}
return messages[messages.length - 1];
};
/**
* Find in the message to scroll and expand
*/
export const findMessageToExpand = (labelID = '', messages: Message[] = []): Message | undefined => {
if (messages.length === 0) {
return;
}
if (messages[0].ID.startsWith(PLACEHOLDER_ID_PREFIX)) {
return getLast(messages);
}
if (labelID === MAILBOX_LABEL_IDS.STARRED || isCustomLabelOrFolder(labelID)) {
return getFirstMessageToRead(messages.filter((message) => hasLabel(message, labelID) && !isDraft(message)));
}
if (labelID === MAILBOX_LABEL_IDS.DRAFTS || labelID === MAILBOX_LABEL_IDS.ALL_DRAFTS) {
return getLast(messages.filter(isDraft));
}
const realMessages = messages.filter((message) => !isDraft(message) && !isSentAutoReply(message));
const latest = getLast(realMessages);
if (latest && latest.Unread === 0) {
return latest;
}
return getFirstMessageToRead(realMessages);
};
| 3,878
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageExpirationTime.ts
|
import { format, fromUnixTime, isToday, isTomorrow } from 'date-fns';
import { c } from 'ttag';
import { MessageState } from '../../logic/messages/messagesTypes';
import { formatFullDate } from '../date';
export const getMessageExpirationDate = (message: MessageState) => {
if (message.data?.ExpirationTime) {
return fromUnixTime(message.data.ExpirationTime);
} else if (message.draftFlags?.expiresIn) {
return message.draftFlags.expiresIn;
}
return undefined;
};
export const getExpiresOnMessage = (expirationDate: Date) => {
const shortDateMessage = format(expirationDate, 'p');
if (isToday(expirationDate)) {
//translator: Full sentence for reference: "This message will expire today at 12:30 PM"
return c('Info').t`This message will expire today at ${shortDateMessage}`;
} else if (isTomorrow(expirationDate)) {
// translator: Full sentence for reference: "This message will expire tomorrow at 12:30 PM"
return c('Info').t`This message will expire tomorrow at ${shortDateMessage}`;
} else {
const longDateMEssage = formatFullDate(expirationDate);
// translator: Full sentence for reference: "This message will expire on Tuesday, May 11 at 12:30 PM"
return c('Info').t`This message will expire on ${longDateMEssage}`;
}
};
export const getAutoDeleteOnMessage = (expirationDate: Date) => {
const shortDateMessage = format(expirationDate, 'p');
if (isToday(expirationDate)) {
//translator: Full sentence for reference: "This message will be automatically deleted on 12:30 PM"
return c('Info').t`This message will be automatically deleted on ${shortDateMessage}`;
} else if (isTomorrow(expirationDate)) {
// translator: Full sentence for reference: "This message will be automatically deleted on 12:30 PM"
return c('Info').t`This message will be automatically deleted on ${shortDateMessage}`;
} else {
const longDateMEssage = formatFullDate(expirationDate);
// translator: Full sentence for reference: "This message will be automatically deleted on Tuesday, May 11 at 12:30 PM"
return c('Info').t`This message will be automatically deleted on ${longDateMEssage}`;
}
};
| 3,879
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageExport.ts
|
import { CryptoProxy, PrivateKeyReference, PublicKeyReference, WorkerDecryptionResult } from '@proton/crypto';
import { arrayToBinaryString, encodeBase64 } from '@proton/crypto/lib/utils';
import { createDraft, updateDraft } from '@proton/shared/lib/api/messages';
import { parseStringToDOM } from '@proton/shared/lib/helpers/dom';
import { Api } from '@proton/shared/lib/interfaces';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { CREATE_DRAFT_MESSAGE_ACTION } from '@proton/shared/lib/interfaces/message';
import { getAttachments, isPlainText } from '@proton/shared/lib/mail/messages';
import { getSessionKey } from '@proton/shared/lib/mail/send/attachments';
import { MESSAGE_ACTIONS } from '../../constants';
import { GetMessageKeys } from '../../hooks/message/useGetMessageKeys';
import { MessageKeys, MessageState, MessageStateWithData, PublicPrivateKey } from '../../logic/messages/messagesTypes';
import { combineHeaders, splitMail } from '../mail';
import { constructMimeFromSource } from '../send/sendMimeBuilder';
import { getPlainTextContent } from './messageContent';
import { insertActualEmbeddedImages } from './messageEmbeddeds';
import { replaceProxyWithOriginalURLAttributes } from './messageImages';
const removePasswordFromRequests: Pick<Message, 'Password' | 'PasswordHint'> = {
Password: undefined,
PasswordHint: undefined,
};
const restorePasswordFromResults = (
resultMessage: Message,
originalMessage: Pick<Message, 'Password' | 'PasswordHint'>
): Message => ({
...resultMessage,
Password: originalMessage.Password,
PasswordHint: originalMessage.PasswordHint,
});
export const prepareExport = (message: MessageState) => {
if (!message.messageDocument?.document) {
return '';
}
const document = message.messageDocument.document.cloneNode(true) as Element;
// Using create element will create a DOM element that will not be added to the window's document, but images will be loaded
// Use a DOMParser instead so that images are not loaded.
const dom = parseStringToDOM(document.innerHTML);
// Embedded images
insertActualEmbeddedImages(dom.body);
// Clean remote images
return replaceProxyWithOriginalURLAttributes(message, dom.body);
};
const encryptBody = async (content: string, messageKeys: PublicPrivateKey) => {
const publicKeys = messageKeys.publicKeys.slice(0, 1);
const privateKeys = messageKeys.privateKeys.slice(0, 1);
const { message: data } = await CryptoProxy.encryptMessage({
textData: content,
stripTrailingSpaces: true,
encryptionKeys: publicKeys,
signingKeys: privateKeys,
});
return data;
};
export const prepareAndEncryptBody = async (message: MessageState, messageKeys: MessageKeys) => {
const plainText = isPlainText(message.data);
const content = plainText ? getPlainTextContent(message) : prepareExport(message);
return encryptBody(content, messageKeys as PublicPrivateKey);
};
export const encryptAttachmentKeyPackets = async (
attachments: Attachment[],
previousAddressPrivateKeys: PrivateKeyReference[] = [],
newAddressPublicKeys: PublicKeyReference[] = [],
messageFlags?: number
) => {
// Only need the first key for encryption (the primary key)
const [primaryEncryptionKey] = newAddressPublicKeys;
return Object.fromEntries(
await Promise.all(
attachments
.filter(({ ID = '' }) => ID.indexOf('PGPAttachment'))
.map(async (attachment) => {
const sessionKey = await getSessionKey(attachment, previousAddressPrivateKeys, messageFlags);
const encryptedSessionKey = await CryptoProxy.encryptSessionKey({
data: sessionKey.data,
algorithm: sessionKey.algorithm,
encryptionKeys: primaryEncryptionKey,
format: 'binary',
});
return [attachment.ID || '', encodeBase64(arrayToBinaryString(encryptedSessionKey))];
})
)
);
};
export const createMessage = async (
message: MessageStateWithData,
api: Api,
getMessageKeys: GetMessageKeys
): Promise<Message> => {
const messageKeys = await getMessageKeys(message.data);
const Body = await prepareAndEncryptBody(message, messageKeys);
const attachments = getAttachments(message.data);
let AttachmentKeyPackets;
if (attachments?.length) {
const originalMessageKeys = await getMessageKeys({
AddressID: message.draftFlags?.originalAddressID || message.data?.AddressID,
});
AttachmentKeyPackets = await encryptAttachmentKeyPackets(
attachments,
originalMessageKeys.privateKeys,
messageKeys.publicKeys,
message.draftFlags?.originalMessageFlags
);
}
const getMessageAction = (action: MESSAGE_ACTIONS | undefined): CREATE_DRAFT_MESSAGE_ACTION | undefined => {
if (action !== MESSAGE_ACTIONS.NEW && action !== undefined) {
return action as unknown as CREATE_DRAFT_MESSAGE_ACTION;
}
return undefined;
};
const { Message: updatedMessage } = await api(
createDraft({
Action: getMessageAction(message.draftFlags?.action),
Message: { ...message.data, Body, ...removePasswordFromRequests },
ParentID: message.draftFlags?.ParentID,
AttachmentKeyPackets,
})
);
return restorePasswordFromResults(updatedMessage, message.data);
};
/**
* Update an already existing message by encrypting it then send the API request to the API
* @param message The message to update containing the right keys related to the address
* @param senderHasChanged Things are different if the sender has changed since the last version
* @param previousAddressPrivateKeys Only needed if senderHasChanged to decrypt attachments sessionKeys and re-encrypt with the new address key
* @param api Api handler to use
*/
export const updateMessage = async (
message: MessageStateWithData,
previousAddressID: string,
api: Api,
getMessageKeys: GetMessageKeys
): Promise<Message> => {
const messageKeys = await getMessageKeys(message.data);
const Body = await prepareAndEncryptBody(message, messageKeys);
const attachments = getAttachments(message.data);
let AttachmentKeyPackets;
if (attachments?.length && previousAddressID !== message.data.AddressID) {
const previousMessageKeys = await getMessageKeys({ AddressID: previousAddressID });
AttachmentKeyPackets = await encryptAttachmentKeyPackets(
attachments,
previousMessageKeys.privateKeys,
messageKeys.publicKeys
);
}
const { Message: updatedMessage } = await api({
...updateDraft(message.data?.ID, {
Message: { ...message.data, Body, ...removePasswordFromRequests },
AttachmentKeyPackets,
}),
silence: true,
});
return restorePasswordFromResults(updatedMessage, message.data);
};
/**
* Prepare a message a blob to download
* Use mime format, don't encrypt,
*/
export const exportBlob = async (
message: MessageState,
messageKeys: MessageKeys,
getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined,
onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void,
api: Api
) => {
const mimeMessage = await constructMimeFromSource(message, messageKeys, getAttachment, onUpdateAttachment, api);
const { body, headers: mimeHeaders } = splitMail(mimeMessage);
const headers = await combineHeaders(message.data?.Header || '', mimeHeaders);
return new Blob([`${headers}\r\n${body}`], {
type: 'data:text/plain;charset=utf-8;',
});
};
| 3,880
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageHead.test.ts
|
import mails from './__fixtures__/messageHead.fixtures';
import { locateHead } from './messageHead';
/**
* Creating a whole document each time is needed because locate blockquote is using xpath request
* which will fail if the content is not actually in the document
*/
const createDocument = (content: string) => {
const newDocument = document.implementation.createHTMLDocument();
newDocument.documentElement.innerHTML = content;
return newDocument;
};
describe('messageHead', () => {
it(`Should find head in a basic email`, () => {
const head = locateHead(createDocument(mails.baseEmail));
expect(head).toContain(`<style type="text/css">a {padding:0;}</style>`);
});
});
| 3,881
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageHead.ts
|
export const locateHead = (inputDocument: Element | Document | undefined): string | undefined => {
if (!inputDocument) {
return undefined;
}
const head = inputDocument.querySelector('head');
return head?.innerHTML;
};
| 3,882
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageImages.test.ts
|
import { MessageImage, MessageImages, MessageState } from '../../logic/messages/messagesTypes';
import { createDocument } from '../test/message';
import { removeProxyURLAttributes, replaceProxyWithOriginalURLAttributes } from './messageImages';
const imageURL = 'imageURL';
const originalImageURL = 'originalImageURL';
describe('removeProxyURLAttributes', () => {
const content = `<div>
<img proton-src='${originalImageURL}-1' src='${imageURL}-1'/>
<table>
<tbody>
<tr>
<td proton-background='${originalImageURL}-2' background='${imageURL}-2'>Element1</td>
</tr>
</tbody>
</table>
<video proton-poster='${originalImageURL}-3' poster='${imageURL}-3'>
<source src="" type="video/mp4">
</video>
<svg width="90" height="90">
<image proton-xlink:href='${originalImageURL}-4' xlink:href='${imageURL}-4'/>
</svg>
</div>`;
it('should remove all proton urls from the content', () => {
const expectedContent = `<div>
<img src="${originalImageURL}-1">
<table>
<tbody>
<tr>
<td background="${originalImageURL}-2">Element1</td>
</tr>
</tbody>
</table>
<video poster="${originalImageURL}-3">
<source src="" type="video/mp4">
</video>
<svg width="90" height="90">
<image xlink:href="${originalImageURL}-4"></image>
</svg>
</div>`;
const result = removeProxyURLAttributes(content);
expect(result).toEqual(expectedContent);
});
it('should not remove urls from embedded images', () => {
const cid = 'imageCID';
const content = `<div>
<img src="cid:${cid}"/>
<img proton-src="${originalImageURL}-1" src="${imageURL}-1"/>
</div>`;
const expectedContent = `<div>
<img src="cid:${cid}">
<img src="${originalImageURL}-1">
</div>`;
const result = removeProxyURLAttributes(content);
expect(result).toEqual(expectedContent);
});
it('should not remove urls from images with no originalURL', () => {
const content = `<div>
<img src="${imageURL}-1"/>
<img proton-src="${originalImageURL}-2" src="${originalImageURL}-2"/>
<img proton-src="${originalImageURL}-3" src="${imageURL}-3"/>
</div>`;
const expectedContent = `<div>
<img src="${imageURL}-1">
<img src="${originalImageURL}-2">
<img src="${originalImageURL}-3">
</div>`;
const result = removeProxyURLAttributes(content);
expect(result).toEqual(expectedContent);
});
});
describe('replaceProxyWithOriginalURLAttributes', () => {
const content = `<div>
<img proton-src='${originalImageURL}-1' src='${imageURL}-1'/>
<img proton-src='${originalImageURL}-2' src='${originalImageURL}-2'/>
<img src='${originalImageURL}-3'/>
<img proton-src='${originalImageURL}-4'/>
<table>
<tbody>
<tr>
<td proton-background='${originalImageURL}-5' background='${imageURL}-5' >Element1</td>
</tr>
</tbody>
</table>
<video proton-poster='${originalImageURL}-6' poster='${imageURL}-6'>
<source src="" type="video/mp4">
</video>
<svg width="90" height="90">
<image proton-xlink:href='${originalImageURL}-7' xlink:href='${imageURL}-7'/>
</svg>
</div>`;
it('should remove proton attributes and use the original URL', () => {
const messageImages = {
hasRemoteImages: true,
images: [
{ type: 'remote', url: `${imageURL}-1`, originalURL: `${originalImageURL}-1` } as MessageImage,
{ type: 'remote', url: `${originalImageURL}-2`, originalURL: `${originalImageURL}-2` } as MessageImage,
{ type: 'remote', url: `${imageURL}-3` } as MessageImage,
{ type: 'remote', url: `${imageURL}-4` } as MessageImage,
{ type: 'remote', url: `${imageURL}-5`, originalURL: `${originalImageURL}-5` } as MessageImage,
{ type: 'remote', url: `${imageURL}-6`, originalURL: `${originalImageURL}-6` } as MessageImage,
{ type: 'remote', url: `${imageURL}-7`, originalURL: `${originalImageURL}-7` } as MessageImage,
],
} as MessageImages;
const message = {
messageImages,
} as MessageState;
const expected = `<div>
<img src="${originalImageURL}-1">
<img src="${originalImageURL}-2">
<img src="${originalImageURL}-3">
<img src="${originalImageURL}-4">
<table>
<tbody>
<tr>
<td background="${originalImageURL}-5">Element1</td>
</tr>
</tbody>
</table>
<video poster="${originalImageURL}-6">
<source src="" type="video/mp4">
</video>
<svg width="90" height="90">
<image xlink:href="${originalImageURL}-7"></image>
</svg>
</div>`;
const result = replaceProxyWithOriginalURLAttributes(message, createDocument(content));
expect(result).toEqual(expected);
});
});
| 3,883
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageImages.ts
|
import { PrivateAuthenticationStore } from '@proton/components/containers';
import { parseStringToDOM } from '@proton/shared/lib/helpers/dom';
import { Api } from '@proton/shared/lib/interfaces';
import uniqueBy from '@proton/utils/uniqueBy';
import {
loadFakeProxy,
loadRemoteDirectFromURL,
loadRemoteProxyFromURL,
} from '../../logic/messages/images/messagesImagesActions';
import {
LoadRemoteResults,
MessageEmbeddedImage,
MessageImage,
MessageImages,
MessageRemoteImage,
MessageState,
PartialMessageState,
} from '../../logic/messages/messagesTypes';
import { getDocumentContent } from './messageContent';
import { setEmbeddedAttr } from './messageEmbeddeds';
import { ATTRIBUTES_TO_LOAD } from './messageRemotes';
const REGEXP_FIXER = (() => {
const str = ATTRIBUTES_TO_LOAD.map((key) => `proton-${key}`).join('|');
return `(${str})`;
})();
export const getRemoteSelector = (hasProtonAttribute = false) => {
return ATTRIBUTES_TO_LOAD.map((name) => {
// 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 `[${hasProtonAttribute ? 'proton-' : ''}${name}]`;
}).join(',');
};
export const getAnchor = (document: Element | null | undefined, image: MessageImage) => {
if (!document) {
return null;
}
return document.querySelector(
`.proton-image-anchor[data-proton-${image.type}="${image.id}"]`
) as HTMLElement | null;
};
export const getRemoteImages = ({ messageImages }: PartialMessageState) =>
(messageImages?.images.filter(({ type }) => type === 'remote') || []) as MessageRemoteImage[];
export const getEmbeddedImages = ({ messageImages }: PartialMessageState) =>
(messageImages?.images.filter(({ type }) => type === 'embedded') || []) as MessageEmbeddedImage[];
export const updateImages = (
original: MessageImages | undefined,
flagChanges: Partial<Omit<MessageImages, 'images'>> | undefined,
remoteImages: MessageRemoteImage[] | undefined,
embeddedImages: MessageEmbeddedImage[] | undefined
): MessageImages => {
const messageImages: MessageImages = {
...{
hasRemoteImages: false,
hasEmbeddedImages: false,
showRemoteImages: false,
showEmbeddedImages: false,
trackersStatus: 'not-loaded',
images: [],
},
...(original || {}),
...(flagChanges || {}),
};
const remotes = getRemoteImages({ messageImages });
const embeddeds = getEmbeddedImages({ messageImages });
const images = [
...(remoteImages !== undefined ? remoteImages : remotes),
...(embeddedImages !== undefined ? embeddedImages : embeddeds),
];
return { ...messageImages, images };
};
export const insertImageAnchor = (id: string, type: 'remote' | 'embedded', match: HTMLElement): string => {
const anchor = document.createElement('span');
anchor.classList.add('proton-image-anchor');
anchor.setAttribute(`data-proton-${type}`, id);
match.parentElement?.replaceChild(anchor, match);
return id;
};
export const restoreImages = (inputDocument: Element | undefined, images: MessageImages | undefined) => {
if (!inputDocument || !images) {
return inputDocument;
}
const document = inputDocument.cloneNode(true) as Element;
const { showEmbeddedImages, showRemoteImages } = images;
images.images.forEach((image) => {
const anchor = getAnchor(document, image);
const parent = anchor?.parentElement;
const { original } = image;
if (!anchor || !parent || !original) {
return;
}
if (image.type === 'embedded') {
setEmbeddedAttr(image.cid, image.cloc, original);
original.classList.add('proton-embedded');
if (showEmbeddedImages) {
original.setAttribute('src', image?.url || '');
}
}
if (image.type === 'remote') {
if (showRemoteImages) {
original.setAttribute('src', image?.url || '');
}
}
parent.replaceChild(original, anchor);
});
return document;
};
/**
* Restore all prefixed attributes
*/
export const restoreAllPrefixedAttributes = (content: string) => {
const regex = new RegExp(REGEXP_FIXER, 'g');
return content.replace(regex, (_, $1) => $1.substring(7));
};
/**
* Remove all "normal" HTML attributes that we filled with our values (e.g. images src with proxyfied urls)
*/
export const removeProxyURLAttributes = (content: string) => {
// Using create element will create a DOM element that will not be added to the window's document, but images will be loaded
// Use a DOMParser instead so that images are not loaded.
const document = parseStringToDOM(content);
const foundElements = document.querySelectorAll(getRemoteSelector());
foundElements.forEach((element) => {
ATTRIBUTES_TO_LOAD.forEach((attr) => {
if (element.hasAttribute(attr)) {
const elementProtonURL = element.getAttribute(`proton-${attr}`);
/**
* We want to remove the src only if it's a proxy one before send
* It's a proxy url when
* - The image is a remote, because we don't want to remove any embedded images src
* - When the current element has a src + a proton-src attribute (or other background, url, etc...)
*
* Normally, "originalURL" is defined when we use the proxy. It will contain the image default distant URL
* And "url" will then contain the proxy URL from Proton
*
* So, if the image.url is equal to the one in the src attribute, and the proton-src attribute equals the image original url
* Then it means "src" contains the proxy url and "proton-src" the original URL.
* We can remove the src so that we will use proton-src (which will be transformed to a src later) for sending
* */
if (!elementProtonURL) {
return;
}
element.setAttribute(attr, elementProtonURL);
element.removeAttribute(`proton-${attr}`);
}
});
});
return document.body.innerHTML;
};
/**
* Clean remotes images from the message.
* At this point images might have a proton-src attribute, containing the original URL of the images
* AND a src attribute containing the proxified URL of the image
*
* However, we want to send the original URL, so we need to remove the proxified URL + transform proton-src to src
*/
export const replaceProxyWithOriginalURLAttributes = (message: MessageState, document: Element) => {
let content = getDocumentContent(document);
// First step, remove all src on images that are using Proton proxy urls
content = removeProxyURLAttributes(content);
// Step two, transform all proton-src (and others) attributes to src, since it contains the original URL of the image
// Normally, removing a proxy url should be associated with transforming a proton-src attribute to src at the same time
// However, I'm not 100% we could not have cases where there is a proton-src in the message and no associated proxy url
// In that case the image would be broken on the recipient side, so I prefer doing it separately
content = restoreAllPrefixedAttributes(content);
return content;
};
export const handleDispatchLoadImagesProxy = (
ID: string,
imagesToLoad: MessageRemoteImage[],
authentication: PrivateAuthenticationStore,
dispatch: (action: any) => void
) => {
const dispatchResult = dispatch(loadRemoteProxyFromURL({ ID, imagesToLoad, uid: authentication.getUID() }));
return dispatchResult as any as Promise<LoadRemoteResults[]>;
};
export const handleDispatchLoadFakeImagesProxy = (
ID: string,
imagesToLoad: MessageRemoteImage[],
api: Api,
dispatch: (action: any) => void,
firstLoad?: boolean
) => {
// Make one call per image, it's possible that several images in the message have the same URL.
const uniqueImages = uniqueBy(imagesToLoad, (image) => image.url);
const dispatchResult = dispatch(loadFakeProxy({ ID, imagesToLoad: uniqueImages, api, firstLoad }));
return dispatchResult as any as Promise<LoadRemoteResults[]>;
};
export const handleDispatchLoadRemoteImagesDirect = (
ID: string,
imagesToLoad: MessageRemoteImage[],
dispatch: (action: any) => void
) => {
const dispatchResult = dispatch(loadRemoteDirectFromURL({ ID, imagesToLoad }));
return dispatchResult as any as Promise<LoadRemoteResults[]>;
};
| 3,884
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageKeys.ts
|
import { CryptoProxy, WorkerDecryptionResult } from '@proton/crypto';
import { arrayToBinaryString } from '@proton/crypto/lib/utils';
import { splitExtension } from '@proton/shared/lib/helpers/file';
import { Api } from '@proton/shared/lib/interfaces';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { getParsedAutocryptHeader } from '@proton/shared/lib/mail/autocrypt';
import isTruthy from '@proton/utils/isTruthy';
import { LARGE_KEY_SIZE } from '../../constants';
import { MessageKeys } from '../../logic/messages/messagesTypes';
import { get } from '../attachment/attachmentLoader';
/**
* Look through a message attachments if there are keys
*/
export const extractKeysFromAttachments = async (
attachments: Attachment[] | undefined = [],
messageKeys: MessageKeys,
getAttachment: (ID: string) => WorkerDecryptionResult<Uint8Array> | undefined,
onUpdateAttachment: (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => void,
api: Api,
messageFlags?: number
) => {
const keyAttachments =
attachments.filter(({ Name, Size }) => splitExtension(Name)[1] === 'asc' && (Size || 0) < LARGE_KEY_SIZE) || [];
return (
await Promise.all(
keyAttachments.map(async (attachment) => {
try {
const { data } = await get(
attachment,
undefined,
messageKeys,
api,
getAttachment,
onUpdateAttachment,
messageFlags
);
const key = await CryptoProxy.importPublicKey({ armoredKey: arrayToBinaryString(data) });
return key;
} catch (e: any) {
// Nothing
return null;
}
})
)
).filter(isTruthy);
};
/**
* Look in a message headers if there is a key in an autocrypt header
* Autocrypt is an old norm almost deprecated
* There is no plan to have a full support of autocrypt, just take advantage of the header opportunistically if present
*/
export const extractKeysFromAutocrypt = async (
parsedHeaders: { [key: string]: string | string[] | undefined } | undefined,
senderAddress: string
) => {
if (!parsedHeaders?.Autocrypt) {
return [];
}
const autocrypt = Array.isArray(parsedHeaders.Autocrypt) ? parsedHeaders.Autocrypt : [parsedHeaders.Autocrypt];
return (
await Promise.all(
autocrypt.map(async (header) => {
try {
const result = getParsedAutocryptHeader(header, senderAddress);
if (!result) {
return;
}
const key = await CryptoProxy.importPublicKey({ binaryKey: result.keydata });
return key;
} catch (e: any) {
// not encoded correctly
return null;
}
})
)
).filter(isTruthy);
};
| 3,885
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageRead.ts
|
import { getMessage } from '@proton/shared/lib/api/messages';
import { Api } from '@proton/shared/lib/interfaces';
import { GetMessageResponse } from '@proton/shared/lib/interfaces/mail/Message';
import { MessageState, MessageStateWithDataFull } from '../../logic/messages/messagesTypes';
export const loadMessage = async (message: MessageState, api: Api): Promise<MessageStateWithDataFull> => {
const messageID = message.data?.ID;
/**
* If the Body is already there, no need to send a request
* messageID is type guard
*/
if (!message.data?.Body && messageID) {
const { Message } = await api<GetMessageResponse>(getMessage(messageID));
if (Message) {
return { ...message, data: Message };
}
}
return message as MessageStateWithDataFull;
};
| 3,886
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageRecipients.test.ts
|
import { INCOMING_DEFAULTS_LOCATION } from '@proton/shared/lib/constants';
import { Address, IncomingDefault, SimpleMap } from '@proton/shared/lib/interfaces';
import { Recipient } from '@proton/shared/lib/interfaces/Address';
import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants';
import { fromFields, recipients } from '../../components/composer/quickReply/tests/QuickReply.test.data';
import { MESSAGE_ACTIONS } from '../../constants';
import { MessageState } from '../../logic/messages/messagesTypes';
import { Conversation } from '../../models/conversation';
import { Element } from '../../models/element';
import {
findSender,
getNumParticipants,
getRecipientGroupLabel,
getRecipientLabel,
getRecipients,
getReplyRecipientListAsString,
getSendersToBlock,
recipientsToRecipientOrGroup,
} from './messageRecipients';
const recipient1: Recipient = { Name: '', Address: 'address1' };
const recipient2: Recipient = { Name: 'recipient2', Address: 'address2' };
const recipient3: Recipient = { Name: 'recipient3', Address: 'address3', Group: 'Group1' };
const recipient4: Recipient = { Name: 'recipient4', Address: 'address4', Group: 'Group1' };
const recipient5: Recipient = { Name: 'recipient5', Address: 'address5', Group: 'Group2' };
const group1 = { ID: 'GroupID1', Name: 'GroupName1', Path: 'Group1' } as ContactGroup;
const groupMap = { [group1.Path]: group1 };
describe('messageRecipients', () => {
describe('findSender', () => {
it('should return empty for no message no addresses', () => {
const result = findSender();
expect(result).toBe(undefined);
});
it('should return empty for no addresses', () => {
const result = findSender([], { AddressID: '1' } as Message);
expect(result).toBe(undefined);
});
it('should return empty if no match', () => {
const result = findSender([{ Status: 2 }] as Address[], { AddressID: '1' } as Message);
expect(result).toBe(undefined);
});
it('should return first if addresses valid but no match', () => {
const first = { Status: 1, Order: 1, ID: '2' };
const result = findSender(
[{ Status: 2 }, first, { Status: 1, Order: 2, ID: '3' }] as Address[],
{
AddressID: '1',
} as Message
);
expect(result).toBe(first);
});
it('should return first if addresses order valid but no match', () => {
const first = { Status: 1, Order: 1, ID: '2' };
const result = findSender(
[{ Status: 2, Order: 0, ID: '1' }, first, { Status: 1, Order: 2, ID: '3' }] as Address[],
{
AddressID: '1',
} as Message
);
expect(result).toEqual(first);
});
it('should return the match over order', () => {
const match = { Status: 1, Order: 2, ID: '1' };
const result = findSender(
[{ Status: 2 }, match, { Status: 1, Order: 1, ID: '2' }] as Address[],
{
AddressID: '1',
} as Message
);
expect(result).toBe(match);
});
});
describe('recipientsToRecipientOrGroup', () => {
it('should return recipients if no group', () => {
const result = recipientsToRecipientOrGroup([recipient1, recipient2], {});
expect(result).toEqual([{ recipient: recipient1 }, { recipient: recipient2 }]);
});
it('should merge recipients from a group', () => {
const result = recipientsToRecipientOrGroup([recipient3, recipient4], groupMap);
expect(result).toEqual([{ group: { group: group1, recipients: [recipient3, recipient4] } }]);
});
it('should split recipients from group and those not', () => {
const result = recipientsToRecipientOrGroup([recipient2, recipient3], groupMap);
expect(result).toEqual([{ recipient: recipient2 }, { group: { group: group1, recipients: [recipient3] } }]);
});
it('should give up group from recipient if not in group list', () => {
const result = recipientsToRecipientOrGroup([recipient5], groupMap);
expect(result).toEqual([{ recipient: recipient5 }]);
});
it('should return recipients if we do not want to display groups', () => {
const result = recipientsToRecipientOrGroup([recipient3, recipient4, recipient5], groupMap, true);
expect(result).toEqual([{ recipient: recipient3 }, { recipient: recipient4 }, { recipient: recipient5 }]);
});
});
describe('getRecipientOrGroupLabel', () => {
it('should return recipient address if it has no name', () => {
const result = getRecipientLabel(recipient1, {});
expect(result).toEqual('address1');
});
it('should return recipient name if it exists', () => {
const result = getRecipientLabel(recipient2, {});
expect(result).toEqual('recipient2');
});
it('should return group label', () => {
const result = getRecipientGroupLabel({ group: group1, recipients: [] }, 0);
expect(result).toEqual('GroupName1 (0/0 members)');
});
it('should compute group size with contact list', () => {
const result = getRecipientGroupLabel({ group: group1, recipients: [recipient3, recipient4] }, 8);
expect(result).toEqual('GroupName1 (2/8 members)');
});
});
describe('getNumParticipants', () => {
it('should not count same participant', () => {
const sender: Recipient = { Name: 'Panda', Address: 'panda@pm.me' };
const recipient1: Recipient = { Name: 'Panda', Address: 'panda@pm.me' };
const recipient2: Recipient = { Name: 'Panda', Address: 'p.an.da@pm.me' };
const recipient3: Recipient = { Name: 'Panda', Address: 'panda+panda@pm.me' };
const conversation: Element = {
ID: 'conversationID',
Senders: [sender],
Recipients: [recipient1, recipient2, recipient3],
};
const result = getNumParticipants(conversation);
expect(result).toEqual(1);
});
});
describe('getSendersToBlock', () => {
// Message not present in SPAM or ALLOW or BLOCK list
const toCreate = 'toCreate@protonmail.com';
// Message from someone already in the SPAM list
const toUpdateSpam = 'toUpdateSpam@protonmail.com';
// Message from someone already in the ALLOW list
const toUpdateInbox = 'toUpdateInbox@protonmail.com';
// Message from someone already in the BLOCK list
const alreadyBlocked = 'alreadyBlocked@protonmail.com';
// Message sent to myself
const me = 'me@protonmail.com';
// Message sent to myself from secondary address
const me2 = 'me2@protonmail.com';
const incomingDefaultsAddresses = [
{ ID: '1', Email: toUpdateInbox, Location: INCOMING_DEFAULTS_LOCATION.INBOX } as IncomingDefault,
{ ID: '2', Email: toUpdateSpam, Location: INCOMING_DEFAULTS_LOCATION.SPAM } as IncomingDefault,
{ ID: '3', Email: alreadyBlocked, Location: INCOMING_DEFAULTS_LOCATION.BLOCKED } as IncomingDefault,
] as IncomingDefault[];
const addresses = [{ Email: me } as Address, { Email: me2 } as Address] as Address[];
const expectedSenders = [
{ Address: toCreate } as Recipient,
{ Address: toUpdateSpam } as Recipient,
{ Address: toUpdateInbox } as Recipient,
];
it('should return expected senders to block from messages', () => {
const elements = [
{ Sender: { Address: toCreate } as Recipient, ConversationID: '1' } as Message,
{ Sender: { Address: toUpdateSpam } as Recipient, ConversationID: '2' } as Message,
{ Sender: { Address: toUpdateInbox } as Recipient, ConversationID: '3' } as Message,
// Put one 2 times to check that it will not be called 2 times
{ Sender: { Address: toUpdateInbox } as Recipient, ConversationID: '4' } as Message,
{ Sender: { Address: alreadyBlocked } as Recipient, ConversationID: '5' } as Message,
{ Sender: { Address: me } as Recipient, ConversationID: '6' } as Message,
{ Sender: { Address: me2 } as Recipient, ConversationID: '7' } as Message,
] as Element[];
const senders = getSendersToBlock(elements, incomingDefaultsAddresses, addresses);
expect(senders).toEqual(expectedSenders);
});
it('should return expected senders to block from conversation', () => {
const elements = [
{ Senders: [{ Address: toCreate } as Recipient] } as Conversation,
{ Senders: [{ Address: toUpdateSpam } as Recipient] } as Conversation,
{ Senders: [{ Address: toUpdateInbox } as Recipient] } as Conversation,
// Put one 2 times to check that it will not be called 2 times
{ Senders: [{ Address: toUpdateInbox } as Recipient] } as Conversation,
{ Senders: [{ Address: alreadyBlocked } as Recipient] } as Conversation,
{ Senders: [{ Address: me } as Recipient] } as Conversation,
{ Senders: [{ Address: me2 } as Recipient] } as Conversation,
] as Element[];
const senders = getSendersToBlock(elements, incomingDefaultsAddresses, addresses);
expect(senders).toEqual(expectedSenders);
});
});
describe('getRecipients', () => {
it.each`
replyType | isSentMessage
${MESSAGE_ACTIONS.REPLY} | ${true}
${MESSAGE_ACTIONS.REPLY} | ${false}
${MESSAGE_ACTIONS.REPLY_ALL} | ${true}
${MESSAGE_ACTIONS.REPLY_ALL} | ${false}
`('should give the expected recipients', ({ replyType, isSentMessage }) => {
const referenceMessage = {
data: {
ReplyTos: isSentMessage ? [recipients.meRecipient] : [recipients.fromRecipient],
ToList: isSentMessage ? [recipients.toRecipient] : [recipients.meRecipient, recipients.toRecipient],
CCList: [recipients.ccRecipient],
BCCList: [recipients.bccRecipient],
Flags: isSentMessage ? MESSAGE_FLAGS.FLAG_SENT : MESSAGE_FLAGS.FLAG_RECEIVED,
} as Partial<Message>,
} as MessageState;
const addresses = [{ DisplayName: fromFields.meName, Email: fromFields.meAddress } as Address];
const { ToList, CCList, BCCList } = getRecipients(referenceMessage, replyType, addresses);
if (replyType === MESSAGE_ACTIONS.REPLY) {
if (isSentMessage) {
expect(ToList).toEqual([recipients.toRecipient]);
expect(CCList).toEqual([]);
expect(BCCList).toEqual([]);
} else {
expect(ToList).toEqual([recipients.fromRecipient]);
expect(CCList).toEqual([]);
expect(BCCList).toEqual([]);
}
} else {
if (isSentMessage) {
expect(ToList).toEqual([recipients.toRecipient]);
expect(CCList).toEqual([recipients.ccRecipient]);
expect(BCCList).toEqual([recipients.bccRecipient]);
} else {
expect(ToList).toEqual([recipients.fromRecipient]);
expect(CCList).toEqual([recipients.toRecipient, recipients.ccRecipient]);
expect(BCCList).toEqual([]);
}
}
});
});
describe('getReplyRecipientListAsString', () => {
it.each`
replyType | isSentMessage
${MESSAGE_ACTIONS.REPLY} | ${true}
${MESSAGE_ACTIONS.REPLY} | ${false}
${MESSAGE_ACTIONS.REPLY_ALL} | ${true}
${MESSAGE_ACTIONS.REPLY_ALL} | ${false}
`('should give the expected recipient string', ({ replyType, isSentMessage }) => {
const referenceMessage = {
data: {
ReplyTos: isSentMessage ? [recipients.meRecipient] : [recipients.fromRecipient],
ToList: isSentMessage ? [recipients.toRecipient] : [recipients.meRecipient, recipients.toRecipient],
CCList: [recipients.ccRecipient],
BCCList: [recipients.bccRecipient],
Flags: isSentMessage ? MESSAGE_FLAGS.FLAG_SENT : MESSAGE_FLAGS.FLAG_RECEIVED,
} as Partial<Message>,
} as MessageState;
const addresses = [{ DisplayName: fromFields.meName, Email: fromFields.meAddress } as Address];
const fromCustomName = 'From contact name';
const contactsMap: SimpleMap<ContactEmail> = {
'from@protonmail.com': {
Email: fromFields.fromAddress,
Name: fromCustomName,
} as ContactEmail,
};
const recipientsString = getReplyRecipientListAsString(referenceMessage, replyType, addresses, contactsMap);
if (replyType === MESSAGE_ACTIONS.REPLY) {
if (isSentMessage) {
expect(recipientsString).toEqual('To');
} else {
expect(recipientsString).toEqual(`${fromCustomName}`);
}
} else {
if (isSentMessage) {
expect(recipientsString).toEqual('To, CC, BCC');
} else {
expect(recipientsString).toEqual(`${fromCustomName}, To, CC`);
}
}
});
});
});
| 3,887
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageRecipients.ts
|
import { c, msgid } from 'ttag';
import { canonicalizeEmail, canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email';
import { isBlockedIncomingDefaultAddress } from '@proton/shared/lib/helpers/incomingDefaults';
import { Address, IncomingDefault, Recipient } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { isSent, isSentAndReceived } from '@proton/shared/lib/mail/messages';
import isTruthy from '@proton/utils/isTruthy';
import unique from '@proton/utils/unique';
import { MESSAGE_ACTIONS } from '../../constants';
import { ContactGroupsMap, ContactsMap } from '../../logic/contacts/contactsTypes';
import { MessageState } from '../../logic/messages/messagesTypes';
import { RecipientGroup, RecipientOrGroup } from '../../models/address';
import { Conversation } from '../../models/conversation';
import { Element } from '../../models/element';
import { isSelfAddress } from '../addresses';
import { isMessage, isConversation as testIsConversation } from '../elements';
/**
* Return the matching ContactEmail in the map taking care of email normalization
*/
export const getContactEmail = (contactsMap: ContactsMap, email: string | undefined) => {
const normalizedEmail = canonicalizeEmail(email || '');
return contactsMap[normalizedEmail];
};
export const recipientsWithoutGroup = (recipients: Recipient[], groupPath?: string) =>
recipients.filter((recipient) => recipient.Group !== groupPath);
export const getRecipientLabelDetailed = (recipient: Recipient, contactsMap: ContactsMap) => {
const { Name, Address } = recipient || {};
const contact = getContactEmail(contactsMap, Address);
if (contact?.Name?.trim()) {
return contact.Name;
}
if (Name) {
return Name;
}
return Address;
};
export const getRecipientLabel = (recipient: Recipient, contactsMap: ContactsMap) => {
const { Name, Address } = recipient || {};
const contact = getContactEmail(contactsMap, Address);
if (contact?.Name?.trim()) {
return contact.Name;
}
if (!Name || Name === Address) {
return Address;
}
if (Name) {
return Name;
}
return '';
};
export const getRecipientGroupLabel = (recipientGroup?: RecipientGroup, contactsInGroup = 0, isShortName = false) => {
const count = recipientGroup?.recipients.length;
if (isShortName) {
if (count === contactsInGroup) {
return `${recipientGroup?.group?.Name} (${contactsInGroup})`;
}
return `${recipientGroup?.group?.Name} (${count}/${contactsInGroup})`;
}
// Copy variables to give explicit naming in the translation string
const contactGroupName = recipientGroup?.group?.Name;
const numberOfSelectedContacts = count;
const numberOfContactsInGroup = contactsInGroup;
// translator: The final string looks like "Work (2/10 members)"
return c('Info').ngettext(
msgid`${contactGroupName} (${numberOfSelectedContacts}/${numberOfContactsInGroup} member)`,
`${contactGroupName} (${numberOfSelectedContacts}/${numberOfContactsInGroup} members)`,
numberOfContactsInGroup
);
};
export const recipientsToRecipientOrGroup = (
recipients: Recipient[],
contactGroupsMap?: ContactGroupsMap,
alwaysShowRecipients: boolean = false
) =>
recipients.reduce<RecipientOrGroup[]>((acc, value) => {
if (value.Group && !alwaysShowRecipients) {
const existingGroup = acc.find((recipientsOrGroup) => recipientsOrGroup.group?.group?.Path === value.Group);
if (existingGroup) {
existingGroup.group?.recipients.push(value);
} else {
if (contactGroupsMap) {
const group = contactGroupsMap[value.Group];
if (group) {
acc.push({ group: { group, recipients: [value] } });
} else {
acc.push({ recipient: value });
}
} else {
acc.push({ recipient: value });
}
}
} else {
// Show recipient if no group is set or when we force the recipient display (e.g. print modal)
acc.push({ recipient: value });
}
return acc;
}, []);
export const recipientOrGroupToRecipients = (recipientsOrGroups: RecipientOrGroup[]) =>
recipientsOrGroups
.map((recipientOrGroup) =>
recipientOrGroup.recipient
? recipientOrGroup.recipient
: (recipientOrGroup.group?.recipients as Recipient[])
)
.flat();
export const getRecipientOrGroupKey = (recipientOrGroup: RecipientOrGroup) =>
recipientOrGroup.recipient ? recipientOrGroup.recipient.Address : recipientOrGroup.group?.group?.ID;
export const matchRecipientOrGroup = (rog1: RecipientOrGroup, rog2: RecipientOrGroup) =>
getRecipientOrGroupKey(rog1) === getRecipientOrGroupKey(rog2);
/**
* Find the current sender for a message
*/
export const findSender = (
addresses: Address[] = [],
message?: Partial<Message>,
ableToSend = false
): Address | undefined => {
const enabledAddresses = addresses
.filter((address) => address.Status === 1)
.filter((address) => (ableToSend ? address.Send === 1 : true))
.sort((a1, a2) => (a1.Order || 0) - (a2.Order || 0));
if (message?.AddressID) {
const originalAddress = enabledAddresses.find((address) => address.ID === message?.AddressID);
if (originalAddress) {
return originalAddress;
}
}
return enabledAddresses[0];
};
export const getNumParticipants = (element: Element) => {
let recipients: Recipient[];
if (isMessage(element)) {
const { ToList = [], CCList = [], BCCList = [], Sender = {} } = element as Message;
recipients = [...ToList, ...CCList, ...BCCList, Sender as Recipient];
} else {
const { Senders = [], Recipients = [] } = element as Conversation;
recipients = [...Recipients, ...Senders];
}
return unique(recipients.map(({ Address }: Recipient) => canonicalizeInternalEmail(Address))).length;
};
export const getSendersToBlock = (
elements: Element[],
incomingDefaultsAddresses: IncomingDefault[],
addresses: Address[]
) => {
const allSenders: Recipient[] = [];
// Get all senders without duplicates
elements.forEach((el) => {
const isConversation = testIsConversation(el);
if (isConversation) {
(el as Conversation)?.Senders?.map((sender) => {
if (sender && allSenders.every((s) => s.Address !== sender.Address)) {
allSenders.push(sender);
}
});
} else {
const sender = (el as Message).Sender;
if (sender && allSenders.every((s) => s.Address !== sender.Address)) {
allSenders.push((el as Message).Sender);
}
}
}, []);
// Remove self and blocked addresses
return allSenders
.filter((sender) => {
if (sender) {
const isSenderBlocked = isBlockedIncomingDefaultAddress(incomingDefaultsAddresses, sender.Address);
const isSenderSelfAddress = isSelfAddress(sender.Address, addresses);
return !isSenderBlocked && !isSenderSelfAddress;
}
return;
})
.filter(isTruthy);
};
export const getRecipients = (referenceMessage: MessageState, action: MESSAGE_ACTIONS, addresses: Address[]) => {
const { data } = referenceMessage;
const toList = data?.ToList || [];
const replyTos = data?.ReplyTos || [];
const ccList = data?.CCList || [];
const bccList = data?.BCCList || [];
let returnToList: Recipient[] = [];
let returnCCList: Recipient[] = [];
let returnBCCList: Recipient[] = [];
if (action === MESSAGE_ACTIONS.REPLY) {
if (isSent(referenceMessage.data) || isSentAndReceived(referenceMessage.data)) {
returnToList = [...toList];
} else {
returnToList = [...replyTos];
}
} else {
if (isSent(referenceMessage.data) || isSentAndReceived(referenceMessage.data)) {
returnToList = [...toList];
returnCCList = [...ccList];
returnBCCList = [...bccList];
} else {
// Remove user address in CCList and ToList
const userAddresses = addresses.map(({ Email = '' }) => canonicalizeInternalEmail(Email));
const CCListAll: Recipient[] = unique([...(toList || []), ...(ccList || [])]);
const CCList = CCListAll.filter(
({ Address = '' }) => !userAddresses.includes(canonicalizeInternalEmail(Address))
);
returnToList = [...replyTos];
returnCCList = [...CCList];
}
}
return { ToList: returnToList, CCList: returnCCList, BCCList: returnBCCList };
};
export const getReplyRecipientListAsString = (
referenceMessage: MessageState,
action: MESSAGE_ACTIONS,
addresses: Address[],
contactsMap: ContactsMap
) => {
const getContactLabel = (recipientList: Recipient[]) => {
return recipientList.map((recipient) => getRecipientLabel(recipient, contactsMap));
};
const { ToList, CCList, BCCList } = getRecipients(referenceMessage, action, addresses);
const recipientList = getContactLabel([...ToList, ...CCList, ...BCCList]);
let recipientAsString = '';
recipientList.forEach((recipient, index) => {
const isLastElement = index === recipientList.length - 1;
recipientAsString = isLastElement ? `${recipientAsString}${recipient}` : `${recipientAsString}${recipient}, `;
});
return recipientAsString;
};
| 3,888
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageRemotes.test.ts
|
import { MessageRemoteImage } from '../../logic/messages/messagesTypes';
import { createDocument } from '../test/message';
import { loadBackgroundImages, loadImages } from './messageRemotes';
describe('messageRemote', () => {
describe('loadImages', () => {
const imageURL = 'ImageURL';
const originalURL = 'originalURL';
const backgroundContent = `<div>
<table>
<tbody>
<tr>
<td proton-background='${originalURL}'>Element1</td>
</tr>
</tbody>
</table>
</div>`;
const backgroundExpectedContent = `<div>
<table>
<tbody>
<tr>
<td proton-background='${originalURL}' background='${imageURL}'>Element1</td>
</tr>
</tbody>
</table>
</div>`;
const posterContent = `<div>
<video proton-poster='${originalURL}'>
<source src="" type="video/mp4">
</video>
</div>`;
const posterExpectedContent = `<div>
<video proton-poster='${originalURL}' poster='${imageURL}'>
<source src="" type="video/mp4">
</video>
</div>`;
const xlinkhrefContent = `<div>
<svg width="90" height="90">
<image proton-xlink:href='${originalURL}'/>
</svg>
</div>`;
const xlinkhrefExpectedContent = `<div>
<svg width="90" height="90">
<image proton-xlink:href='${originalURL}' xlink:href='${imageURL}'/>
</svg>
</div>`;
const srcsetContent = `<div>
<picture>
<source media="(min-width:650px)" proton-srcset='${originalURL}' >
<img src='${imageURL}' >
</picture>
</div>`;
const srcsetExpectedContent = `<div>
<picture>
<source media="(min-width:650px)" proton-srcset='${originalURL}' >
<img src='${imageURL}' >
</picture>
</div>`;
it.each`
content | expectedContent
${backgroundContent} | ${backgroundExpectedContent}
${posterContent} | ${posterExpectedContent}
${xlinkhrefContent} | ${xlinkhrefExpectedContent}
`('should load elements other than images', async ({ content, expectedContent }) => {
const messageDocument = createDocument(content);
const remoteImages = [
{
type: 'remote',
url: imageURL,
originalURL,
id: 'remote-0',
tracker: undefined,
status: 'loaded',
},
] as MessageRemoteImage[];
loadImages(remoteImages, messageDocument);
const expectedDocument = createDocument(expectedContent);
expect(messageDocument.innerHTML).toEqual(expectedDocument.innerHTML);
});
it('should not load srcset attribute', () => {
const messageDocument = createDocument(srcsetContent);
const remoteImages = [
{
type: 'remote',
url: imageURL,
originalURL,
id: 'remote-0',
tracker: undefined,
status: 'loaded',
},
] as MessageRemoteImage[];
loadImages(remoteImages, messageDocument);
const expectedDocument = createDocument(srcsetExpectedContent);
expect(messageDocument.innerHTML).toEqual(expectedDocument.innerHTML);
});
});
describe('loadBackgroundImages', () => {
const imageURL = 'http://test.fr/img.jpg';
const content = `<div style="background: proton-url(${imageURL})">Element1</div>`;
const expectedContent = `<div style="background: url(${imageURL})">Element1</div>`;
it('should load elements other than images', async () => {
const messageDocument = createDocument(content);
const expectedDocument = createDocument(expectedContent);
const remoteImages = [
{
type: 'remote',
url: imageURL,
originalURL: imageURL,
id: 'remote-0',
tracker: undefined,
status: 'loaded',
},
] as MessageRemoteImage[];
loadBackgroundImages({ images: remoteImages, document: messageDocument });
expect(messageDocument.innerHTML).toEqual(expectedDocument.innerHTML);
});
});
});
| 3,889
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageRemotes.ts
|
import { wait } from '@proton/shared/lib/helpers/promise';
import { MessageImage, MessageRemoteImage } from '../../logic/messages/messagesTypes';
import { getRemoteSelector } from './messageImages';
export const ATTRIBUTES_TO_FIND = ['url', 'xlink:href', 'src', 'srcset', 'svg', 'background', 'poster'];
export const ATTRIBUTES_TO_LOAD = ['url', 'xlink:href', 'src', 'svg', 'background', 'poster'];
export const urlCreator = () => window.URL || window.webkitURL;
export const removeProtonPrefix = (match: HTMLElement) => {
ATTRIBUTES_TO_LOAD.forEach((attr) => {
const protonAttr = `proton-${attr}`;
if (match.hasAttribute(protonAttr)) {
match.setAttribute(attr, match.getAttribute(protonAttr) as string);
match.removeAttribute(protonAttr);
}
});
};
interface LoadBackgroundImagesProps {
images?: MessageRemoteImage[];
document?: Element;
}
export const loadBackgroundImages = ({ images, document }: LoadBackgroundImagesProps) => {
if (!document || !images) {
return;
}
const elementWithStyleTag = document?.querySelectorAll('[style]');
elementWithStyleTag?.forEach((element) => {
const styleAttribute = element.getAttribute('style');
if (styleAttribute && styleAttribute.includes('proton-url')) {
const rawUrlMatch = styleAttribute.match(/proton-url\((.*?)\)/)?.[1];
const cleanUrlMatch = rawUrlMatch?.replace(/('|")/g, '');
// Find the corresponding image to get its url (same url if loading without proxy, or blob if loading through proxy)
const preLoadedImage = images.find((img) => cleanUrlMatch === img.originalURL);
// Set attribute with the right URL (normal or blob depending on the setting)
if (preLoadedImage && preLoadedImage.url && rawUrlMatch) {
element.setAttribute(
'style',
styleAttribute.replace(rawUrlMatch, preLoadedImage.url).replace('proton-url', 'url')
);
}
}
});
};
/**
* Search for proton attributes in the document and replace them with their normal attributes
* => e.g. proton-src becomes src so that we can load an image
*
* It should work on img tags and other elements from ATTRIBUTE_TO_LOAD (e.g. url, background, etc...)
*/
export const loadImages = (images: MessageRemoteImage[], messageDocument?: Element) => {
const selector = getRemoteSelector(true);
// Get all elements in the mail which have a proton attribute
const foundElements = messageDocument ? messageDocument.querySelectorAll(selector) : [];
foundElements.forEach((element) => {
ATTRIBUTES_TO_LOAD.forEach((attr) => {
const protonAttr = `proton-${attr}`;
if (element.hasAttribute(protonAttr)) {
const elementValue = element.getAttribute(protonAttr) as string;
// Find the corresponding image to get its url (same url if loading without proxy, or blob if loading through proxy)
// Check its originalUrl because url field can be a blob at this point
images.forEach((el) => {
if (elementValue === el.originalURL && el.url) {
// Set attribute with the right URL (normal or blob depending on the setting)
element.setAttribute(attr, el.url);
}
});
}
});
});
};
// Error Code 2902 means proxy failed to load the image
const imageFailedWithProxy = (image: MessageRemoteImage) => (image.error as any)?.data?.Code === 2902 && !image.tracker;
export const hasToSkipProxy = (images: MessageImage[] = []) => {
const remoteImages = images.filter((image) => image.type === 'remote') as MessageRemoteImage[];
return remoteImages.every((image) => image.status === 'loaded') && remoteImages.some(imageFailedWithProxy);
};
export const loadRemoteImages = async (
useProxy: boolean,
images: MessageRemoteImage[],
onLoadRemoteImagesDirect: (imagesToLoad: MessageRemoteImage[]) => void,
onLoadRemoteImagesProxy?: (imagesToLoad: MessageRemoteImage[]) => void
) => {
// Not really happy with this hack but we need to "wait" that the message transform process is finished
// And update the message cache before updating image statuses
await wait(0);
const imagesToLoad = images.filter((image) => image.status === 'not-loaded');
if (useProxy) {
return onLoadRemoteImagesProxy?.(imagesToLoad);
}
return onLoadRemoteImagesDirect(imagesToLoad);
};
export const loadFakeImages = async (
images: MessageRemoteImage[],
onLoadFakeImagesProxy: (imagesToLoad: MessageRemoteImage[], firstLoad?: boolean) => void,
firstLoad = false
) => {
// Not really happy with this hack but we need to "wait" that the message transform process is finished
// And update the message cache before updating image statuses
await wait(0);
return onLoadFakeImagesProxy(images, firstLoad);
};
export const loadSkipProxyImages = async (
images: MessageRemoteImage[],
onLoadRemoteImagesDirect: (imagesToLoad: MessageRemoteImage[]) => void
) => {
// Not really happy with this hack but we need to "wait" that the message transform process is finished
// And update the message cache before updating image statuses
await wait(0);
const imagesToLoad = images.filter(imageFailedWithProxy);
return onLoadRemoteImagesDirect(imagesToLoad);
};
| 3,890
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageSignature.test.ts
|
import { MailSettings, UserSettings } from '@proton/shared/lib/interfaces';
import { PM_SIGNATURE as PM_SIGNATURE_ENUM } from '@proton/shared/lib/mail/mailSettings';
import { getProtonMailSignature } from '@proton/shared/lib/mail/signature';
import { message } from '@proton/shared/lib/sanitize';
import { MESSAGE_ACTIONS } from '../../constants';
import {
CLASSNAME_SIGNATURE_CONTAINER,
CLASSNAME_SIGNATURE_EMPTY,
CLASSNAME_SIGNATURE_USER,
insertSignature,
} from './messageSignature';
const content = '<p>test</p>';
const signature = `
<strong>>signature</strong>`;
const mailSettings = { PMSignature: PM_SIGNATURE_ENUM.DISABLED } as MailSettings;
const userSettings = {} as UserSettings;
const PM_SIGNATURE = getProtonMailSignature();
describe('signature', () => {
afterEach(() => {
jest.clearAllMocks();
});
describe('insertSignature', () => {
describe('rules', () => {
it('should remove line breaks', () => {
const result = insertSignature(
content,
signature,
MESSAGE_ACTIONS.NEW,
mailSettings,
userSettings,
undefined,
false
);
expect(result).toContain('<br><strong>');
});
it('should try to clean the signature', () => {
const result = insertSignature(
content,
signature,
MESSAGE_ACTIONS.NEW,
mailSettings,
userSettings,
undefined,
false
);
expect(result).toContain('>');
});
it('should add empty line before the signature', () => {
const result = insertSignature(
content,
'',
MESSAGE_ACTIONS.NEW,
mailSettings,
userSettings,
undefined,
false
);
expect(result).toMatch(new RegExp(`<div><br></div>\\s*<div class="${CLASSNAME_SIGNATURE_CONTAINER}`));
});
it('should add different number of empty lines depending on the action', () => {
let result = insertSignature(
content,
'',
MESSAGE_ACTIONS.NEW,
mailSettings,
userSettings,
undefined,
false
);
expect((result.match(/<div><br><\/div>/g) || []).length).toBe(1);
result = insertSignature(
content,
'',
MESSAGE_ACTIONS.REPLY,
mailSettings,
userSettings,
undefined,
false
);
expect((result.match(/<div><br><\/div>/g) || []).length).toBe(2);
result = insertSignature(
content,
'',
MESSAGE_ACTIONS.REPLY,
{ ...mailSettings, PMSignature: PM_SIGNATURE_ENUM.ENABLED },
userSettings,
undefined,
false
);
expect((result.match(/<div><br><\/div>/g) || []).length).toBe(3);
result = insertSignature(
content,
signature,
MESSAGE_ACTIONS.REPLY,
mailSettings,
userSettings,
undefined,
false
);
expect((result.match(/<div><br><\/div>/g) || []).length).toBe(3);
result = insertSignature(
content,
signature,
MESSAGE_ACTIONS.REPLY,
{ ...mailSettings, PMSignature: PM_SIGNATURE_ENUM.ENABLED },
userSettings,
undefined,
false
);
expect((result.match(/<div><br><\/div>/g) || []).length).toBe(4);
});
it('should append PM signature depending mailsettings', () => {
let result = insertSignature(content, '', MESSAGE_ACTIONS.NEW, mailSettings, {}, undefined, false);
expect(result).not.toContain(PM_SIGNATURE);
result = insertSignature(
content,
'',
MESSAGE_ACTIONS.NEW,
{ ...mailSettings, PMSignature: PM_SIGNATURE_ENUM.ENABLED },
userSettings,
undefined,
false
);
const sanitizedPmSignature = message(PM_SIGNATURE);
expect(result).toContain(sanitizedPmSignature);
let messagePosition = result.indexOf(content);
let signaturePosition = result.indexOf(sanitizedPmSignature);
expect(messagePosition).toBeGreaterThan(signaturePosition);
result = insertSignature(
content,
'',
MESSAGE_ACTIONS.NEW,
{ ...mailSettings, PMSignature: PM_SIGNATURE_ENUM.ENABLED },
userSettings,
undefined,
true
);
messagePosition = result.indexOf(content);
signaturePosition = result.indexOf(sanitizedPmSignature);
expect(messagePosition).toBeLessThan(signaturePosition);
});
it('should append user signature if exists', () => {
let result = insertSignature(
content,
'',
MESSAGE_ACTIONS.NEW,
mailSettings,
userSettings,
undefined,
false
);
expect(result).toContain(`${CLASSNAME_SIGNATURE_USER} ${CLASSNAME_SIGNATURE_EMPTY}`);
result = insertSignature(
content,
signature,
MESSAGE_ACTIONS.NEW,
mailSettings,
userSettings,
undefined,
false
);
expect(result).toContain('signature');
let messagePosition = result.indexOf(content);
let signaturePosition = result.indexOf(signature);
expect(messagePosition).toBeGreaterThan(signaturePosition);
result = insertSignature(
content,
signature,
MESSAGE_ACTIONS.NEW,
mailSettings,
userSettings,
undefined,
true
);
messagePosition = result.indexOf(content);
signaturePosition = result.indexOf('signature');
expect(messagePosition).toBeLessThan(signaturePosition);
});
});
describe('snapshots', () => {
const protonSignatures = [false, true];
const userSignatures = [false, true];
const actions = [
MESSAGE_ACTIONS.NEW,
MESSAGE_ACTIONS.REPLY,
MESSAGE_ACTIONS.REPLY_ALL,
MESSAGE_ACTIONS.FORWARD,
];
const isAfters = [false, true];
protonSignatures.forEach((protonSignature) => {
userSignatures.forEach((userSignature) => {
actions.forEach((action) => {
isAfters.forEach((isAfter) => {
const label = `should match with protonSignature ${protonSignature}, userSignature ${userSignature}, action ${action}, isAfter ${isAfter}`;
it(label, () => {
const result = insertSignature(
content,
userSignature ? signature : '',
action,
{
PMSignature: protonSignature
? PM_SIGNATURE_ENUM.ENABLED
: PM_SIGNATURE_ENUM.DISABLED,
} as MailSettings,
userSettings,
undefined,
isAfter
);
expect(result).toMatchSnapshot();
});
});
});
});
});
});
});
});
| 3,891
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messageSignature.ts
|
import { MailSettings, UserSettings } from '@proton/shared/lib/interfaces';
import { PM_SIGNATURE } from '@proton/shared/lib/mail/mailSettings';
import { isPlainText } from '@proton/shared/lib/mail/messages';
import { getProtonMailSignature } from '@proton/shared/lib/mail/signature';
import { message } from '@proton/shared/lib/sanitize';
import isTruthy from '@proton/utils/isTruthy';
import { MESSAGE_ACTIONS } from '../../constants';
import { MessageState } from '../../logic/messages/messagesTypes';
import { dedentTpl } from '../dedent';
import { isHTMLEmpty, parseInDiv } from '../dom';
import { replaceLineBreaks } from '../string';
import { exportPlainText, getPlainTextContent } from './messageContent';
import { CLASSNAME_BLOCKQUOTE } from './messageDraft';
export const CLASSNAME_SIGNATURE_CONTAINER = 'protonmail_signature_block';
export const CLASSNAME_SIGNATURE_USER = 'protonmail_signature_block-user';
export const CLASSNAME_SIGNATURE_PROTON = 'protonmail_signature_block-proton';
export const CLASSNAME_SIGNATURE_EMPTY = 'protonmail_signature_block-empty';
/**
* Preformat the protonMail signature
*/
const getProtonSignature = (mailSettings: Partial<MailSettings> = {}, userSettings: Partial<UserSettings> = {}) =>
mailSettings.PMSignature === PM_SIGNATURE.DISABLED
? ''
: getProtonMailSignature({
isReferralProgramLinkEnabled: !!mailSettings.PMSignatureReferralLink,
referralProgramUserLink: userSettings.Referral?.Link,
});
/**
* Generate a space tag, it can be hidden from the UX via a className
*/
const createSpace = (style?: string, className?: string) => {
const tagOpen = [
'div',
style === undefined ? undefined : `style="${style}"`,
className === undefined ? undefined : `class="${className}"`,
]
.filter(isTruthy)
.join(' ');
return `<${tagOpen}><br /></div>`;
};
/**
* Generate spaces for the signature
* No signature: 1 space
* addressSignature: 2 spaces + addressSignature
* protonSignature: 2 spaces + protonSignature
* user + proton signature: 2 spaces + addressSignature + 1 space + protonSignature
*/
const getSpaces = (signature: string, protonSignature: string, fontStyle: string | undefined, isReply = false) => {
const isUserSignatureEmpty = isHTMLEmpty(signature);
const isEmptySignature = isUserSignatureEmpty && !protonSignature;
return {
start: isEmptySignature ? createSpace(fontStyle) : createSpace(fontStyle) + createSpace(fontStyle),
end: isReply ? createSpace(fontStyle) : '',
between: !isUserSignatureEmpty && protonSignature ? createSpace(fontStyle) : '',
};
};
/**
* Generate a map of classNames used for the signature template
*/
const getClassNamesSignature = (signature: string, protonSignature: string) => {
const isUserEmpty = isHTMLEmpty(signature);
const isProtonEmpty = !protonSignature;
return {
userClass: isUserEmpty ? CLASSNAME_SIGNATURE_EMPTY : '',
protonClass: isProtonEmpty ? CLASSNAME_SIGNATURE_EMPTY : '',
containerClass: isUserEmpty && isProtonEmpty ? CLASSNAME_SIGNATURE_EMPTY : '',
};
};
/**
* Generate the template for a signature and clean it
*/
export const templateBuilder = (
signature = '',
mailSettings: Partial<MailSettings> | undefined = {},
userSettings: Partial<UserSettings> | undefined = {},
fontStyle: string | undefined,
isReply = false,
noSpace = false
) => {
const protonSignature = getProtonSignature(mailSettings, userSettings);
const { userClass, protonClass, containerClass } = getClassNamesSignature(signature, protonSignature);
const space = getSpaces(signature, protonSignature, fontStyle, isReply);
const defaultStyle = fontStyle === undefined ? '' : `style="${fontStyle}" `;
const template = dedentTpl`
<div ${defaultStyle}class="${CLASSNAME_SIGNATURE_CONTAINER} ${containerClass}">
<div class="${CLASSNAME_SIGNATURE_USER} ${userClass}">
${!isHTMLEmpty(signature) ? replaceLineBreaks(signature) : ''}
</div>
${space.between}
<div class="${CLASSNAME_SIGNATURE_PROTON} ${protonClass}">
${replaceLineBreaks(protonSignature)}
</div>
</div>
`;
if (!noSpace) {
return `${space.start}${message(template)}${space.end}`;
}
return message(template);
};
/**
* Insert Signatures before the message
* - Always append a container signature with both user's and proton's
* - Theses signature can be empty but the dom remains
*/
export const insertSignature = (
content = '',
signature = '',
action: MESSAGE_ACTIONS,
mailSettings: MailSettings,
userSettings: Partial<UserSettings>,
fontStyle: string | undefined,
isAfter = false
) => {
const position = isAfter ? 'beforeend' : 'afterbegin';
const template = templateBuilder(signature, mailSettings, userSettings, fontStyle, action !== MESSAGE_ACTIONS.NEW);
// Parse the current message and append before it the signature
const element = parseInDiv(content);
element.insertAdjacentHTML(position, template);
return element.innerHTML;
};
/**
* Return the content of the message with the signature switched from the old one to the new one
*/
export const changeSignature = (
message: MessageState,
mailSettings: Partial<MailSettings> | undefined,
userSettings: Partial<UserSettings> | undefined,
fontStyle: string | undefined,
oldSignature: string,
newSignature: string
) => {
if (isPlainText(message.data)) {
const oldTemplate = templateBuilder(oldSignature, mailSettings, userSettings, fontStyle, false, true);
const newTemplate = templateBuilder(newSignature, mailSettings, userSettings, fontStyle, false, true);
const content = getPlainTextContent(message);
const oldSignatureText = exportPlainText(oldTemplate).trim();
const newSignatureText = exportPlainText(newTemplate).trim();
// Special case when there was no signature before
if (oldSignatureText === '') {
return `${content}\n\n${newSignatureText}`;
}
return (
content
.replace(oldSignatureText, newSignatureText)
// Remove empty lines at the end, remove all lines if no signatures
.trimEnd()
);
}
const document = message.messageDocument?.document as Element;
const userSignature = [...document.querySelectorAll(`.${CLASSNAME_SIGNATURE_USER}`)].find(
(element) => element.closest(`.${CLASSNAME_BLOCKQUOTE}`) === null
);
if (userSignature) {
const protonSignature = getProtonSignature(mailSettings, userSettings);
const { userClass, containerClass } = getClassNamesSignature(newSignature, protonSignature);
userSignature.innerHTML = replaceLineBreaks(newSignature);
userSignature.className = `${CLASSNAME_SIGNATURE_USER} ${userClass}`;
const signatureContainer = userSignature?.closest(`.${CLASSNAME_SIGNATURE_CONTAINER}`);
if (signatureContainer && signatureContainer !== null) {
signatureContainer.className = `${CLASSNAME_SIGNATURE_CONTAINER} ${containerClass}`;
}
}
return document.innerHTML;
};
| 3,892
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messages.test.ts
|
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { getRecipients, getSender } from '@proton/shared/lib/mail/messages';
import { MessageImage, MessageImages } from '../../logic/messages/messagesTypes';
import { getAttachmentCounts, getMessagesAuthorizedToMove } from './messages';
const { INBOX, SENT, DRAFTS, TRASH, SPAM } = MAILBOX_LABEL_IDS;
describe('message', () => {
describe('getSender', () => {
it('should return Sender', () => {
const message = { Sender: { Name: 'Name', Address: 'Address' } } as Message;
expect(getSender(message)).toBe(message.Sender);
});
});
describe('getRecipients', () => {
it('should return Name over Address', () => {
const message = { ToList: [{ Name: 'Name', Address: 'Address' }] } as Message;
expect(getRecipients(message)).toEqual([message.ToList[0]]);
});
it('should return recipients from all kinds', () => {
const message = {
ToList: [{ Name: 'Name1' }],
CCList: [{ Address: 'Address2' }],
BCCList: [{ Name: 'Name3' }],
} as Message;
expect(getRecipients(message)).toEqual([message.ToList[0], message.CCList[0], message.BCCList[0]]);
});
});
describe('getMessagesAuthorizedToMove', () => {
const inboxMessage = { ID: '0', LabelIDs: [INBOX], Flags: 1 } as Message;
const sentMessage = { ID: '1', LabelIDs: [SENT], Flags: 2 } as Message;
const draftMessage = { ID: '2', LabelIDs: [DRAFTS], Flags: 0 } as Message;
it('should return messages authorized to move', () => {
expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], INBOX)).toEqual([
inboxMessage,
]);
expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], SENT)).toEqual([sentMessage]);
expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], DRAFTS)).toEqual([
draftMessage,
]);
});
it('should move all to trash', () => {
expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], TRASH)).toEqual([
inboxMessage,
sentMessage,
draftMessage,
]);
});
it('should authorize move to Inbox when message is sent to himself', () => {
const message = { ID: '0', LabelIDs: [SENT], Flags: 3 } as Message;
expect(getMessagesAuthorizedToMove([message], INBOX)).toEqual([message]);
});
it('should not move Sent and Draft messages to Spam', () => {
expect(getMessagesAuthorizedToMove([inboxMessage, sentMessage, draftMessage], SPAM)).toEqual([
inboxMessage,
]);
});
});
describe('getAttachmentCounts', () => {
const attachment1 = { ID: '0' };
const attachment2 = { ID: '1' };
const attachment3 = { ID: '2' };
const messageImage1 = { type: 'embedded', attachment: attachment1 };
const messageImage2 = { type: 'embedded', attachment: attachment2 };
const messageImage3 = { type: 'embedded', attachment: attachment2 }; // image 3 use attachment 2
const messageImage4 = { type: 'embedded', attachment: attachment2 }; // image 4 use attachment 2
it('should count only pure attachments', () => {
const { pureAttachmentsCount, embeddedAttachmentsCount, attachmentsCount } = getAttachmentCounts(
[attachment1],
{ images: [] as MessageImage[] } as MessageImages
);
expect(pureAttachmentsCount).toBe(1);
expect(embeddedAttachmentsCount).toBe(0);
expect(attachmentsCount).toBe(1);
});
it('should count only embedded images', () => {
const { pureAttachmentsCount, embeddedAttachmentsCount, attachmentsCount } = getAttachmentCounts(
[attachment1],
{ images: [messageImage1] } as MessageImages
);
expect(pureAttachmentsCount).toBe(0);
expect(embeddedAttachmentsCount).toBe(1);
expect(attachmentsCount).toBe(1);
});
it('should count mixed attachments', () => {
const { pureAttachmentsCount, embeddedAttachmentsCount, attachmentsCount } = getAttachmentCounts(
[attachment1, attachment2, attachment3],
{ images: [messageImage1, messageImage2] } as MessageImages
);
expect(pureAttachmentsCount).toBe(1);
expect(embeddedAttachmentsCount).toBe(2);
expect(attachmentsCount).toBe(3);
});
it('should deal with single attachment used for several embeddeds', () => {
const { pureAttachmentsCount, embeddedAttachmentsCount, attachmentsCount } = getAttachmentCounts(
[attachment1, attachment2, attachment3],
{ images: [messageImage1, messageImage2, messageImage3, messageImage4] } as MessageImages
);
expect(pureAttachmentsCount).toBe(1);
expect(embeddedAttachmentsCount).toBe(2);
expect(attachmentsCount).toBe(3);
});
});
});
| 3,893
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/messages.ts
|
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import humanSize from '@proton/shared/lib/helpers/humanSize';
import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message';
import { attachmentsSize, isDraft, isReceived, isSent, isSentAndReceived } from '@proton/shared/lib/mail/messages';
import uniqueBy from '@proton/utils/uniqueBy';
import { MARK_AS_STATUS } from '../../hooks/actions/useMarkAs';
import { MarkAsChanges } from '../../hooks/optimistic/useOptimisticMarkAs';
import {
MessageImages,
MessageState,
MessageStateWithData,
MessageWithOptionalBody,
PartialMessageState,
} from '../../logic/messages/messagesTypes';
import { getContent, setContent } from './messageContent';
import { getEmbeddedImages } from './messageImages';
const { SENT, DRAFTS, INBOX, SPAM } = MAILBOX_LABEL_IDS;
export const getAttachmentCounts = (attachments: Attachment[], messageImages: MessageImages | undefined) => {
const size = attachmentsSize({ Attachments: attachments } as Message);
const sizeLabel = humanSize(size);
const embeddedImages = getEmbeddedImages({ messageImages });
const embeddedAttachmentsWithDups = embeddedImages.map(({ attachment }) => attachment);
const embeddedAttachments = uniqueBy(embeddedAttachmentsWithDups, (attachment) => attachment.ID);
const pureAttachments = attachments.filter(
(attachment) => !embeddedAttachments.find((embeddedAttachment) => attachment.ID === embeddedAttachment.ID)
);
const embeddedAttachmentSize = attachmentsSize({ Attachments: embeddedAttachments } as Message);
const pureAttachmentSize = attachmentsSize({ Attachments: pureAttachments } as Message);
const pureAttachmentsCount = pureAttachments.length;
const embeddedAttachmentsCount = embeddedAttachments.length;
const attachmentsCount = pureAttachmentsCount + embeddedAttachmentsCount;
return {
size,
sizeLabel,
pureAttachments,
pureAttachmentsCount,
embeddedAttachmentsCount,
attachmentsCount,
embeddedAttachmentSize,
pureAttachmentSize,
};
};
/**
* Apply updates from the message model to the message in state
*/
export const mergeMessages = (
messageState: MessageState | undefined,
messageModel: PartialMessageState
): MessageState => {
if (messageState?.messageDocument?.document && messageModel.messageDocument?.document) {
setContent(messageState, getContent(messageModel));
}
return {
...messageState,
...messageModel,
data: { ...messageState?.data, ...messageModel.data } as Message,
decryption: { ...messageState?.decryption, ...messageModel.decryption },
messageDocument: { ...messageState?.messageDocument, ...messageModel.messageDocument },
verification: { ...messageState?.verification, ...messageModel.verification },
draftFlags: { ...messageState?.draftFlags, ...messageModel.draftFlags },
errors: { ...messageState?.errors, ...messageModel.errors },
} as MessageState;
};
export const getMessagesAuthorizedToMove = (messages: Message[], destinationFolderID: string) => {
return messages.filter((message) => {
if ([SENT, DRAFTS, INBOX, SPAM].includes(destinationFolderID as MAILBOX_LABEL_IDS)) {
const excludedDestinations = [];
if (!isSentAndReceived(message)) {
if (isReceived(message)) {
excludedDestinations.push(...[SENT, DRAFTS]);
}
if (isSent(message)) {
excludedDestinations.push(...[INBOX, DRAFTS, SPAM]);
}
}
if (isDraft(message)) {
excludedDestinations.push(...[INBOX, SENT, SPAM]);
}
return !excludedDestinations.includes(destinationFolderID as MAILBOX_LABEL_IDS);
}
return true;
});
};
export const getMessageHasData = (message: MessageState): message is MessageStateWithData => !!message.data;
export const applyMarkAsChangesOnMessage = <T>(
message: MessageWithOptionalBody & T,
{ status, displaySnoozedReminder }: MarkAsChanges
): MessageWithOptionalBody & T => ({
...message,
DisplaySnoozedReminder: displaySnoozedReminder,
Unread: status === MARK_AS_STATUS.UNREAD ? 1 : 0,
});
| 3,894
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/trackers.test.tsx
|
import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers';
import { Tracker } from '../../hooks/message/useMessageTrackers';
import { MessageImage, MessageImages, MessageState } from '../../logic/messages/messagesTypes';
import { createDocument } from '../test/message';
import { getImageTrackersFromMessage, getUTMTrackersFromMessage } from './trackers';
const tracker1Url = 'http://tracker.com';
const tracker2Url = 'http://tracking.com';
const tracker3Url = 'http://trackerInBlockQuote.com';
const tracker4Url = 'http://Tracker.com';
const utmTracker1 = 'http://tracker.com?utm_source=tracker';
const utmTracker2 = 'http://tracking.com?utm_source=tracking&utm_content=tracking';
const document = `
<div>
<div>
Here is some mail content
<img src="${tracker1Url}" alt="" data-proton-remote="1"/>
<img src="${tracker1Url}" alt="" data-proton-remote="2"/>
<img src="${tracker2Url}" alt="" data-proton-remote="3"/>
<img src="${tracker4Url}" alt="" data-proton-remote="5"/>
</div>
<blockquote class="protonmail_quote" type="cite">
Here is some blockquote content
<img src="${tracker3Url}" alt="" data-proton-remote="4"/>
</blockquote>
</div>`;
const message = {
messageImages: {
images: [
{
type: 'remote',
id: '1',
originalURL: `${tracker1Url}/tracker-1`,
url: `${tracker1Url}/tracker-1`,
tracker: tracker1Url,
},
{
type: 'remote',
id: '2',
originalURL: `${tracker1Url}/tracker-2`,
url: `${tracker1Url}/tracker-2`,
tracker: tracker1Url,
},
{
type: 'embedded',
id: '3',
cloc: `${tracker2Url}/tracker`,
tracker: tracker2Url,
},
] as MessageImage[],
} as MessageImages,
messageDocument: {
document: createDocument(document),
},
messageUTMTrackers: [
{
originalURL: utmTracker1,
cleanedURL: tracker1Url,
removed: [{ key: 'utm_source', value: 'tracker' }],
},
{
originalURL: utmTracker2,
cleanedURL: tracker2Url,
removed: [
{ key: 'utm_source', value: 'tracking' },
{ key: 'utm_content', value: 'tracking' },
],
},
] as MessageUTMTracker[],
} as MessageState;
describe('trackers', () => {
describe('getImageTrackersFromMessage', () => {
it('should return the expected image trackers', () => {
const { trackers, numberOfTrackers } = getImageTrackersFromMessage(message);
const expectedTrackers: Tracker[] = [
{ name: tracker1Url, urls: [`${tracker1Url}/tracker-1`, `${tracker1Url}/tracker-2`] },
{ name: tracker2Url, urls: [`${tracker2Url}/tracker`] },
];
expect(trackers).toEqual(expectedTrackers);
expect(numberOfTrackers).toEqual(3);
});
});
describe('getImageTrackersFromMessage', () => {
it('should return expected utm trackers', () => {
const { trackers, numberOfTrackers } = getUTMTrackersFromMessage(message);
const expectedTrackers = [
{
originalURL: utmTracker1,
cleanedURL: tracker1Url,
removed: [{ key: 'utm_source', value: 'tracker' }],
},
{
originalURL: utmTracker2,
cleanedURL: tracker2Url,
removed: [
{ key: 'utm_source', value: 'tracking' },
{ key: 'utm_content', value: 'tracking' },
],
},
];
expect(trackers).toEqual(expectedTrackers);
expect(numberOfTrackers).toEqual(2);
});
});
});
| 3,895
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/trackers.ts
|
import { c, msgid } from 'ttag';
import { Tracker } from '../../hooks/message/useMessageTrackers';
import { MessageState } from '../../logic/messages/messagesTypes';
export const getImageTrackersFromMessage = (message: MessageState) => {
const trackersImages = message.messageImages?.images.filter((image) => {
return image.tracker;
});
const trackers: Tracker[] = [];
trackersImages?.forEach((trackerImage) => {
const elExists = trackers.findIndex((tracker) => tracker.name === trackerImage.tracker);
let url = '';
if ('cloc' in trackerImage) {
url = trackerImage.cloc;
} else if ('originalURL' in trackerImage) {
url = trackerImage.originalURL || '';
}
if (elExists < 0) {
trackers.push({ name: trackerImage.tracker || '', urls: [url] });
} else {
const alreadyContainsURL = trackers[elExists].urls.includes(url);
if (!alreadyContainsURL) {
trackers[elExists] = { ...trackers[elExists], urls: [...trackers[elExists].urls, url] };
}
}
});
const numberOfTrackers = trackers.reduce((acc, tracker) => {
return acc + tracker.urls.length;
}, 0);
return { trackers, numberOfTrackers };
};
export const getUTMTrackersFromMessage = (message: MessageState) => {
return { trackers: message.messageUTMTrackers || [], numberOfTrackers: message.messageUTMTrackers?.length || 0 };
};
export const getImageTrackerText = (numberOfImageTrackers: number) => {
if (numberOfImageTrackers === 0) {
return c('Info').t`No trackers found`;
}
return c('Info').ngettext(
msgid`${numberOfImageTrackers} tracker blocked`,
`${numberOfImageTrackers} trackers blocked`,
numberOfImageTrackers
);
};
export const getUTMTrackerText = (numberOfUTMTrackers: number) => {
if (numberOfUTMTrackers === 0) {
return c('Info').t`No links cleaned`;
}
return c('Info').ngettext(
msgid`${numberOfUTMTrackers} link cleaned`,
`${numberOfUTMTrackers} links cleaned`,
numberOfUTMTrackers
);
};
| 3,896
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/__fixtures__/messageBlockquote.fixtures.ts
|
/* eslint-disable @typescript-eslint/naming-convention */
import { ORIGINAL_MESSAGE } from "@proton/shared/lib/mail/messages";
/**
* Mails extracted by us
*/
const proton1 = `
<div><br></div>
<div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty"><br></div>
<div class="protonmail_signature_block-proton">Sent with <a href="https://proton.me/?utm_campaign=ww-all-2a-mail-pmm_mail-protonmail_signature&utm_source=proton_users&utm_medium=cta&utm_content=sent_with_protonmail_secure_email" target="_blank">ProtonMail</a> Secure Email.<br></div>
</div>
<div><br></div>
<div class="protonmail_quote">
<div>${ORIGINAL_MESSAGE}<br></div>
<div> On Monday 19 January 1970 à 08:21, Matthieu Lux wrote:<br></div>
<div> <br></div>
<blockquote class="protonmail_quote" type="cite"><div dir="ltr">1<br></div></blockquote>
</div>
`;
const gmail1 = `
<div>
<div dir="ltr">3</div>
<br>
<div class="gmail_quote">
<div class="gmail_attr" dir="ltr">Le ven. 14 févr. 2020 à 10:19, swiip.test <swiip.test@protonmail.blue> a écrit :<br></div>
<blockquote style="margin:0px 0px 0px 0.8ex;border-inline-start:1px solid rgb(204,204,204);padding-inline-start:1ex" class="gmail_quote">
<div>
<div>2<br></div><div><br></div><div><div><br></div><div>Sent with <a target="_blank" href="https://proton.me/?utm_campaign=ww-all-2a-mail-pmm_mail-protonmail_signature&utm_source=proton_users&utm_medium=cta&utm_content=sent_with_protonmail_secure_email" rel="noreferrer nofollow noopener">ProtonMail</a> Secure Email.<br></div></div><div><br></div><span>${ORIGINAL_MESSAGE}</span><br>
On Monday 19 January 1970 à 08:21, Matthieu Lux wrote:<br>
<blockquote type="cite">
<div dir="ltr">1</div>
</blockquote>
<br>
</div>
</blockquote>
</div>
</div>
`;
/**
* Mails found on https://github.com/mailgun/talon/tree/master/tests/fixtures
*/
const android = `
<p>Hello</p>
<div class="gmail_quote">02.04.2012 14:20 пользователь "<a href="mailto:bob@xxx.mailgun.org">bob@xxx.mailgun.org</a>" <<a href="mailto:bob@xxx.mailgun.org">bob@xxx.mailgun.org</a>> написал:<br type="attribution">
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-inline-start:1px #ccc solid;padding-inline-start:1ex">Hi<br>
</blockquote></div>
`;
const aol1 = `
<font color='black' size='2' face='arial'>Hello<br>
<span>toto</span>
<span>${ORIGINAL_MESSAGE}</span>
<br>
<br>
<div style="font-family:arial,helvetica;font-size:10pt;color:black">${ORIGINAL_MESSAGE}<br>
From: bob <bob@example.com><br>
To: xxx <xxx@gmail.com>; xxx <xxx@hotmail.com>; xxx <xxx@yahoo.com>; xxx <xxx@aol.com>; xxx <xxx@comcast.net>; xxx <xxx@nyc.rr.com><br>
Sent: Mon, Apr 2, 2012 5:49 pm<br>
Subject: Test<br>
<br>
<span>${ORIGINAL_MESSAGE}</span>
<div id="AOLMsgPart_0_4d68a632-fe65-4f6d-ace2-292ac1b91f1f" style="margin: 0px;font-family: Tahoma, Verdana, Arial, Sans-Serif;font-size: 12px;color: #000;background-color: #fff;">
<pre style="font-size: 9pt;"><tt>Hi
</tt></pre>
</div>
<!-- end of AOLMsgPart_0_4d68a632-fe65-4f6d-ace2-292ac1b91f1f -->
</div>
</font>
`;
const comcast = `
<html>
<head><style type='text/css'>p { margin: 0; }</style></head>
<body>
<div style='font-family: Arial; font-size: 12pt; color: #000000'>
Hello<br><br><hr id="zwchr"><b>From: </b>bob@xxx.mailgun.org<br><b>To: </b>xxx@gmail.com, xxx@hotmail.com, xxx@yahoo.com, xxx@aol.com, xxx@comcast.net, lsloan6@nyc.rr.com<br><b>Sent: </b>Monday, April 2, 2012 5:44:22 PM<br><b>Subject: </b>Test<br><br>Hi<br>
</div>
</body>
</html>
`;
const gmail2 = `
Hello<br><br><div class="gmail_quote">On Mon, Apr 2, 2012 at 6:26 PM, Megan One <span dir="ltr"><<a href="mailto:xxx@gmail.com">xxx@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-inline-start:1px #ccc solid;padding-inline-start:1ex">
Hi
</blockquote></div><br>
`;
const gmail3 = `
<div dir="ltr"><div class="gmail_default"><div class="gmail_default" style>Hi. I am fine.</div><div class="gmail_default" style><br></div><div class="gmail_default" style>Thanks,</div><div class="gmail_default" style>Alex</div>
</div></div><div class="gmail_extra"><br><br><div class="gmail_quote">On Thu, Jun 26, 2014 at 2:14 PM, Alexander L <span dir="ltr"><<a href="mailto:abc@example.com" target="_blank">a@example.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-inline-start:1px #ccc solid;padding-inline-start:1ex"><div dir="ltr"><div class="gmail_default" style="font-size:small"><div class="gmail_default" style="font-family:arial,sans-serif">
Hello! How are you?</div><div class="gmail_default" style="font-family:arial,sans-serif"><br>
</div><div class="gmail_default" style="font-family:arial,sans-serif">Thanks,</div><div class="gmail_default" style="font-family:arial,sans-serif">Sasha.</div></div></div>
</blockquote></div><br></div>
`;
const hotmail1 = `
<html>
<head>
<style><!--
.hmmessage P
{
margin:0px;
padding:0px
}
body.hmmessage
{
font-size: 10pt;
font-family:Tahoma
}
--></style></head>
<body class='hmmessage'><div dir='ltr'>
Hello<br><br><div><div id="SkyDrivePlaceholder"></div>> Subject: Test<br>> From: bob@xxx.mailgun.org<br>> To: xxx@gmail.com; xxx@hotmail.com; xxx@yahoo.com; xxx@aol.com; xxx@comcast.net; xxx@nyc.rr.com<br>> Date: Mon, 2 Apr 2012 17:44:22 +0400<br>> <br>> Hi<br></div> </div></body>
</html>
`;
const hotmail2 = `
<?xml version="1.0" encoding="UTF-8"?>
<html>
<head>
<style><!--
.hmmessage P
{
margin:0px;
padding:0px
}
body.hmmessage
{
font-size: 12pt;
font-family:Calibri
}
--></style></head>
<body class='hmmessage'><div dir='ltr'>Hi. I am fine.<div><br></div><div>Thanks,</div><div>Alex<br><br><div><hr id="stopSpelling">Date: Thu, 26 Jun 2014 13:53:45 +0400<br>Subject: Test message<br>From: abc@example.com<br>To: alex.l@example.com<br><br><div dir="ltr"><div class="ecxgmail_default" style="font-size:small;">Hello! How are you?</div><div class="ecxgmail_default" style="font-size:small;"><br></div><div class="ecxgmail_default" style="font-size:small;">Thanks,</div><div class="ecxgmail_default" style="font-size:small;">
Sasha.</div></div></div></div> </div></body>
</html>
`;
const outlook1 = `
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=us-ascii"><meta name=Generator content="Microsoft Word 14 (filtered medium)"><style><!--
/* Font Definitions */
@font-face
{font-family:Calibri;
panose-1:2 15 5 2 2 2 4 3 2 4;}
@font-face
{font-family:Tahoma;
panose-1:2 11 6 4 3 5 4 4 2 4;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{margin:0cm;
margin-block-end:.0001pt;
font-size:12.0pt;
font-family:"Times New Roman","serif";}
a:link, span.MsoHyperlink
{mso-style-priority:99;
color:blue;
text-decoration:underline;}
a:visited, span.MsoHyperlinkFollowed
{mso-style-priority:99;
color:purple;
text-decoration:underline;}
span.EmailStyle17
{mso-style-type:personal-reply;
font-family:"Calibri","sans-serif";
color:#1F497D;}
.MsoChpDefault
{mso-style-type:export-only;
font-family:"Calibri","sans-serif";
mso-fareast-language:EN-US;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:72.0pt 72.0pt 72.0pt 72.0pt;}
div.WordSection1
{page:WordSection1;}
--></style><!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1026" />
</xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1" />
</o:shapelayout></xml><![endif]--></head><body lang=EN-CA link=blue vlink=purple><div class=WordSection1><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D'>Allo! Follow up MIME!<o:p></o:p></span></p><p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D'><o:p> </o:p></span></p><p class=MsoNormal><b><span lang=EN-US style='font-size:10.0pt;font-family:"Tahoma","sans-serif"'>From:</span></b><span lang=EN-US style='font-size:10.0pt;font-family:"Tahoma","sans-serif"'> xxx@xxx.mailgun.org [mailto:xxx@xxx.mailgun.org] <br><b>Sent:</b> March-09-12 4:22 PM<br><b>To:</b> Dan Le<br><b>Subject:</b> The manager has commented on your Loop<o:p></o:p></span></p><p class=MsoNormal><o:p> </o:p></p><p class=MsoNormal>Hi <a href="mailto:dan.le@example.com">dan.le@example.com</a>,<br><br>The manager's comment:<br>"Hello Allan! Did you ask for some MIME? "<br><br>Loop details:<br><br>xxx at Dan<br>I'm not happy<br>""<br><br>Your Loop is <a href="http://dev.xxx.com/loop/view/4f50f20e160839c95a000bb3?_uid=4f3541a7ac63e655040008e3">here</a>.<br><br>We will be in touch again with any further updates,<br><br>xxx<br><br>If you did not sign up to receive emails from us you can use the link below to unsubscribe. We apologize for any inconvenience.<br><br><a href="http://dev.xxx.com/user/unsubscribe/dan.le@example.com?verify=4a400554148256338956101abdf06406">Unsubscribe</a> <o:p></o:p></p></div></body></html>
`;
const outlook2003 = `
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=us-ascii">
<meta name=Generator content="Microsoft Word 11 (filtered medium)">
<!--[if !mso]>
<style>
v\\:* {behavior:url(#default#VML);}
o\\:* {behavior:url(#default#VML);}
w\\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style>
<![endif]-->
<style>
<!--
/* Font Definitions */
@font-face
{font-family:Tahoma;
panose-1:2 11 6 4 3 5 4 4 2 4;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{margin:0cm;
margin-block-end:.0001pt;
font-size:12.0pt;
font-family:"Times New Roman";}
a:link, span.MsoHyperlink
{color:blue;
text-decoration:underline;}
a:visited, span.MsoHyperlinkFollowed
{color:purple;
text-decoration:underline;}
span.EmailStyle17
{mso-style-type:personal-reply;
font-family:Arial;
color:navy;}
@page Section1
{size:595.3pt 841.9pt;
margin:2.0cm 42.5pt 2.0cm 3.0cm;}
div.Section1
{page:Section1;}
-->
</style>
<!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1026" />
</xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1" />
</o:shapelayout></xml><![endif]-->
</head>
<body lang=RU link=blue vlink=purple>
<div class=Section1>
<p class=MsoNormal><font size=2 color=navy face=Arial><span lang=EN-US
style='font-size:10.0pt;font-family:Arial;color:navy'>Hi. I am fine.<o:p></o:p></span></font></p>
<p class=MsoNormal><font size=2 color=navy face=Arial><span lang=EN-US
style='font-size:10.0pt;font-family:Arial;color:navy'><o:p> </o:p></span></font></p>
<p class=MsoNormal><font size=2 color=navy face=Arial><span lang=EN-US
style='font-size:10.0pt;font-family:Arial;color:navy'>Thanks,<o:p></o:p></span></font></p>
<p class=MsoNormal><font size=2 color=navy face=Arial><span lang=EN-US
style='font-size:10.0pt;font-family:Arial;color:navy'>Alex<o:p></o:p></span></font></p>
<p class=MsoNormal><font size=2 color=navy face=Arial><span style='font-size:
10.0pt;font-family:Arial;color:navy'><o:p> </o:p></span></font></p>
<div>
<div class=MsoNormal align=center style='text-align:center'><font size=3
face="Times New Roman"><span lang=EN-US style='font-size:12.0pt'>
<hr size=3 width="100%" align=center tabindex=-1>
</span></font></div>
<p class=MsoNormal><b><font size=2 face=Tahoma><span lang=EN-US
style='font-size:10.0pt;font-family:Tahoma;font-weight:bold'>From:</span></font></b><font
size=2 face=Tahoma><span lang=EN-US style='font-size:10.0pt;font-family:Tahoma'>
Alexander L [mailto:abc@example.com] <br>
<b><span style='font-weight:bold'>Sent:</span></b> Friday, June 27, 2014 12:06
PM<br>
<b><span style='font-weight:bold'>To:</span></b> Alexander<br>
<b><span style='font-weight:bold'>Subject:</span></b> Test message</span></font><span
lang=EN-US><o:p></o:p></span></p>
</div>
<p class=MsoNormal><font size=3 face="Times New Roman"><span style='font-size:
12.0pt'><o:p> </o:p></span></font></p>
<div>
<div>
<div>
<p class=MsoNormal><font size=3 face=Arial><span style='font-size:12.0pt;
font-family:Arial'>Hello! How are you?<o:p></o:p></span></font></p>
</div>
<div>
<p class=MsoNormal><font size=3 face=Arial><span style='font-size:12.0pt;
font-family:Arial'><o:p> </o:p></span></font></p>
</div>
<div>
<p class=MsoNormal><font size=3 face=Arial><span style='font-size:12.0pt;
font-family:Arial'>Thanks,<o:p></o:p></span></font></p>
</div>
<div>
<p class=MsoNormal><font size=3 face=Arial><span style='font-size:12.0pt;
font-family:Arial'>Sasha.<o:p></o:p></span></font></p>
</div>
</div>
</div>
</div>
</body>
</html>
`;
const outlook2007 = `
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv=Content-Type content="text/html; charset=utf-8"><meta name=Generator content="Microsoft Word 12 (filtered medium)"><style><!--
/* Font Definitions */
@font-face
{font-family:"Cambria Math";
panose-1:2 4 5 3 5 4 6 3 2 4;}
@font-face
{font-family:Calibri;
panose-1:2 15 5 2 2 2 4 3 2 4;}
@font-face
{font-family:Tahoma;
panose-1:2 11 6 4 3 5 4 4 2 4;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{margin:0cm;
margin-block-end:.0001pt;
font-size:12.0pt;
font-family:"Times New Roman","serif";}
a:link, span.MsoHyperlink
{mso-style-priority:99;
color:blue;
text-decoration:underline;}
a:visited, span.MsoHyperlinkFollowed
{mso-style-priority:99;
color:purple;
text-decoration:underline;}
span.EmailStyle17
{mso-style-type:personal-reply;
font-family:"Calibri","sans-serif";
color:#1F497D;}
.MsoChpDefault
{mso-style-type:export-only;}
@page WordSection1
{size:612.0pt 792.0pt;
margin:2.0cm 42.5pt 2.0cm 3.0cm;}
div.WordSection1
{page:WordSection1;}
--></style><!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1026" />
</xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1" />
</o:shapelayout></xml><![endif]--></head>
<body lang=EN-US link=blue vlink=purple>
<div class=WordSection1>
<p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D'>Hi. I am fine.<o:p></o:p></span></p>
<p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D'> <o:p></o:p></span></p>
<p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D'>Thanks,<o:p></o:p></span></p>
<p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D'>Alex<o:p></o:p></span></p>
<p class=MsoNormal><span style='font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D'><o:p> </o:p></span></p>
<div style='border:none;border-block-start:solid #B5C4DF 1.0pt;padding-block:3.0pt 0cm;padding-inline:0'>
<p class=MsoNormal><b><span lang=RU style='font-size:10.0pt;font-family:"Tahoma","sans-serif"'>From:</span></b><span lang=RU style='font-size:10.0pt;font-family:"Tahoma","sans-serif"'> Alexander L [mailto:abc@example.com] <br><b>Sent:</b> Thursday, July 03, 2014 3:50 PM<br><b>To:</b> alex.l@example.com<br><b>Subject:</b> Test message<o:p></o:p></span></p>
</div>
<p class=MsoNormal><o:p> </o:p></p>
<div><div><div><p class=MsoNormal><span style='font-family:"Arial","sans-serif"'>Hello! How are you?<o:p></o:p></span></p></div><div><p class=MsoNormal><span style='font-family:"Arial","sans-serif"'><o:p> </o:p></span></p></div><div><p class=MsoNormal><span style='font-family:"Arial","sans-serif"'>Thanks,<o:p></o:p></span></p></div><div><p class=MsoNormal><span style='font-family:"Arial","sans-serif"'>Sasha.<o:p></o:p></span></p></div></div></div></div></body></html>
`;
const outlook2010 = `
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-2022-jp">
<meta name="Generator" content="Microsoft Word 14 (filtered medium)">
<style><!--
/* Font Definitions */
@font-face
{font-family:Calibri;
panose-1:2 15 5 2 2 2 4 3 2 4;}
@font-face
{font-family:Tahoma;
panose-1:2 11 6 4 3 5 4 4 2 4;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{margin:0in;
margin-block-end:.0001pt;
font-size:12.0pt;
font-family:"Times New Roman","serif";}
h3
{mso-style-priority:9;
mso-style-link:"Heading 3 Char";
mso-margin-block-start-alt:auto;
margin-inline-end:0in;
mso-margin-block-end-alt:auto;
margin-inline-start:0in;
font-size:13.5pt;
font-family:"Times New Roman","serif";
font-weight:bold;}
a:link, span.MsoHyperlink
{mso-style-priority:99;
color:blue;
text-decoration:underline;}
a:visited, span.MsoHyperlinkFollowed
{mso-style-priority:99;
color:purple;
text-decoration:underline;}
p
{mso-style-priority:99;
mso-margin-block-start-alt:auto;
margin-inline-end:0in;
mso-margin-block-end-alt:auto;
margin-inline-start:0in;
font-size:12.0pt;
font-family:"Times New Roman","serif";}
span.Heading3Char
{mso-style-name:"Heading 3 Char";
mso-style-priority:9;
mso-style-link:"Heading 3";
font-family:"Cambria","serif";
color:#4F81BD;
font-weight:bold;}
span.EmailStyle19
{mso-style-type:personal-reply;
font-family:"Calibri","sans-serif";
color:#1F497D;}
.MsoChpDefault
{mso-style-type:export-only;
font-family:"Calibri","sans-serif";}
@page WordSection1
{size:8.5in 11.0in;
margin:1.0in 1.0in 1.0in 1.0in;}
div.WordSection1
{page:WordSection1;}
--></style><!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1026" />
</xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1" />
</o:shapelayout></xml><![endif]-->
</head>
<body lang="EN-US" link="blue" vlink="purple">
<div class="WordSection1">
<p class="MsoNormal"><span style="font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D">Hi. I am fine.<o:p></o:p></span></p>
<p class="MsoNormal"><span style="font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D">Thanks,<o:p></o:p></span></p>
<p class="MsoNormal"><span style="font-size:11.0pt;font-family:"Calibri","sans-serif";color:#1F497D">Alex<o:p></o:p></span></p>
<p class="MsoNormal"><b><span style="font-size:10.0pt;font-family:"Tahoma","sans-serif"">From:</span></b><span style="font-size:10.0pt;font-family:"Tahoma","sans-serif""> Foo [mailto:foo@bar.com]
<b>On Behalf Of </b>baz@bar.com<br>
<b>Sent:</b> Monday, January 01, 2000 12:00 AM<br>
<b>To:</b> john@bar.com<br>
<b>Cc:</b> jane@bar.io<br>
<b>Subject:</b> Conversation<o:p></o:p></span></p>
<p class="MsoNormal"><o:p> </o:p></p>
<p>Hello! How are you?<o:p></o:p></p>
<p class="MsoNormal"><o:p> </o:p></p>
</div>
</body>
</html>
`;
const sparrow = `
<div>
<span style=3D=22font-size: 12px;=22>Hello</span>
</div>
<div><div><br></div><div>-- </div><div>xx=
x</div><div>Sent with <a href=3D=22http://www.sparrowmailapp.com/=3Fsig=22=
>Sparrow</a></div><div><br></div></div>
=20
<p style=3D=22color: =23A0A0A8;=22>On Tuesday, April 3, 2=
012 at 4:55 PM, xxx wrote:</p>
<blockquote type=3D=22cite=22 style=3D=22border-inline-start-styl=
e:solid;border-width:1px;margin-inline-start:0px;padding-inline-start:10px;=22>
<span><div><div><div>Hello</div><div><br></div><div>O=
n Apr 3, 2012, at 4:19 PM, bob wrote:</div><div><br></div><blo=
ckquote type=3D=22cite=22><div>Hi</div></blockquote></div></div></span>
=20
=20
=20
=20
</blockquote>
=20
<div>
<br>
</div>
`;
export const mail_ru = `
<HTML><BODY><p>Hi. I am fine.</p><p>Thanks,<br>Alex</p><br><br><br>Thu, 26 Jun 2014 14:00:51 +0400 от Alexander L <abc@example.com>:<br>
<blockquote style="border-inline-start:1px solid #0857A6; margin:10px; padding-block:0; padding-inline: 10px 0;">
<div id="">
<div class="js-helper js-readmsg-msg">
<style type="text/css"></style>
<div>
<base target="_self" href="https://e.mail.ru/">
<div id="style_14037768550000001020_BODY"><div dir="ltr"><div style="font-size:small"><div style="font-family:arial,sans-serif">Hello! How are you?</div><div style="font-family:arial,sans-serif"><br>
</div><div style="font-family:arial,sans-serif">Thanks,</div><div style="font-family:arial,sans-serif">Sasha.</div></div></div>
</div>
<base target="_self" href="https://e.mail.ru/">
</div>
</div>
</div>
</blockquote>
<br></BODY></HTML>
`;
const thunderbird = `
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
</head>
<body bgcolor="#FFFFFF" text="#000000">
Hi. I am fine.<br>
<br>
Thanks,<br>
Alex<br>
<div class="moz-cite-prefix">On 26.06.2014 14:41, Alexander L
wrote:<br>
</div>
<blockquote
cite="mid:CA+jEWTKBU6qc4OnH5m=-0sfwkAzZhcy0rd+ean2W6bFUVXaO7A@mail.gmail.com"
type="cite">
<div dir="ltr">
<div class="gmail_default" style="font-size:small">
<div class="gmail_default"
style="font-family:arial,sans-serif">Hello! How are you?</div>
<div class="gmail_default"
style="font-family:arial,sans-serif"><br>
</div>
<div class="gmail_default"
style="font-family:arial,sans-serif">Thanks,</div>
<div class="gmail_default"
style="font-family:arial,sans-serif">Sasha.</div>
</div>
</div>
</blockquote>
<br>
</body>
</html>
`;
const windows_mail = `
<html>
<head>
<meta name="generator" content="Windows Mail 17.5.9600.20498">
<style data-externalstyle="true"><!--
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph {
margin-block-start:0in;
margin-inline-end:0in;
margin-block-end:0in;
margin-inline-start:.5in;
margin-block-end:.0001pt;
}
p.MsoNormal, li.MsoNormal, div.MsoNormal {
margin:0in;
margin-block-end:.0001pt;
}
p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst,
p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle,
p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast {
margin-block-start:0in;
margin-inline-end:0in;
margin-block-end:0in;
margin-inline-start:.5in;
margin-block-end:.0001pt;
line-height:115%;
}
--></style></head>
<body dir="ltr">
<div data-externalstyle="false" dir="ltr" style="font-family: 'Calibri', 'Segoe UI', 'Meiryo', 'Microsoft YaHei UI', 'Microsoft JhengHei UI', 'Malgun Gothic', 'sans-serif';font-size:12pt;"><div>Hi. I am fine.</div><div><br></div><div>Thanks,</div><div>Alex<br></div><div data-signatureblock="true"><div><br></div><div><br></div></div><div style="padding-block-start: 5px; border-block-start-color: rgb(229, 229, 229); border-block-start-width: 1px; border-block-start-style: solid;"><div><font face=" 'Calibri', 'Segoe UI', 'Meiryo', 'Microsoft YaHei UI', 'Microsoft JhengHei UI', 'Malgun Gothic', 'sans-serif'" style='line-height: 15pt; letter-spacing: 0.02em; font-family: "Calibri", "Segoe UI", "Meiryo", "Microsoft YaHei UI", "Microsoft JhengHei UI", "Malgun Gothic", "sans-serif"; font-size: 12pt;'><b>От:</b> <a href="mailto:abc@example.com" target="_parent">Alexander L</a><br><b>Отправлено:</b> четверг, 26 июня 2014 г. 15:05<br><b>Кому:</b> <a href="mailto:alex-ninja@example.com" target="_parent">Alex</a></font></div></div><div><br></div><div dir=""><div dir="ltr"><div class="gmail_default" style="font-size: small;"><div class="gmail_default" style="font-family: arial,sans-serif;">Hello! How are you?</div><div class="gmail_default" style="font-family: arial,sans-serif;"><br>
</div><div class="gmail_default" style="font-family: arial,sans-serif;">Thanks,</div><div class="gmail_default" style="font-family: arial,sans-serif;">Sasha.</div></div></div>
</div></div>
</body>
</html>
`;
const yandex1 = `
<p>
Hi. I am fine.<br /><br />
Thanks,<br />
Alex<br /><br />
26.06.2014, 14:41, "Alexander L" <<a href="mailto:abc@example.com">abc@example.com</a>>:</p>
<blockquote> Hello! How are you?<br /><br /> Thanks,<br /> Sasha.</blockquote>
`;
/**
* Mails from https://github.com/felixfw1990/email-origin/tree/master/test/Providers
*/
const aol2 = `
<div style="color:;font: 10pt Helvetica Neue;"><span style="font-family: Arial, Helvetica, sans-serif;">我的爱人</span>
<div>
<span style="font-family: Arial, Helvetica, sans-serif; font-weight: bold; text-decoration-line: underline; font-style: italic; background-color: red;"><font
size="7">我爱你</font></span></div>
<div><span style="font-family: Arial, Helvetica, sans-serif; font-weight: bold; text-decoration-line: underline; font-style: italic; background-color: red;"><font
size="7"><br>
</font></span><br>
<br>
<div style="font-family:helvetica,arial;font-size:10pt;color:black">${ORIGINAL_MESSAGE}<br>
From: felix <felixfw1111@gmail.com><br>
To: achankayi <csdfsf@aol.com><br>
Sent: Wed, Jul 3, 2019 6:10 pm<br>
Subject: gmail to aol<br>
<br>
<div id="yiv5828060424">
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb(255,0,0);">contnet2</u></i></div>
</div>
</div>
</div>
</div>
</div>
`;
const gmail4 = `
<div dir="ltr">
<div dir="ltr">
<div class = "abc", id = "sss">回复内容</divsty>
<div dir="ltr"><b>this is content 1</b>
<div><b><u>this is content 2</u></b></div>
</div>
<br><br>
<div class="gmail_quote">
<div dir="ltr" class="gmail_attr">冯伟 <<a href="mailto:felixfw1111@gmail.com">felixfw1111@gmail.com</a>>
于2019年7月2日周二 下午5:36写道:<br></div>
<blockquote class="gmail_quote"
style="margin-block:0; margin-inline: 0.8ex 0;border-inline-start-width:1px;border-inline-start-style:solid;border-inline-start-color:rgb(204,204,204);padding-inline-start:1ex">
<div dir="ltr"><b>this is content 1</b>
<div><b><u>this is content 2</u><br></b>
<div><br></div>
</div>
</div>
</blockquote>
</div>
</div>
</div>
`;
const gmx = `
回复内容<br />
content1<br />
content2<br>
<br>
<div name="quote"
style='margin-block: 10px 5px; margin-inline: 10px 5px; padding-block: 10px; padding-inline: 10px 0; border-inline-start:2px solid #C3D9E5; word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;'>
<div style="margin-block: 0 10px; margin-inline: 0;">
<b>Sent:</b> Tuesday, July 02, 2019 at 6:15 PM<br />
<b>From:</b> "冯伟" <felixfw1111@gmail.com><br />
<b>To:</b> felixfw1111@gmx.com<br />
<b>Subject:</b> gmail to gmx
</div>
<div name="quoted-content">
<div><b>content1</b>
<div><i><u style="background-color: rgb(255,0,0);">content2</u></i></div>
</div>
</div>
</div>
<br />
`;
const hotmail3 = `
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<style type="text/css" style="display:none;"> P {
margin-block-start: 0;
margin-block-end: 0;
} </style>
</head>
<body dir="ltr">
<div style="font-family: Calibri, Arial, Helvetica, sans-serif; font-size: 12pt; color: rgb(0, 0, 0);">
回复内容
</div>
<div id="appendonsend"></div>
<div style="font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0)">
<b style="color: rgb(50, 49, 48); font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, system-ui, Roboto, "Helvetica Neue", sans-serif; background-color: rgb(255, 255, 255)">content1</b><span
style="color: rgb(50, 49, 48); font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, system-ui, Roboto, "Helvetica Neue", sans-serif; background-color: rgb(255, 255, 255); display: inline !important"></span>
<div style="margin: 0px; font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, system-ui, Roboto, "Helvetica Neue", sans-serif; color: rgb(50, 49, 48); background-color: rgb(255, 255, 255)">
<i><u style="background-color: rgb(255, 0, 0)">content2</u></i></div>
<br>
</div>
<hr tabindex="-1" style="display:inline-block; inline-size:98%">
<div id="divRplyFwdMsg" dir="ltr"><font face="Calibri, sans-serif" color="#000000" style="font-size:11pt"><b>From:</b>
冯伟 <felixfw1111@gmail.com><br>
<b>Sent:</b> Tuesday, July 2, 2019 5:43 PM<br>
<b>To:</b> felixfw1111@hotmail.com<br>
<b>Subject:</b> gmail to hotmail</font>
<div> </div>
</div>
<div>
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb(255,0,0)">content2</u></i></div>
</div>
</div>
</body>
</html>
`;
const icloud = `
<html>
<body>
<div>回复内容</div>
<div>
<meta charset="utf-8">
<blockquote type="cite"
style="padding-block: 0; padding-inline: 12px; border-inline-start: 2px solid #003399; margin: 0px; color: #003399; font-family: SFNSText, 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 300; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; text-decoration-style: initial; text-decoration-color: initial;"
data-mce-style="padding-block: 0; padding-inline: 12px; border-inline-start: 2px solid #003399; margin: 0px; color: #003399; font-family: SFNSText, 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 15px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 300; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: #ffffff; text-decoration-style: initial; text-decoration-color: initial;">
<div class="msg-quote">
<div dir="ltr"><b>content1</b>
<div><i><u data-mce-style="background-color: #ff0000;" style="background-color: rgb(255, 0, 0);">content2</u></i>
</div>
</div>
</div>
</blockquote>
</div>
<div><br>2019年7月2日 上午2:59,冯伟 <felixfw1111@gmail.com> 写道:<br><br></div>
<div>
<blockquote type="cite">
<div class="msg-quote">
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color: #ff0000;"
data-mce-style="background-color: #ff0000;">content2</u></i></div>
</div>
</div>
</blockquote>
</div>
<audio controls="controls" style="display: none;"></audio>
</body>
</html>
`;
const netease = `
回复内容<br>content1<br>content2<br><br>At 2019-07-04 11:20:38, "冯伟" <felixfw1111@gmail.com> wrote:<br>
<blockquote id="isReplyContent" style="padding-inline-start: 1ex; margin-block: 0; margin-inline: 0.8ex 0; border-inline-start: #ccc 1px solid">
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb(255,0,0)">content2</u></i></div>
</div>
</blockquote><br><br><span title="neteasefooter"><p> </p></span>
`;
const outlook2 = `
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<style type="text/css" style="display:none;"> P {
margin-block-start: 0;
margin-block-end: 0;
} </style>
</head>
<body dir="ltr">
<div style="font-family: Calibri, Arial, Helvetica, sans-serif; font-size: 12pt; color: rgb(0, 0, 0);">
回复内容
</div>
<div id="appendonsend"></div>
<div style="font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0)">
<b style="color: rgb(50, 49, 48); font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, system-ui, Roboto, "Helvetica Neue", sans-serif; background-color: rgb(255, 255, 255)">content1</b><span
style="color: rgb(50, 49, 48); font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, system-ui, Roboto, "Helvetica Neue", sans-serif; background-color: rgb(255, 255, 255); display: inline !important"></span>
<div style="margin: 0px; font-family: "Segoe UI", "Segoe UI Web (West European)", "Segoe UI", -apple-system, system-ui, Roboto, "Helvetica Neue", sans-serif; color: rgb(50, 49, 48); background-color: rgb(255, 255, 255)">
<i><u style="background-color: rgb(255, 0, 0)">content2</u></i></div>
<br>
</div>
<hr tabindex="-1" style="display:inline-block; inline-size:98%">
<div id="divRplyFwdMsg" dir="ltr"><font face="Calibri, sans-serif" color="#000000" style="font-size:11pt"><b>From:</b>
冯伟 <felixfw1111@gmail.com><br>
<b>Sent:</b> Tuesday, July 2, 2019 5:43 PM<br>
<b>To:</b> felixfw1111@hotmail.com<br>
<b>Subject:</b> gmail to hotmail</font>
<div> </div>
</div>
<div>
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb(255,0,0)">content2</u></i></div>
</div>
</div>
</body>
</html>
`;
const proton2 = `
<div>回复内容<br></div>
<blockquote type="cite" class="protonmail_quote">
<div dir="ltr">
<div><b>content1</b><br></div>
</div>
</blockquote>
<div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty"><br></div>
<div class="protonmail_signature_block-proton">Sent with <a href="https://proton.me/?utm_campaign=ww-all-2a-mail-pmm_mail-protonmail_signature&utm_source=proton_users&utm_medium=cta&utm_content=sent_with_protonmail_secure_emailttps://proton.me"
target="_blank">ProtonMail</a> Secure Email.<br></div>
</div>
<div><br></div>
<div>${ORIGINAL_MESSAGE}<br></div>
<div> 星期二, 七月 2, 2019 6:09 晚上,冯伟 <felixfw1111@gmail.com> 来信:<br></div>
<div><br></div>
<blockquote class="protonmail_quote" type="cite">
<div dir="ltr">
<div><b>content1</b><br></div>
<div><i><u style="background-color:rgb(255,0,0)">content2</u></i><br></div>
</div>
</blockquote>
<div><br></div>
`;
const sina = `
回复内容<br />content1<br />content2<br />
<div id="origbody">
<div style="background: #f2f2f2;">----- 原始邮件 -----<br />发件人:冯伟 <felixfw1111@gmail.com><br />收件人:felixfw1111@sina.com<br />主题:gmail
to sina<br />日期:2019年07月04日 11点27分<br /></div>
<br />
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb(255,0,0)">content2</u></i></div>
</div>
</div>
`;
const tencent = `
<font color="#800000" face="幼圆">回复内容</font>
<div><b style="font-family: "lucida Grande", Verdana;">content1</b>
<div style="font-family: "lucida Grande", Verdana;"><i><u style="background-color: rgb(255, 0, 0);">contnet2</u></i>
</div>
</div>
<div><br></div>
<div><br></div>
<div style="font-size: 12px;font-family: Arial Narrow;padding-block: 2px; padding-inline: 0;">------------------ 原始邮件 ------------------</div>
<div style="font-size: 12px;background:#efefef;padding:8px;">
<div><b>发件人:</b> "felixfw1111"<felixfw1111@gmail.com>;</div>
<div><b>发送时间:</b> 2019年7月4日(星期四) 中午11:18</div>
<div><b>收件人:</b> "IT贫民"<758185812@qq.com>;</div>
<div><b>主题:</b> gmail to tencent</div>
</div>
<div><br></div>
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb(255,0,0)">contnet2</u></i></div>
</div>
<style type="text/css">.qmbox style, .qmbox script, .qmbox head, .qmbox link, .qmbox meta {
display: none !important;
}</style>
`;
const yahoo = `
<html>
<head></head>
<body>
<div class="ydp4ec1323dyahoo-style-wrap"
style="font-family:Helvetica Neue, Helvetica, Arial, sans-serif;font-size:16px;">
<div></div>
<div><br></div>
<div dir="ltr" data-setdir="false">回复内容</div>
<div dir="ltr" data-setdir="false">
<div>
<div data-testid="message-view-body" class="ydp7263f265I_52qC ydp7263f265D_FY">
<div class="ydp7263f265msg-body ydp7263f265P_wpofO ydp7263f265iy_A"
data-testid="message-view-body-content">
<div class="ydp7263f265jb_0 ydp7263f265X_6MGW ydp7263f265N_6Fd5">
<div id="ydp7263f265yiv3306508764">
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color: rgb(255, 0, 0);">content2</u></i></div>
</div>
</div>
</div>
</div>
<div class="ydp7263f265jb_0 ydp7263f265X_6MGW ydp7263f265N_6Fd5"></div>
</div>
<div class="ydp7263f265H_7jIs ydp7263f265D_F ydp7263f265ab_C ydp7263f265Q_69H5 ydp7263f265E_36RhU"
data-testid="toolbar-hover-area">
<div class="ydp7263f265D_F ydp7263f265W_6D6F ydp7263f265r_BN ydp7263f265gl_C"
data-testid="card-toolbar"
style="inline-size: 903.406px;"></div>
</div>
</div>
<br></div>
</div>
<div id="yahoo_quoted_2158811873" class="yahoo_quoted">
<div style="font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;font-size:13px;color:#26282a;">
<div>
冯伟 (<felixfw1111@gmail.com>) 在 2019年7月2日星期二 下午05:48:53 [GMT+8] 寫道:
</div>
<div><br></div>
<div><br></div>
<div>
<div id="yiv3306508764">
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb(255,0,0);">content2</u></i></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
`;
const yandex2 = `
<div>回复内容</div>
<div>
<b style="background-color:rgb( 255 , 255 , 255 );color:rgb( 0 , 0 , 0 );font-family:'arial' , sans-serif;font-size:15px;font-style:normal;text-decoration-style:initial;text-transform:none;white-space:normal;word-spacing:0px">content1</b>
<div style="background-color:rgb( 255 , 255 , 255 );color:rgb( 0 , 0 , 0 );font-family:'arial' , sans-serif;font-size:15px;font-style:normal;font-weight:400;text-decoration-style:initial;text-transform:none;white-space:normal;word-spacing:0px">
<i><u style="background-color:rgb( 255 , 0 , 0 )">content2</u></i></div>
</div>
<div><br /></div>
<div><br /></div>
<div>03.07.2019, 10:27, "冯伟" <felixfw1111@gmail.com>:</div>
<blockquote>
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb( 255 , 0 , 0 )">content2</u></i></div>
</div>
</blockquote>
`;
const zoho = `
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="Content-Type">
</head>
<body>
<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt;">
<div>回复内容<br></div>
<div class="zmail_extra" style="">
<blockquote style="border-inline-start: 1px solid rgb(204, 204, 204); padding-inline-start: 6px; margin-block: 0; margin-inline: 5px 0;">
<div>
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb(255,0,0);">content2</u></i><br></div>
</div>
</div>
</blockquote>
</div>
<br>
<div id="Zm-_Id_-Sgn"><p style=""><span class="colour" style="color:rgb(42, 42, 42)">使用<a target="_blank"
href="https://www.zoho.com.cn/mail/"
style="color:#598fde;">Zoho Mail</a>发送</span><br></p></div>
<br>
<div style="" class="zmail_extra"><br>
<div id="Zm-_Id_-Sgn1">---- 在 星期二, 02 七月 2019 17:55:32 +0800 <b>冯伟 <felixfw1111@gmail.com></b> 撰写 ----<br>
</div>
<br>
<blockquote style="border-inline-start: 1px solid rgb(204, 204, 204); padding-inline-start: 6px; margin-block: 0; margin-inline: 5px 0;">
<div>
<div dir="ltr"><b>content1</b>
<div><i><u style="background-color:rgb(255,0,0);">content2</u></i><br></div>
</div>
</div>
</blockquote>
</div>
<div><br></div>
</div>
<br></body>
</html>
`;
export default {
proton1,
proton2,
gmail1,
gmail2,
gmail3,
gmail4,
gmx,
android,
aol1,
aol2,
icloud, // multiple same level blockquote
netease,
sina,
thunderbird,
yahoo,
zoho,
};
export const unsuported /* yet? */ = {
comcast, // hr
hotmail1, // almost nothing
hotmail2, // hr
hotmail3, // hr
outlook1, // ??
outlook2, // hr
outlook2003, // hr
outlook2007, // almost nothing
outlook2010, // almost nothing
sparrow, // really exists?
tencent, // text separator + not including
windows_mail, // almost nothing
yandex1, // only blockquote
yandex2, // only blockquote
};
| 3,897
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/__fixtures__/messageHead.fixtures.ts
|
const baseEmail = `
<html>
<head>
<style type="text/css">a {padding:0;}</style>
</head>
<body>Test email</body>
</html>
`;
export default {
baseEmail,
};
| 3,898
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/message/__snapshots__/messageSignature.test.ts.snap
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action -1, isAfter false 1`] = `
"<div><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action -1, isAfter true 1`] = `
"<p>test</p><div><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 0, isAfter false 1`] = `
"<div><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 0, isAfter true 1`] = `
"<p>test</p><div><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 1, isAfter false 1`] = `
"<div><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 1, isAfter true 1`] = `
"<p>test</p><div><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 2, isAfter false 1`] = `
"<div><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature false, action 2, isAfter true 1`] = `
"<p>test</p><div><br></div>
<div class="protonmail_signature_block protonmail_signature_block-empty">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action -1, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action -1, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 0, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 0, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 1, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 1, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 2, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature false, userSignature true, action 2, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div class="protonmail_signature_block-proton protonmail_signature_block-empty">
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action -1, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action -1, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 0, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 0, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 1, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 1, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 2, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature false, action 2, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user protonmail_signature_block-empty">
</div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action -1, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action -1, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 0, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 0, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 1, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 1, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 2, isAfter false 1`] = `
"<div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div><p>test</p>"
`;
exports[`signature insertSignature snapshots should match with protonSignature true, userSignature true, action 2, isAfter true 1`] = `
"<p>test</p><div><br></div><div><br></div>
<div class="protonmail_signature_block">
<div class="protonmail_signature_block-user">
<br><strong>>signature</strong>
</div>
<div><br></div>
<div class="protonmail_signature_block-proton">
Sent with <a target="_blank" href="https://proton.me/">Proton Mail</a> secure email.
</div>
</div>
<div><br></div>"
`;
| 3,899
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.