Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ export class ComposeDraftModule extends ViewModule<ComposeView> {
};

private fillAndRenderDraftHeaders = async (decoded: MimeContent) => {
await this.view.recipientsModule.addRecipientsAndShowPreview({ to: decoded.to, cc: decoded.cc, bcc: decoded.bcc });
this.view.recipientsModule.addRecipientsAndShowPreview({ to: decoded.to, cc: decoded.cc, bcc: decoded.bcc });
if (decoded.from) {
this.view.S.now('input_from').val(decoded.from);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ class ComposerNotReadyError extends ComposerUserError { }
export class ComposerResetBtnTrigger extends Error { }

export const PUBKEY_LOOKUP_RESULT_FAIL: 'fail' = 'fail';
export const PUBKEY_LOOKUP_RESULT_WRONG: 'wrong' = 'wrong';

export class ComposeErrModule extends ViewModule<ComposeView> {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

'use strict';

import { NewMsgData, RecipientElement } from './compose-types.js';
import { NewMsgData, ValidRecipientElement } from './compose-types.js';
import { CursorEvent, SquireEditor, WillPasteEvent } from '../../../types/squire.js';

import { Catch } from '../../../js/common/platform/catch.js';
import { Recipients } from '../../../js/common/api/email-provider/email-provider-api.js';
import { ParsedRecipients } from '../../../js/common/api/email-provider/email-provider-api.js';
import { Str } from '../../../js/common/core/common.js';
import { Xss } from '../../../js/common/platform/xss.js';
import { ViewModule } from '../../../js/common/view-module.js';
Expand Down Expand Up @@ -61,8 +61,7 @@ export class ComposeInputModule extends ViewModule<ComposeView> {
};

public extractAll = (): NewMsgData => {
const recipientElements = this.view.recipientsModule.getRecipients();
const recipients = this.mapRecipients(recipientElements);
const recipients = this.mapRecipients(this.view.recipientsModule.getValidRecipients());
const subject = this.view.isReplyBox && this.view.replyParams ? this.view.replyParams.subject : String($('#input_subject').val() || '');
const plaintext = this.view.inputModule.extract('text', 'input_text');
const plainhtml = this.view.inputModule.extract('html', 'input_text');
Expand Down Expand Up @@ -212,18 +211,18 @@ export class ComposeInputModule extends ViewModule<ComposeView> {
this.view.sizeModule.setInputTextHeightManuallyIfNeeded();
};

private mapRecipients = (recipients: RecipientElement[]) => {
const result: Recipients = { to: [], cc: [], bcc: [] };
private mapRecipients = (recipients: ValidRecipientElement[]): ParsedRecipients => {
const result: ParsedRecipients = { to: [], cc: [], bcc: [] };
for (const recipient of recipients) {
switch (recipient.sendingType) {
case "to":
result.to!.push(recipient.email);
result.to!.push({ email: recipient.email, name: recipient.name });
break;
case "cc":
result.cc!.push(recipient.email);
result.cc!.push({ email: recipient.email, name: recipient.name });
break;
case "bcc":
result.bcc!.push(recipient.email);
result.bcc!.push({ email: recipient.email, name: recipient.name });
break;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ export class ComposeMyPubkeyModule extends ViewModule<ComposeView> {
return;
}
const myDomain = Str.getDomainFromEmailAddress(senderEmail);
const foreignRecipients = this.view.recipientsModule.getRecipients().map(r => r.email)
.filter(Boolean)
const foreignRecipients = this.view.recipientsModule.getValidRecipients().map(r => r.email)
.filter(email => myDomain !== Str.getDomainFromEmailAddress(email));
if (foreignRecipients.length > 0) {
if (!Array.isArray(cached)) {
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class ComposeRenderModule extends ViewModule<ComposeView> {
} else {
this.view.S.cached('body').css('overflow', 'hidden'); // do not enable this for replies or automatic resize won't work
await this.renderComposeTable();
await this.view.recipientsModule.setEmailsPreview(this.view.recipientsModule.getRecipients());
this.view.recipientsModule.setEmailsPreview();
}
this.view.sendBtnModule.resetSendBtn();
await this.view.sendBtnModule.popover.render();
Expand All @@ -70,7 +70,7 @@ export class ComposeRenderModule extends ViewModule<ComposeView> {
public renderReplyMsgComposeTable = async (): Promise<void> => {
this.view.S.cached('prompt').css({ display: 'none' });
this.view.recipientsModule.showHideCcAndBccInputsIfNeeded();
await this.view.recipientsModule.setEmailsPreview(this.view.recipientsModule.getRecipients());
this.view.recipientsModule.setEmailsPreview();
await this.renderComposeTable();
if (this.view.replyParams) {
const thread = await this.view.emailProvider.threadGet(this.view.threadId, 'metadata');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ import { ComposeSendBtnPopoverModule } from './compose-send-btn-popover-module.j
import { GeneralMailFormatter } from './formatters/general-mail-formatter.js';
import { GmailRes } from '../../../js/common/api/email-provider/gmail/gmail-parser.js';
import { KeyInfo } from '../../../js/common/core/crypto/key.js';
import { SendBtnTexts } from './compose-types.js';
import { getUniqueRecipientEmails, SendBtnTexts } from './compose-types.js';
import { SendableMsg } from '../../../js/common/api/email-provider/sendable-msg.js';
import { Str } from '../../../js/common/core/common.js';
import { Ui } from '../../../js/common/browser/ui.js';
import { Xss } from '../../../js/common/platform/xss.js';
import { ViewModule } from '../../../js/common/view-module.js';
import { ComposeView } from '../compose.js';
import { AcctStore } from '../../../js/common/platform/store/acct-store.js';
import { ContactStore } from '../../../js/common/platform/store/contact-store.js';
import { AcctStore } from '../../../js/common/platform/store/acct-store.js';
import { Str } from '../../../js/common/core/common.js';

export class ComposeSendBtnModule extends ViewModule<ComposeView> {

Expand Down Expand Up @@ -112,7 +112,8 @@ export class ComposeSendBtnModule extends ViewModule<ComposeView> {
this.view.S.cached('send_btn_note').text('');
const newMsgData = this.view.inputModule.extractAll();
await this.view.errModule.throwIfFormValsInvalid(newMsgData);
await ContactStore.update(undefined, Array.prototype.concat.apply([], Object.values(newMsgData.recipients)), { lastUse: Date.now() });
const emails = getUniqueRecipientEmails(newMsgData.recipients);
await ContactStore.update(undefined, emails, { lastUse: Date.now() });
const msgObj = await GeneralMailFormatter.processNewMsg(this.view, newMsgData);
if (msgObj) {
await this.finalizeSendableMsg(msgObj);
Expand Down Expand Up @@ -146,7 +147,7 @@ export class ComposeSendBtnModule extends ViewModule<ComposeView> {
if (this.view.myPubkeyModule.shouldAttach() && senderKi) { // todo: report on undefined?
msg.attachments.push(Attachment.keyinfoAsPubkeyAttachment(senderKi));
}
await this.addNamesToMsg(msg);
msg.from = await this.formatSenderEmailAsMimeString(msg.from);
};

private extractInlineImagesToAttachments = (html: string) => {
Expand Down Expand Up @@ -224,30 +225,24 @@ export class ComposeSendBtnModule extends ViewModule<ComposeView> {
}
};

private addNamesToMsg = async (msg: SendableMsg): Promise<void> => {
private formatSenderEmailAsMimeString = async (email: string): Promise<string> => {
const parsedEmail = Str.parseEmail(email);
if (!parsedEmail.email) {
throw new Error(`Recipient email ${email} is not valid`);
}
if (parsedEmail.name) {
return Str.formatEmailWithOptionalName({ email: parsedEmail.email, name: parsedEmail.name });
}
const { sendAs } = await AcctStore.get(this.view.acctEmail, ['sendAs']);
const addNameToEmail = async (emails: string[]): Promise<string[]> => {
return await Promise.all(emails.map(async email => {
let name: string | undefined;
if (sendAs && sendAs[email]?.name) {
name = sendAs[email].name!;
} else {
const [contact] = await ContactStore.get(undefined, [email]);
if (contact?.name) {
name = contact.name;
}
}
const fixedEmail = Str.parseEmail(email).email;
if (!fixedEmail) {
throw new Error(`Recipient email ${email} is not valid`);
}
return name ? `${Str.rmSpecialCharsKeepUtf(name, 'ALLOW-SOME')} <${fixedEmail}>` : fixedEmail;
}));
};
msg.recipients.to = await addNameToEmail(msg.recipients.to || []);
msg.recipients.cc = await addNameToEmail(msg.recipients.cc || []);
msg.recipients.bcc = await addNameToEmail(msg.recipients.bcc || []);
msg.from = (await addNameToEmail([msg.from]))[0];
let name: string | undefined;
if (sendAs && sendAs[email]?.name) {
name = sendAs[email].name!;
} else {
const [contact] = await ContactStore.get(undefined, [email]);
if (contact?.name) {
name = contact.name;
}
}
return Str.formatEmailWithOptionalName({ email: parsedEmail.email, name });
};

}
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ export class ComposeSenderModule extends ViewModule<ComposeView> {
};

private actionInputFromChangeHanlder = async () => {
await this.view.recipientsModule.reEvaluateRecipients(this.view.recipientsModule.getRecipients());
await this.view.recipientsModule.setEmailsPreview(this.view.recipientsModule.getRecipients());
await this.view.recipientsModule.reEvaluateRecipients(this.view.recipientsModule.getValidRecipients());
this.view.footerModule.onFooterUpdated(await this.view.footerModule.getFooterFromStorage(this.view.senderModule.getSender()));
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export class ComposeSizeModule extends ViewModule<ComposeView> {
this.resizeComposeBox();
this.setInputTextHeightManuallyIfNeeded(true);
if (this.view.S.cached('recipients_placeholder').is(':visible')) {
await this.view.recipientsModule.setEmailsPreview(this.view.recipientsModule.getRecipients());
this.view.recipientsModule.setEmailsPreview();
}
};

Expand Down Expand Up @@ -156,7 +156,7 @@ export class ComposeSizeModule extends ViewModule<ComposeView> {
this.view.S.cached('icon_popout').attr('src', '/img/svgs/maximize.svg').attr('title', 'Full screen');
}
if (this.view.S.cached('recipients_placeholder').is(':visible')) {
await this.view.recipientsModule.setEmailsPreview(this.view.recipientsModule.getRecipients());
this.view.recipientsModule.setEmailsPreview();
}
this.composeWindowIsMaximized = !this.composeWindowIsMaximized;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
'use strict';

import { BrowserMsg } from '../../../js/common/browser/browser-msg.js';
import { KeyInfo, KeyUtil, Key, PubkeyInfo, PubkeyResult } from '../../../js/common/core/crypto/key.js';
import { KeyInfo, KeyUtil, Key, PubkeyInfo, PubkeyResult, ContactInfoWithSortedPubkeys } from '../../../js/common/core/crypto/key.js';
import { ApiErr } from '../../../js/common/api/shared/api-error.js';
import { Assert } from '../../../js/common/assert.js';
import { Catch, UnreportableError } from '../../../js/common/platform/catch.js';
Expand Down Expand Up @@ -133,7 +133,7 @@ export class ComposeStorageModule extends ViewModule<ComposeView> {
*/
public getUpToDatePubkeys = async (
email: string
): Promise<PubkeyInfo[] | "fail"> => {
): Promise<ContactInfoWithSortedPubkeys | "fail" | undefined> => {
this.view.errModule.debug(`getUpToDatePubkeys.email(${email})`);
const storedContact = await ContactStore.getOneWithAllPubkeys(undefined, email);
this.view.errModule.debug(`getUpToDatePubkeys.storedContact.sortedPubkeys.length(${storedContact?.sortedPubkeys.length})`);
Expand All @@ -145,7 +145,7 @@ export class ComposeStorageModule extends ViewModule<ComposeView> {
// an async method to update them
this.updateLocalPubkeysFromRemote(storedContact.sortedPubkeys, email)
.catch(ApiErr.reportIfSignificant);
return storedContact.sortedPubkeys;
return storedContact;
}
this.view.errModule.debug(`getUpToDatePubkeys.bestKey not usable, refreshing sync`);
try { // no valid keys found, query synchronously, then return result
Expand All @@ -157,7 +157,7 @@ export class ComposeStorageModule extends ViewModule<ComposeView> {
const updatedContact = await ContactStore.getOneWithAllPubkeys(undefined, email);
this.view.errModule.debug(`getUpToDatePubkeys.updatedContact.sortedPubkeys.length(${updatedContact?.sortedPubkeys.length})`);
this.view.errModule.debug(`getUpToDatePubkeys.updatedContact(${updatedContact})`);
return updatedContact?.sortedPubkeys ?? [];
return updatedContact;
};

/**
Expand All @@ -175,12 +175,9 @@ export class ComposeStorageModule extends ViewModule<ComposeView> {
}
try {
const lookupResult = await this.view.pubLookup.lookupEmail(email);
if (await compareAndSavePubkeysToStorage(email, lookupResult.pubkeys, storedPubkeys)) {
if (await compareAndSavePubkeysToStorage({ email, name }, lookupResult.pubkeys, storedPubkeys)) {
await this.view.recipientsModule.reRenderRecipientFor(email);
}
if (name) { // update name
await ContactStore.update(undefined, email, { name });
}
} catch (e) {
if (!ApiErr.isNetErr(e) && !ApiErr.isServerErr(e)) {
Catch.reportErr(e);
Expand Down
21 changes: 17 additions & 4 deletions extension/chrome/elements/compose-modules/compose-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
'use strict';

import { RecipientType } from '../../../js/common/api/shared/api.js';
import { Recipients } from '../../../js/common/api/email-provider/email-provider-api.js';
import { ParsedRecipients } from '../../../js/common/api/email-provider/email-provider-api.js';
import { KeyInfo, PubkeyResult } from '../../../js/common/core/crypto/key.js';
import { EmailParts, Value } from '../../../js/common/core/common.js';

export enum RecipientStatus {
EVALUATING,
Expand All @@ -16,15 +17,23 @@ export enum RecipientStatus {
FAILED
}

export interface RecipientElement {
email: string;
interface RecipientElementBase {
sendingType: RecipientType;
element: HTMLElement;
id: string;
status: RecipientStatus;
evaluating?: Promise<void>;
}

export interface RecipientElement extends RecipientElementBase {
email?: string;
name?: string;
invalid?: string;
}

export interface ValidRecipientElement extends RecipientElementBase, EmailParts {
}

export type MessageToReplyOrForward = {
headers: {
references: string,
Expand All @@ -42,7 +51,7 @@ export type CollectKeysResult = { pubkeys: PubkeyResult[], emailsWithoutPubkeys:
export type PopoverOpt = 'encrypt' | 'sign' | 'richtext';
export type PopoverChoices = { [key in PopoverOpt]: boolean };

export type NewMsgData = { recipients: Recipients, subject: string, plaintext: string, plainhtml: string, pwd: string | undefined, from: string };
export type NewMsgData = { recipients: ParsedRecipients, subject: string, plaintext: string, plainhtml: string, pwd: string | undefined, from: string };

export class SendBtnTexts {
public static readonly BTN_ENCRYPT_AND_SEND: string = "Encrypt and Send";
Expand All @@ -52,3 +61,7 @@ export class SendBtnTexts {
public static readonly BTN_WRONG_ENTRY: string = "Re-enter recipient..";
public static readonly BTN_SENDING: string = "Sending..";
}

export const getUniqueRecipientEmails = (recipients: ParsedRecipients) => {
return Value.arr.unique(Object.values(recipients).reduce((a, b) => a.concat(b), []).filter(x => x.email).map(x => x.email));
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { BaseMailFormatter } from './base-mail-formatter.js';
import { ComposerResetBtnTrigger } from '../compose-err-module.js';
import { Mime, SendableMsgBody } from '../../../../js/common/core/mime.js';
import { NewMsgData } from '../compose-types.js';
import { getUniqueRecipientEmails, NewMsgData } from '../compose-types.js';
import { Str, Url, Value } from '../../../../js/common/core/common.js';
import { ApiErr } from '../../../../js/common/api/shared/api-error.js';
import { Attachment } from '../../../../js/common/core/attachment.js';
Expand Down Expand Up @@ -157,7 +157,7 @@ export class EncryptedMsgMailFormatter extends BaseMailFormatter {
private getPwdMsgSendableBodyWithOnlineReplyMsgToken = async (
authInfo: FcUuidAuth, newMsgData: NewMsgData
): Promise<{ bodyWithReplyToken: SendableMsgBody, replyToken: string }> => {
const recipients = Array.prototype.concat.apply([], Object.values(newMsgData.recipients));
const recipients = getUniqueRecipientEmails(newMsgData.recipients);
try {
const response = await this.view.acctServer.messageToken(authInfo);
const infoDiv = Ui.e('div', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import { EncryptedMsgMailFormatter } from './encrypted-mail-msg-formatter.js';
import { Key, KeyInfo } from "../../../../js/common/core/crypto/key.js";
import { NewMsgData } from "../compose-types.js";
import { getUniqueRecipientEmails, NewMsgData } from "../compose-types.js";
import { PlainMsgMailFormatter } from './plain-mail-msg-formatter.js';
import { SendableMsg } from '../../../../js/common/api/email-provider/sendable-msg.js';
import { SignedMsgMailFormatter } from './signed-msg-mail-formatter.js';
Expand All @@ -15,7 +15,7 @@ export class GeneralMailFormatter {
// returns undefined in case user cancelled decryption of the signing key
public static processNewMsg = async (view: ComposeView, newMsgData: NewMsgData): Promise<{ msg: SendableMsg, senderKi: KeyInfo | undefined } | undefined> => {
const choices = view.sendBtnModule.popover.choices;
const recipientsEmails = Array.prototype.concat.apply([], Object.values(newMsgData.recipients).filter(arr => !!arr)) as string[];
const recipientsEmails = getUniqueRecipientEmails(newMsgData.recipients);
if (!choices.encrypt && !choices.sign) { // plain
return { senderKi: undefined, msg: await new PlainMsgMailFormatter(view).sendableMsg(newMsgData) };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { BaseMailFormatter } from './base-mail-formatter.js';
import { BrowserWindow } from '../../../../js/common/browser/browser-window.js';
import { Catch } from '../../../../js/common/platform/catch.js';
import { NewMsgData } from '../compose-types.js';
import { getUniqueRecipientEmails, NewMsgData } from '../compose-types.js';
import { Key } from '../../../../js/common/core/crypto/key.js';
import { MsgUtil } from '../../../../js/common/core/crypto/pgp/msg-util.js';
import { SendableMsg } from '../../../../js/common/api/email-provider/sendable-msg.js';
Expand Down Expand Up @@ -40,8 +40,8 @@ export class SignedMsgMailFormatter extends BaseMailFormatter {
// Removing them here will prevent Gmail from screwing up the signature
newMsg.plaintext = newMsg.plaintext.split('\n').map(l => l.replace(/\s+$/g, '')).join('\n').trim();
const signedData = await MsgUtil.sign(signingPrv, newMsg.plaintext);
const allContacts = [...newMsg.recipients.to || [], ...newMsg.recipients.cc || [], ...newMsg.recipients.bcc || []];
ContactStore.update(undefined, allContacts, { lastUse: Date.now() }).catch(Catch.reportErr);
const recipients = getUniqueRecipientEmails(newMsg.recipients);
ContactStore.update(undefined, recipients, { lastUse: Date.now() }).catch(Catch.reportErr);
return await SendableMsg.createInlineArmored(this.acctEmail, this.headers(newMsg), signedData, attachments);
}
// pgp/mime detached signature - it must be signed later, while being mime-encoded
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class BackupManualActionModule extends ViewModule<BackupView> {
public doBackupOnEmailProvider = async (armoredKey: string) => {
const emailMsg = String(await $.get({ url: '/chrome/emails/email_intro.template.htm', dataType: 'html' }));
const emailAttachments = [this.asBackupFile(armoredKey)];
const headers = { from: this.view.acctEmail, recipients: { to: [this.view.acctEmail] }, subject: GMAIL_RECOVERY_EMAIL_SUBJECTS[0] };
const headers = { from: this.view.acctEmail, recipients: { to: [{ email: this.view.acctEmail }] }, subject: GMAIL_RECOVERY_EMAIL_SUBJECTS[0] };
const msg = await SendableMsg.createPlain(this.view.acctEmail, headers, { 'text/html': emailMsg }, emailAttachments);
if (this.view.emailProvider === 'gmail') {
return await this.view.gmail.msgSend(msg);
Expand Down
Loading