Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore(email-service): Hexify get-threads endpoint (#1737)

Evan Hutnike395a594cb3c
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.ts
index 1c0abc9dd6..e5bd486786 100644
--- a/infra/stacks/email-service/index.ts
+++ b/infra/stacks/email-service/index.ts
@@ -344,7 +344,7 @@ emailAttachmentBucket.attachCloudfrontPolicy({
const containerEnvVars = [
{
name: 'RUST_LOG',
- value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${stack === 'prod' ? 'debug' : 'debug'},pubsub_workers=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info`,
+ value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${stack === 'prod' ? 'debug' : 'debug'},entity_access=${stack === 'prod' ? 'debug' : 'debug'},pubsub_workers=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info`,
},
{
name: 'ENVIRONMENT',
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index d355bf7452..d43dc93e7d 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -52,7 +52,7 @@ import {
} from '@queries/email/thread';
import type {
MessageToSendDbId,
- MessageWithBodyReplyless,
+ ApiMessage,
} from '@service-email/generated/schemas';
import { useEmail, useUserId } from '@core/context/user';
import { Button } from '@ui/components/Button';
@@ -313,11 +313,11 @@ type UndoReplySnapshot = {
let undoReplySnapshot: UndoReplySnapshot | null = null;
export function BaseInput(props: {
- replyingTo: Accessor<MessageWithBodyReplyless | undefined>;
+ replyingTo: Accessor<ApiMessage | undefined>;
// TODO: Remove `newMessage` props. It's not used...
newMessage?: boolean;
isEditingExisting?: boolean;
- draft?: MessageWithBodyReplyless;
+ draft?: ApiMessage;
preloadedBody?: string;
preloadedHtml?: string;
sideEffectOnSend?: (newMessageId: MessageToSendDbId | null) => void;
diff --git a/js/app/packages/block-email/component/CollapsedMessage.tsx b/js/app/packages/block-email/component/CollapsedMessage.tsx
index daf0a27bd6..413c6a23dc 100644
--- a/js/app/packages/block-email/component/CollapsedMessage.tsx
+++ b/js/app/packages/block-email/component/CollapsedMessage.tsx
@@ -1,6 +1,6 @@
import { BozzyBracket } from '@core/component/BozzyBracket';
import { UserIcon } from '@core/component/UserIcon';
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
import { useEmail, useUserId } from '@core/context/user';
import { createMemo, createSignal } from 'solid-js';
import {
@@ -10,7 +10,7 @@ import {
import { formatShortDate } from './EmailMessageTopBar';
interface CollapsedMessageProps {
- message: MessageWithBodyReplyless;
+ message: ApiMessage;
isFocused: boolean;
isFirstMessage: boolean;
onClick: () => void;
diff --git a/js/app/packages/block-email/component/Email.tsx b/js/app/packages/block-email/component/Email.tsx
index b0bb4cba6d..43d4b53e32 100644
--- a/js/app/packages/block-email/component/Email.tsx
+++ b/js/app/packages/block-email/component/Email.tsx
@@ -9,7 +9,7 @@ import {
blockElementSignal,
blockHotkeyScopeSignal,
} from '@core/signal/blockElement';
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
import { createCallback } from '@solid-primitives/rootless';
import { useUserContext } from '@core/context/user';
import {
@@ -92,7 +92,7 @@ function EmailContent(props: EmailViewProps) {
// Check if message exists in current batch
const messageExists = messages.some(
- (m: MessageWithBodyReplyless) => m.db_id === targetMessageId
+ (m: ApiMessage) => m.db_id === targetMessageId
);
if (messageExists) return true;
diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsx
index 7695728320..91dcb9c9e4 100644
--- a/js/app/packages/block-email/component/EmailContext.tsx
+++ b/js/app/packages/block-email/component/EmailContext.tsx
@@ -26,9 +26,9 @@ import {
import { emailKeys } from '@queries/email/keys';
import { queryClient } from '@queries/client';
import type {
- APIThread,
+ ApiThread,
ContactInfo,
- MessageWithBodyReplyless,
+ ApiMessage,
} from '@service-email/generated/schemas';
import { useSearchParams } from '@solidjs/router';
import {
@@ -69,16 +69,14 @@ export type EmailContextValues = {
onRecipientsChange: (items: EmailRecipient[]) => void;
drafts: {
- getDraftForMessage: (
- messageDbID: string
- ) => MessageWithBodyReplyless | undefined;
+ getDraftForMessage: (messageDbID: string) => ApiMessage | undefined;
deleteDraftForMessage: (messageDbID: string) => void;
initialDraftsSettled: Accessor<boolean>;
};
messages: {
- unfiltered: Accessor<MessageWithBodyReplyless[]>;
- list: Accessor<MessageWithBodyReplyless[]>;
+ unfiltered: Accessor<ApiMessage[]>;
+ list: Accessor<ApiMessage[]>;
targetMessageID: Accessor<string | undefined>;
setTargetMessageID: (id: string | undefined) => void;
focusedID: Accessor<string | undefined>;
@@ -89,7 +87,7 @@ export type EmailContextValues = {
replyingToMessageId: Accessor<string | undefined>;
setReplyingToMessageId: (id: string | undefined) => void;
};
- thread: Accessor<APIThread | undefined>;
+ thread: Accessor<ApiThread | undefined>;
permissions: Accessor<{
type: Permissions;
isOwner: boolean;
@@ -134,7 +132,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
});
const filtered = [];
- const messageDraftMap: Record<string, MessageWithBodyReplyless> = {};
+ const messageDraftMap: Record<string, ApiMessage> = {};
for (const message of messages) {
if (!message.is_draft) {
@@ -212,7 +210,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
});
const [messageDraftMap, setMessageDraftMap] = createStore<
- Record<string, MessageWithBodyReplyless | undefined>
+ Record<string, ApiMessage | undefined>
>({});
const deleteDraftForMessage = (messageID: string) => {
diff --git a/js/app/packages/block-email/component/EmailInput.tsx b/js/app/packages/block-email/component/EmailInput.tsx
index fe5c171446..ec28db3966 100644
--- a/js/app/packages/block-email/component/EmailInput.tsx
+++ b/js/app/packages/block-email/component/EmailInput.tsx
@@ -1,15 +1,15 @@
import { useEmailContext } from '@block-email/component/EmailContext';
import type {
MessageToSendDbId,
- MessageWithBodyReplyless,
+ ApiMessage,
} from '@service-email/generated/schemas';
import { type Accessor, createMemo, type Setter, Show } from 'solid-js';
import { decodeBase64Utf8 } from '../util/decodeBase64';
import { BaseInput } from './BaseInput';
interface EmailInputProps {
- replyingTo: Accessor<MessageWithBodyReplyless | undefined>;
- draft?: MessageWithBodyReplyless;
+ replyingTo: Accessor<ApiMessage | undefined>;
+ draft?: ApiMessage;
setShowReply?: Setter<boolean>;
markdownDomRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
}
diff --git a/js/app/packages/block-email/component/EmailMessageBody.tsx b/js/app/packages/block-email/component/EmailMessageBody.tsx
index 57df803ce6..55fb637252 100644
--- a/js/app/packages/block-email/component/EmailMessageBody.tsx
+++ b/js/app/packages/block-email/component/EmailMessageBody.tsx
@@ -9,7 +9,7 @@ import {
type ThemeColorParams,
} from '@core/email';
import DotsThree from '@icon/light/dots-three-light.svg';
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
import { useEmail } from '@core/context/user';
import {
type Accessor,
@@ -25,7 +25,7 @@ import { themeReactive } from '../../block-theme/signals/themeReactive';
import { themeUpdate } from '../../block-theme/signals/themeSignals';
interface EmailMessageBodyProps {
- message: MessageWithBodyReplyless;
+ message: ApiMessage;
isBodyExpanded: Accessor<boolean>;
setExpandedMessageBody: (id: string) => void;
setFocusedMessageId: (messageID: string | undefined) => void;
diff --git a/js/app/packages/block-email/component/EmailMessageTopBar.tsx b/js/app/packages/block-email/component/EmailMessageTopBar.tsx
index 9b72998b48..f78f03f990 100644
--- a/js/app/packages/block-email/component/EmailMessageTopBar.tsx
+++ b/js/app/packages/block-email/component/EmailMessageTopBar.tsx
@@ -2,7 +2,7 @@ import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';
import { Tooltip } from '@core/component/Tooltip';
import CaretDown from '@icon/regular/caret-down.svg';
import X from '@icon/regular/x.svg';
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
import { useEmail } from '@core/context/user';
import {
type Accessor,
@@ -23,7 +23,7 @@ import { type EmailMessageAction, MessageActions } from './MessageActions';
import type { DateValue } from '@core/util/date';
interface EmailMessageTopBarProps {
- message: MessageWithBodyReplyless;
+ message: ApiMessage;
focused: boolean;
setExpandedBodyId: (id: string, expanded: boolean) => void;
isBodyExpanded: Accessor<boolean>;
@@ -112,7 +112,7 @@ function RecipientRow(props: {
}
function ExpandedHeader(props: {
- message: MessageWithBodyReplyless;
+ message: ApiMessage;
onClose: () => void;
}): JSX.Element {
return (
@@ -154,7 +154,7 @@ function CollapsedHeader(props: {
recipientSummary: string;
isHovering: boolean;
onExpand: () => void;
- message: MessageWithBodyReplyless;
+ message: ApiMessage;
focused: boolean;
setShowReply: Setter<boolean>;
isLastMessage?: boolean;
diff --git a/js/app/packages/block-email/component/MessageActions.tsx b/js/app/packages/block-email/component/MessageActions.tsx
index 383a00f678..4e07021ba4 100644
--- a/js/app/packages/block-email/component/MessageActions.tsx
+++ b/js/app/packages/block-email/component/MessageActions.tsx
@@ -1,7 +1,7 @@
import ArrowBendDoubleUpLeft from '@icon/regular/arrow-bend-double-up-left.svg';
import ArrowBendUpLeft from '@icon/regular/arrow-bend-up-left.svg';
import ArrowBendUpRight from '@icon/regular/arrow-bend-up-right.svg';
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
import { useEmail } from '@core/context/user';
import { Button } from '@ui/components/Button';
import { type Setter, Show } from 'solid-js';
@@ -13,7 +13,7 @@ const EMAIL_MESSAGE_ACTIONS = ['reply', 'reply-all', 'forward'] as const;
export type EmailMessageAction = (typeof EMAIL_MESSAGE_ACTIONS)[number];
export function MessageActions(props: {
- message: MessageWithBodyReplyless;
+ message: ApiMessage;
showActions: boolean;
setShowReply: Setter<boolean>;
isLastMessage?: boolean;
diff --git a/js/app/packages/block-email/component/MessageContainer.tsx b/js/app/packages/block-email/component/MessageContainer.tsx
index bb22ec6207..41a569c021 100644
--- a/js/app/packages/block-email/component/MessageContainer.tsx
+++ b/js/app/packages/block-email/component/MessageContainer.tsx
@@ -16,10 +16,7 @@ import { isErr } from '@core/util/maybeResult';
import { refetchSoupEntity } from '@queries/soup/cache';
import { logger } from '@observability';
import { emailClient } from '@service-email/client';
-import type {
- Attachment,
- MessageWithBodyReplyless,
-} from '@service-email/generated/schemas';
+import type { Attachment, ApiMessage } from '@service-email/generated/schemas';
import { useEmail, useUserId } from '@core/context/user';
import { storageServiceClient } from '@service-storage/client';
import type { FileType } from '@service-storage/generated/schemas/fileType';
@@ -27,7 +24,7 @@ import { createMemo, createSignal, For, Show } from 'solid-js';
import { Portal } from 'solid-js/web';
interface MessageContainerProps {
- message: MessageWithBodyReplyless;
+ message: ApiMessage;
isFirstMessage: boolean;
isLastMessage: boolean;
isFocused: boolean;
diff --git a/js/app/packages/block-email/component/createEmailFormState.ts b/js/app/packages/block-email/component/createEmailFormState.ts
index b664318677..b11582624a 100644
--- a/js/app/packages/block-email/component/createEmailFormState.ts
+++ b/js/app/packages/block-email/component/createEmailFormState.ts
@@ -12,7 +12,7 @@ import {
import type { ReplyType } from '../util/replyType';
import { getSubjectText } from '../util/subjectText';
import type { EmailRecipient } from './EmailContext';
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
export type EmailFormRecipients = {
to: EmailRecipient[];
@@ -43,8 +43,8 @@ export type DraftFormAttachment =
};
export interface EmailFormStateOptions {
- getMessageByID: (id: string) => MessageWithBodyReplyless | undefined;
- getDraftForMessageReply: (id: string) => MessageWithBodyReplyless | undefined;
+ getMessageByID: (id: string) => ApiMessage | undefined;
+ getDraftForMessageReply: (id: string) => ApiMessage | undefined;
onRecipientsChange?: (next: EmailRecipient[]) => void;
}
@@ -88,13 +88,13 @@ export function createEmailFormState(
) {
const userEmail = useEmail();
- let replyingTo: MessageWithBodyReplyless | undefined;
+ let replyingTo: ApiMessage | undefined;
if (purpose?.type === 'replying_to') {
replyingTo = options?.getMessageByID(purpose.messageID);
}
- let draft: MessageWithBodyReplyless | undefined;
+ let draft: ApiMessage | undefined;
if (purpose?.type === 'draft') {
draft = options?.getMessageByID(purpose.messageID);
diff --git a/js/app/packages/block-email/util/emailHotkeys.ts b/js/app/packages/block-email/util/emailHotkeys.ts
index 9592fe0613..291377de52 100644
--- a/js/app/packages/block-email/util/emailHotkeys.ts
+++ b/js/app/packages/block-email/util/emailHotkeys.ts
@@ -1,5 +1,5 @@
import { TOKENS } from '@core/hotkey/tokens';
-import type { Thread } from '@service-email/generated/schemas';
+import type { ApiThread } from '@service-email/generated/schemas';
import { registerHotkey } from 'core/hotkey/hotkeys';
import type { Accessor } from 'solid-js';
@@ -11,7 +11,7 @@ export interface EmailHotkeyHandlers {
export function registerEmailHotkeys(
scopeId: string,
- threadData: Accessor<Thread | undefined>,
+ threadData: Accessor<ApiThread | undefined>,
handlers: EmailHotkeyHandlers
) {
registerHotkey({
diff --git a/js/app/packages/block-email/util/emailUser.ts b/js/app/packages/block-email/util/emailUser.ts
index 12efe8dd83..496dedecb2 100644
--- a/js/app/packages/block-email/util/emailUser.ts
+++ b/js/app/packages/block-email/util/emailUser.ts
@@ -1,11 +1,11 @@
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
import { getFirstName } from './name';
/**
* Check if a message is from the current user
*/
export function isMessageFromCurrentUser(
- message: MessageWithBodyReplyless,
+ message: ApiMessage,
currentUserEmail?: string
): boolean {
if (!currentUserEmail) return false;
@@ -18,7 +18,7 @@ export function isMessageFromCurrentUser(
* Get the sender display name, showing "Me" for the current user
*/
export function getSenderDisplayName(
- message: MessageWithBodyReplyless,
+ message: ApiMessage,
currentUserEmail?: string
): string {
if (isMessageFromCurrentUser(message, currentUserEmail)) {
diff --git a/js/app/packages/block-email/util/prepareEmailBody.ts b/js/app/packages/block-email/util/prepareEmailBody.ts
index 952c726867..8e65817274 100644
--- a/js/app/packages/block-email/util/prepareEmailBody.ts
+++ b/js/app/packages/block-email/util/prepareEmailBody.ts
@@ -10,7 +10,7 @@ import {
type ClassedBlockNode,
type DocumentMentionInfo,
} from '@lexical-core';
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
import {
$createLineBreakNode,
$createParagraphNode,
@@ -38,7 +38,7 @@ export function clearEmailBody(editor: LexicalEditor | undefined) {
}
export const TOGGLE_APPEND_EMAIL_THREAD_COMMAND = createCommand<{
- replyingTo: MessageWithBodyReplyless | undefined;
+ replyingTo: ApiMessage | undefined;
replyType?: ReplyType;
visible: boolean;
}>('TOGGLE_APPEND_EMAIL_THREAD_COMMAND');
@@ -48,7 +48,7 @@ type HeaderDescriptor =
| { kind: 'reply'; text: string };
function buildHeaderDescriptor(
- replyingTo: MessageWithBodyReplyless,
+ replyingTo: ApiMessage,
replyType: ReplyType | undefined
): HeaderDescriptor {
const replyingToDate = replyingTo.internal_date_ts ?? replyingTo.created_at;
@@ -104,7 +104,7 @@ function buildHeaderDescriptor(
}
function $generateHeaderNodes(
- replyingTo: MessageWithBodyReplyless,
+ replyingTo: ApiMessage,
replyType: ReplyType | undefined
): LexicalNode[] {
const descriptor = buildHeaderDescriptor(replyingTo, replyType);
@@ -133,7 +133,7 @@ const REPLYING_TO_ID_ATTRIBUTE = 'data-replying-to-id';
const $appendPreviousEmail = (
editor: LexicalEditor,
- replyingTo: MessageWithBodyReplyless | undefined,
+ replyingTo: ApiMessage | undefined,
replyType: ReplyType | undefined
) => {
if (!replyingTo) return true;
@@ -292,7 +292,7 @@ export async function appendItemsAsMacroMentions(
}
function getAppendedReplyElement(
- replyingTo: MessageWithBodyReplyless,
+ replyingTo: ApiMessage,
replyType: ReplyType | undefined
) {
const wrapper = document.createElement('div');
@@ -451,7 +451,7 @@ export function prepareEmailBody(
// if this argument is provided, we append the message being replied to the html email body
appendReply?: {
replyType: ReplyType | undefined;
- replyingTo: MessageWithBodyReplyless;
+ replyingTo: ApiMessage;
}
): {
bodyHtml: string;
diff --git a/js/app/packages/block-email/util/recipientConversion.ts b/js/app/packages/block-email/util/recipientConversion.ts
index 941845f7bb..eb4704fcfb 100644
--- a/js/app/packages/block-email/util/recipientConversion.ts
+++ b/js/app/packages/block-email/util/recipientConversion.ts
@@ -4,7 +4,7 @@ import {
emailToId,
recipientEntityMapper,
} from '@core/user';
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
import type { EmailRecipient } from '../component/EmailContext';
const extractedContactInfo = (contact: ContactInfo): ExtractedContactInfo => ({
@@ -34,7 +34,7 @@ export const convertContactInfoToEmailRecipient = (
// Note: because of the logic, this works with a reference message that is either the message being replied to, or the draft.
export const getReplyAllRecipients = (
- referenceMessage: MessageWithBodyReplyless | undefined,
+ referenceMessage: ApiMessage | undefined,
userEmail: string
): {
to: EmailRecipient[];
@@ -76,7 +76,7 @@ export const getReplyAllRecipients = (
};
export const getReplyRecipientsFromParent = (
- replyingTo: MessageWithBodyReplyless | undefined,
+ replyingTo: ApiMessage | undefined,
userEmail: string
): {
to: EmailRecipient[];
diff --git a/js/app/packages/block-email/util/replyType.ts b/js/app/packages/block-email/util/replyType.ts
index cf9ce34edd..606b25951e 100644
--- a/js/app/packages/block-email/util/replyType.ts
+++ b/js/app/packages/block-email/util/replyType.ts
@@ -1,10 +1,10 @@
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
export type ReplyType = 'reply' | 'reply-all' | 'forward';
export const getReplyTypeFromDraft: (
- draft: MessageWithBodyReplyless | undefined
-) => ReplyType | undefined = (draft: MessageWithBodyReplyless | undefined) => {
+ draft: ApiMessage | undefined
+) => ReplyType | undefined = (draft: ApiMessage | undefined) => {
if (!draft) {
return undefined;
}
diff --git a/js/app/packages/block-email/util/scrollToMessage.ts b/js/app/packages/block-email/util/scrollToMessage.ts
index dae04d1769..d823d5ead4 100644
--- a/js/app/packages/block-email/util/scrollToMessage.ts
+++ b/js/app/packages/block-email/util/scrollToMessage.ts
@@ -1,4 +1,4 @@
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
/**
* Scrolls to a message by its ID within a messages container
@@ -10,7 +10,7 @@ import type { MessageWithBodyReplyless } from '@service-email/generated/schemas'
*/
export function scrollToMessage(
messageId: string,
- messages: MessageWithBodyReplyless[],
+ messages: ApiMessage[],
messagesContainer: HTMLElement,
{
behavior = 'smooth',
@@ -66,9 +66,7 @@ export function scrollToLastMessage(
* @param messages - Array of messages in the current thread
* @returns The db_id of the last message, or undefined if no messages
*/
-export function getLastMessageId(
- messages: MessageWithBodyReplyless[]
-): string | undefined {
+export function getLastMessageId(messages: ApiMessage[]): string | undefined {
const lastMessage = messages[messages.length - 1];
return lastMessage?.db_id?.toString();
}
diff --git a/js/app/packages/block-email/util/subjectText.ts b/js/app/packages/block-email/util/subjectText.ts
index 163396faab..1db805f47d 100644
--- a/js/app/packages/block-email/util/subjectText.ts
+++ b/js/app/packages/block-email/util/subjectText.ts
@@ -1,8 +1,8 @@
-import type { MessageWithBodyReplyless } from '@service-email/generated/schemas';
+import type { ApiMessage } from '@service-email/generated/schemas';
import type { ReplyType } from './replyType';
export const getSubjectText = (
- replyingTo: MessageWithBodyReplyless | undefined,
+ replyingTo: ApiMessage | undefined,
replyType: ReplyType | undefined
) => {
if (!replyingTo) return '';
diff --git a/js/app/packages/core/constant/servers.ts b/js/app/packages/core/constant/servers.ts
index a26198368e..e23400deaf 100644
--- a/js/app/packages/core/constant/servers.ts
+++ b/js/app/packages/core/constant/servers.ts
@@ -26,7 +26,7 @@ const serverHostRemote = {
'static-file': `https://static-file-service${devServerSuffix}.macro.com`,
'unfurl-service': `https://unfurl-service${devServerSuffix}.macro.com`,
contacts: `https://contacts${devServerSuffix}.macro.com`,
- 'email-service': `https://email-service${devServerSuffix}.macro.com`,
+ 'email-service': `http://localhost:8094`,
'image-proxy-service': `https://image-proxy${devServerSuffix}.macro.com`,
} as const;
diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.ts
index 75b865b862..980ed1024d 100644
--- a/js/app/packages/queries/email/thread.ts
+++ b/js/app/packages/queries/email/thread.ts
@@ -5,7 +5,7 @@ import { emailClient } from '@service-email/client';
import type {
MessageToSend,
SendMessageResponse,
- APIThread as Thread,
+ ApiThread as Thread,
UpsertScheduledResponse,
} from '@service-email/generated/schemas';
import {
diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.ts
index 4f2fd7cd55..4836f29e52 100644
--- a/js/app/packages/service-clients/service-email/generated/client.ts
+++ b/js/app/packages/service-clients/service-email/generated/client.ts
@@ -1834,86 +1834,6 @@ export const previewsInboxCursor = async (
} as previewsInboxCursorResponse;
};
-/**
- * @summary Get a thread with a paginated number of messages.
- */
-export type getThreadResponse200 = {
- data: GetThreadResponse;
- status: 200;
-};
-
-export type getThreadResponse400 = {
- data: ErrorResponse;
- status: 400;
-};
-
-export type getThreadResponse401 = {
- data: ErrorResponse;
- status: 401;
-};
-
-export type getThreadResponse404 = {
- data: ErrorResponse;
- status: 404;
-};
-
-export type getThreadResponse500 = {
- data: ErrorResponse;
- status: 500;
-};
-
-export type getThreadResponseSuccess = getThreadResponse200 & {
- headers: Headers;
-};
-export type getThreadResponseError = (
- | getThreadResponse400
- | getThreadResponse401
- | getThreadResponse404
- | getThreadResponse500
-) & {
- headers: Headers;
-};
-
-export type getThreadResponse =
- | getThreadResponseSuccess
- | getThreadResponseError;
-
-export const getGetThreadUrl = (id: string, params: GetThreadParams) => {
- const normalizedParams = new URLSearchParams();
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString());
- }
- });
-
- const stringifiedParams = normalizedParams.toString();
-
- return stringifiedParams.length > 0
- ? `/email/threads/${id}?${stringifiedParams}`
- : `/email/threads/${id}`;
-};
-
-export const getThread = async (
- id: string,
- params: GetThreadParams,
- options?: RequestInit
-): Promise<getThreadResponse> => {
- const res = await fetch(getGetThreadUrl(id, params), {
- ...options,
- method: 'GET',
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: getThreadResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as getThreadResponse;
-};
-
/**
* @summary Change the archived status of a thread.
*/
@@ -2195,6 +2115,86 @@ export const threadSeen = async (
} as threadSeenResponse;
};
+/**
+ * @summary Get a thread with paginated messages.
+ */
+export type getThreadResponse200 = {
+ data: GetThreadResponse;
+ status: 200;
+};
+
+export type getThreadResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type getThreadResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type getThreadResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type getThreadResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type getThreadResponseSuccess = getThreadResponse200 & {
+ headers: Headers;
+};
+export type getThreadResponseError = (
+ | getThreadResponse400
+ | getThreadResponse401
+ | getThreadResponse404
+ | getThreadResponse500
+) & {
+ headers: Headers;
+};
+
+export type getThreadResponse =
+ | getThreadResponseSuccess
+ | getThreadResponseError;
+
+export const getGetThreadUrl = (threadId: string, params?: GetThreadParams) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/email/threads/${threadId}?${stringifiedParams}`
+ : `/email/threads/${threadId}`;
+};
+
+export const getThread = async (
+ threadId: string,
+ params?: GetThreadParams,
+ options?: RequestInit
+): Promise<getThreadResponse> => {
+ const res = await fetch(getGetThreadUrl(threadId, params), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getThreadResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getThreadResponse;
+};
+
/**
* @summary Health check
*/
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/aPIThread.ts b/js/app/packages/service-clients/service-email/generated/schemas/aPIThread.ts
deleted file mode 100644
index bfa27fe251..0000000000
--- a/js/app/packages/service-clients/service-email/generated/schemas/aPIThread.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * email_service
- * OpenAPI spec version: 0.1.0
- */
-import type { AccessLevel } from './accessLevel';
-import type { APIThreadLatestInboundMessageTs } from './aPIThreadLatestInboundMessageTs';
-import type { APIThreadLatestNonSpamMessageTs } from './aPIThreadLatestNonSpamMessageTs';
-import type { APIThreadLatestOutboundMessageTs } from './aPIThreadLatestOutboundMessageTs';
-import type { APIThreadProviderId } from './aPIThreadProviderId';
-import type { MessageWithBodyReplyless } from './messageWithBodyReplyless';
-
-/**
- * Thread object exposed to the FE in Get Threads Call
- */
-export interface APIThread {
- access_level: AccessLevel;
- created_at: string;
- db_id: string;
- inbox_visible: boolean;
- is_read: boolean;
- latest_inbound_message_ts?: APIThreadLatestInboundMessageTs;
- latest_non_spam_message_ts?: APIThreadLatestNonSpamMessageTs;
- latest_outbound_message_ts?: APIThreadLatestOutboundMessageTs;
- link_id: string;
- messages: MessageWithBodyReplyless[];
- provider_id?: APIThreadProviderId;
- updated_at: string;
-}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentDraft.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentDraft.ts
new file mode 100644
index 0000000000..53913de332
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentDraft.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * API representation of a draft attachment on a message.
+ */
+export interface ApiAttachmentDraft {
+ content_type: string;
+ draft_id: string;
+ file_name: string;
+ id: string;
+ s3_key: string;
+ sha: string;
+ size: number;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwarded.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwarded.ts
new file mode 100644
index 0000000000..9c78a8aec3
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwarded.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiAttachmentForwardedFilename } from './apiAttachmentForwardedFilename';
+import type { ApiAttachmentForwardedMimeType } from './apiAttachmentForwardedMimeType';
+import type { ApiAttachmentForwardedProviderAttachmentId } from './apiAttachmentForwardedProviderAttachmentId';
+import type { ApiAttachmentForwardedSizeBytes } from './apiAttachmentForwardedSizeBytes';
+
+/**
+ * API representation of a forwarded attachment on a message.
+ */
+export interface ApiAttachmentForwarded {
+ attachment_id: string;
+ draft_id: string;
+ filename?: ApiAttachmentForwardedFilename;
+ message_provider_id: string;
+ mime_type?: ApiAttachmentForwardedMimeType;
+ provider_attachment_id?: ApiAttachmentForwardedProviderAttachmentId;
+ size_bytes?: ApiAttachmentForwardedSizeBytes;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/aPIThreadLatestInboundMessageTs.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedFilename.ts
similarity index 65%
rename from js/app/packages/service-clients/service-email/generated/schemas/aPIThreadLatestInboundMessageTs.ts
rename to js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedFilename.ts
index e76f40c4ea..b8d643d510 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/aPIThreadLatestInboundMessageTs.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedFilename.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type APIThreadLatestInboundMessageTs = string | null;
+export type ApiAttachmentForwardedFilename = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/aPIThreadLatestNonSpamMessageTs.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedMimeType.ts
similarity index 65%
rename from js/app/packages/service-clients/service-email/generated/schemas/aPIThreadLatestNonSpamMessageTs.ts
rename to js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedMimeType.ts
index 7a61d094b5..cc56cb87f8 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/aPIThreadLatestNonSpamMessageTs.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedMimeType.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type APIThreadLatestNonSpamMessageTs = string | null;
+export type ApiAttachmentForwardedMimeType = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageWithBodyReplylessAllOfBodyReplyless.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedProviderAttachmentId.ts
similarity index 66%
rename from js/app/packages/service-clients/service-email/generated/schemas/messageWithBodyReplylessAllOfBodyReplyless.ts
rename to js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedProviderAttachmentId.ts
index d78539dc0f..20e14ce678 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/messageWithBodyReplylessAllOfBodyReplyless.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedProviderAttachmentId.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type MessageWithBodyReplylessAllOfBodyReplyless = string | null;
+export type ApiAttachmentForwardedProviderAttachmentId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/aPIThreadLatestOutboundMessageTs.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedSizeBytes.ts
similarity index 65%
rename from js/app/packages/service-clients/service-email/generated/schemas/aPIThreadLatestOutboundMessageTs.ts
rename to js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedSizeBytes.ts
index fdacf2bda0..fc26eadf8f 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/aPIThreadLatestOutboundMessageTs.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiAttachmentForwardedSizeBytes.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type APIThreadLatestOutboundMessageTs = string | null;
+export type ApiAttachmentForwardedSizeBytes = number | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiContactInfo.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiContactInfo.ts
new file mode 100644
index 0000000000..109ff54d29
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiContactInfo.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiContactInfoName } from './apiContactInfoName';
+import type { ApiContactInfoPhotoUrl } from './apiContactInfoPhotoUrl';
+
+/**
+ * API representation of a contact (sender or recipient).
+ */
+export interface ApiContactInfo {
+ email: string;
+ name?: ApiContactInfoName;
+ photo_url?: ApiContactInfoPhotoUrl;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/aPIThreadProviderId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiContactInfoName.ts
similarity index 70%
rename from js/app/packages/service-clients/service-email/generated/schemas/aPIThreadProviderId.ts
rename to js/app/packages/service-clients/service-email/generated/schemas/apiContactInfoName.ts
index 9c2ff2a9ac..fdc2ba16ce 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/aPIThreadProviderId.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiContactInfoName.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type APIThreadProviderId = string | null;
+export type ApiContactInfoName = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiContactInfoPhotoUrl.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiContactInfoPhotoUrl.ts
new file mode 100644
index 0000000000..7b0ecfc109
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiContactInfoPhotoUrl.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiContactInfoPhotoUrl = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessage.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessage.ts
new file mode 100644
index 0000000000..cc109b5c84
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessage.ts
@@ -0,0 +1,68 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { ApiAttachmentDraft } from './apiAttachmentDraft';
+import type { ApiAttachmentForwarded } from './apiAttachmentForwarded';
+import type { ApiContactInfo } from './apiContactInfo';
+import type { ApiMessageAttachment } from './apiMessageAttachment';
+import type { ApiMessageBodyHtmlSanitized } from './apiMessageBodyHtmlSanitized';
+import type { ApiMessageBodyMacro } from './apiMessageBodyMacro';
+import type { ApiMessageBodyReplyless } from './apiMessageBodyReplyless';
+import type { ApiMessageBodyText } from './apiMessageBodyText';
+import type { ApiMessageFrom } from './apiMessageFrom';
+import type { ApiMessageGlobalId } from './apiMessageGlobalId';
+import type { ApiMessageInternalDateTs } from './apiMessageInternalDateTs';
+import type { ApiMessageLabel } from './apiMessageLabel';
+import type { ApiMessageProviderHistoryId } from './apiMessageProviderHistoryId';
+import type { ApiMessageProviderId } from './apiMessageProviderId';
+import type { ApiMessageProviderThreadId } from './apiMessageProviderThreadId';
+import type { ApiMessageReplyingToId } from './apiMessageReplyingToId';
+import type { ApiMessageScheduledSendTime } from './apiMessageScheduledSendTime';
+import type { ApiMessageSentAt } from './apiMessageSentAt';
+import type { ApiMessageSizeEstimate } from './apiMessageSizeEstimate';
+import type { ApiMessageSnippet } from './apiMessageSnippet';
+import type { ApiMessageSubject } from './apiMessageSubject';
+
+/**
+ * API representation of a fully assembled email message.
+ */
+export interface ApiMessage {
+ attachments: ApiMessageAttachment[];
+ attachments_draft: ApiAttachmentDraft[];
+ attachments_forwarded: ApiAttachmentForwarded[];
+ bcc: ApiContactInfo[];
+ body_html_sanitized?: ApiMessageBodyHtmlSanitized;
+ body_macro?: ApiMessageBodyMacro;
+ body_replyless?: ApiMessageBodyReplyless;
+ body_text?: ApiMessageBodyText;
+ cc: ApiContactInfo[];
+ created_at: string;
+ db_id: string;
+ from?: ApiMessageFrom;
+ global_id?: ApiMessageGlobalId;
+ has_attachments: boolean;
+ headers_json?: unknown;
+ internal_date_ts?: ApiMessageInternalDateTs;
+ is_draft: boolean;
+ is_read: boolean;
+ is_sent: boolean;
+ is_starred: boolean;
+ labels: ApiMessageLabel[];
+ link_id: string;
+ provider_history_id?: ApiMessageProviderHistoryId;
+ provider_id?: ApiMessageProviderId;
+ provider_thread_id?: ApiMessageProviderThreadId;
+ replying_to_id?: ApiMessageReplyingToId;
+ scheduled_send_time?: ApiMessageScheduledSendTime;
+ sent_at?: ApiMessageSentAt;
+ size_estimate?: ApiMessageSizeEstimate;
+ snippet?: ApiMessageSnippet;
+ subject?: ApiMessageSubject;
+ thread_db_id: string;
+ to: ApiContactInfo[];
+ updated_at: string;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachment.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachment.ts
new file mode 100644
index 0000000000..de7a8b8405
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachment.ts
@@ -0,0 +1,27 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiMessageAttachmentContentId } from './apiMessageAttachmentContentId';
+import type { ApiMessageAttachmentDataUrl } from './apiMessageAttachmentDataUrl';
+import type { ApiMessageAttachmentFilename } from './apiMessageAttachmentFilename';
+import type { ApiMessageAttachmentMimeType } from './apiMessageAttachmentMimeType';
+import type { ApiMessageAttachmentProviderId } from './apiMessageAttachmentProviderId';
+import type { ApiMessageAttachmentSfsId } from './apiMessageAttachmentSfsId';
+import type { ApiMessageAttachmentSizeBytes } from './apiMessageAttachmentSizeBytes';
+
+/**
+ * API representation of a provider attachment on a message.
+ */
+export interface ApiMessageAttachment {
+ content_id?: ApiMessageAttachmentContentId;
+ data_url?: ApiMessageAttachmentDataUrl;
+ db_id: string;
+ filename?: ApiMessageAttachmentFilename;
+ mime_type?: ApiMessageAttachmentMimeType;
+ provider_id?: ApiMessageAttachmentProviderId;
+ sfs_id?: ApiMessageAttachmentSfsId;
+ size_bytes?: ApiMessageAttachmentSizeBytes;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentContentId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentContentId.ts
new file mode 100644
index 0000000000..d9ddd61202
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentContentId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageAttachmentContentId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentDataUrl.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentDataUrl.ts
new file mode 100644
index 0000000000..e4ad1c693a
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentDataUrl.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageAttachmentDataUrl = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentFilename.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentFilename.ts
new file mode 100644
index 0000000000..c2137fb2ca
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentFilename.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageAttachmentFilename = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentMimeType.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentMimeType.ts
new file mode 100644
index 0000000000..d5ba809b44
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentMimeType.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageAttachmentMimeType = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentProviderId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentProviderId.ts
new file mode 100644
index 0000000000..9bafbb2b9d
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentProviderId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageAttachmentProviderId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentSfsId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentSfsId.ts
new file mode 100644
index 0000000000..167e8948a9
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentSfsId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageAttachmentSfsId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentSizeBytes.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentSizeBytes.ts
new file mode 100644
index 0000000000..91bbb14b53
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageAttachmentSizeBytes.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageAttachmentSizeBytes = number | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyHtmlSanitized.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyHtmlSanitized.ts
new file mode 100644
index 0000000000..711b38662f
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyHtmlSanitized.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageBodyHtmlSanitized = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyMacro.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyMacro.ts
new file mode 100644
index 0000000000..a14c470938
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyMacro.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageBodyMacro = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyReplyless.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyReplyless.ts
new file mode 100644
index 0000000000..cca7e131bb
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyReplyless.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageBodyReplyless = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyText.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyText.ts
new file mode 100644
index 0000000000..f8f4bcfa5a
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageBodyText.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageBodyText = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageFrom.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageFrom.ts
new file mode 100644
index 0000000000..dcbbeaea51
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageFrom.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiContactInfo } from './apiContactInfo';
+
+export type ApiMessageFrom = null | ApiContactInfo;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageGlobalId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageGlobalId.ts
new file mode 100644
index 0000000000..e21c702b3f
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageGlobalId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageGlobalId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageInternalDateTs.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageInternalDateTs.ts
new file mode 100644
index 0000000000..f32397e1a7
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageInternalDateTs.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageInternalDateTs = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabel.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabel.ts
new file mode 100644
index 0000000000..085b5db6a8
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabel.ts
@@ -0,0 +1,25 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiMessageLabelId } from './apiMessageLabelId';
+import type { ApiMessageLabelLabelListVisibility } from './apiMessageLabelLabelListVisibility';
+import type { ApiMessageLabelMessageListVisibility } from './apiMessageLabelMessageListVisibility';
+import type { ApiMessageLabelName } from './apiMessageLabelName';
+import type { ApiMessageLabelType } from './apiMessageLabelType';
+
+/**
+ * API representation of a label on a message.
+ */
+export interface ApiMessageLabel {
+ created_at: string;
+ id?: ApiMessageLabelId;
+ label_list_visibility?: ApiMessageLabelLabelListVisibility;
+ link_id: string;
+ message_list_visibility?: ApiMessageLabelMessageListVisibility;
+ name?: ApiMessageLabelName;
+ provider_label_id: string;
+ type_?: ApiMessageLabelType;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelId.ts
new file mode 100644
index 0000000000..c9811340bd
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageLabelId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelLabelListVisibility.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelLabelListVisibility.ts
new file mode 100644
index 0000000000..faec991f61
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelLabelListVisibility.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiLabelListVisibility } from './apiLabelListVisibility';
+
+export type ApiMessageLabelLabelListVisibility = null | ApiLabelListVisibility;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelMessageListVisibility.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelMessageListVisibility.ts
new file mode 100644
index 0000000000..0e668ff867
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelMessageListVisibility.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiMessageListVisibility } from './apiMessageListVisibility';
+
+export type ApiMessageLabelMessageListVisibility =
+ null | ApiMessageListVisibility;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelName.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelName.ts
new file mode 100644
index 0000000000..c028537524
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelName.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageLabelName = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelType.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelType.ts
new file mode 100644
index 0000000000..f4a675713c
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageLabelType.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiLabelType } from './apiLabelType';
+
+export type ApiMessageLabelType = null | ApiLabelType;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageProviderHistoryId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageProviderHistoryId.ts
new file mode 100644
index 0000000000..2a5ea1bcfe
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageProviderHistoryId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageProviderHistoryId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageProviderId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageProviderId.ts
new file mode 100644
index 0000000000..a7573efc4e
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageProviderId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageProviderId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageProviderThreadId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageProviderThreadId.ts
new file mode 100644
index 0000000000..17b126d50f
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageProviderThreadId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageProviderThreadId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageReplyingToId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageReplyingToId.ts
new file mode 100644
index 0000000000..83a1c2630d
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageReplyingToId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageReplyingToId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageScheduledSendTime.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageScheduledSendTime.ts
new file mode 100644
index 0000000000..5810db80db
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageScheduledSendTime.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageScheduledSendTime = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSentAt.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSentAt.ts
new file mode 100644
index 0000000000..33039ee2f7
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSentAt.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageSentAt = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSizeEstimate.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSizeEstimate.ts
new file mode 100644
index 0000000000..d16aa1568a
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSizeEstimate.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageSizeEstimate = number | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSnippet.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSnippet.ts
new file mode 100644
index 0000000000..8b6d41af6d
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSnippet.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageSnippet = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSubject.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSubject.ts
new file mode 100644
index 0000000000..7179bce649
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiMessageSubject.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiMessageSubject = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiThread.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiThread.ts
new file mode 100644
index 0000000000..e2ef7f7bb3
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiThread.ts
@@ -0,0 +1,30 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AccessLevel } from './accessLevel';
+import type { ApiMessage } from './apiMessage';
+import type { ApiThreadLatestInboundMessageTs } from './apiThreadLatestInboundMessageTs';
+import type { ApiThreadLatestNonSpamMessageTs } from './apiThreadLatestNonSpamMessageTs';
+import type { ApiThreadLatestOutboundMessageTs } from './apiThreadLatestOutboundMessageTs';
+import type { ApiThreadProviderId } from './apiThreadProviderId';
+
+/**
+ * API representation of a fully assembled email thread.
+ */
+export interface ApiThread {
+ access_level: AccessLevel;
+ created_at: string;
+ db_id: string;
+ inbox_visible: boolean;
+ is_read: boolean;
+ latest_inbound_message_ts?: ApiThreadLatestInboundMessageTs;
+ latest_non_spam_message_ts?: ApiThreadLatestNonSpamMessageTs;
+ latest_outbound_message_ts?: ApiThreadLatestOutboundMessageTs;
+ link_id: string;
+ messages: ApiMessage[];
+ provider_id?: ApiThreadProviderId;
+ updated_at: string;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiThreadLatestInboundMessageTs.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadLatestInboundMessageTs.ts
new file mode 100644
index 0000000000..1ebda5a1cb
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadLatestInboundMessageTs.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadLatestInboundMessageTs = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiThreadLatestNonSpamMessageTs.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadLatestNonSpamMessageTs.ts
new file mode 100644
index 0000000000..489f37aa1e
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadLatestNonSpamMessageTs.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadLatestNonSpamMessageTs = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiThreadLatestOutboundMessageTs.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadLatestOutboundMessageTs.ts
new file mode 100644
index 0000000000..9cc083743b
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadLatestOutboundMessageTs.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadLatestOutboundMessageTs = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiThreadProviderId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadProviderId.ts
new file mode 100644
index 0000000000..40421c3db1
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadProviderId.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiThreadProviderId = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/getThreadParams.ts b/js/app/packages/service-clients/service-email/generated/schemas/getThreadParams.ts
index d367d93311..1c6fac33b5 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/getThreadParams.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/getThreadParams.ts
@@ -9,9 +9,9 @@ export type GetThreadParams = {
/**
* Offset for message pagination. Default is 0.
*/
- offset: number;
+ offset?: number;
/**
- * Limit for message pagination. Default is 5.
+ * Limit for message pagination. Default is 5, max 100.
*/
- limit: number;
+ limit?: number;
};
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/getThreadResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/getThreadResponse.ts
index 41ddad1e28..f7b303e0ef 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/getThreadResponse.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/getThreadResponse.ts
@@ -4,12 +4,11 @@
* email_service
* OpenAPI spec version: 0.1.0
*/
-import type { APIThread } from './aPIThread';
+import type { ApiThread } from './apiThread';
/**
- * The response returned from the get thread endpoint
+ * Response body for the get-thread endpoint.
*/
export interface GetThreadResponse {
- /** the thread, with messages inside */
- thread: APIThread;
+ thread: ApiThread;
}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
index 295dcd6548..49ab056bb1 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
@@ -13,28 +13,67 @@ export * from './addForwardedAttachmentResponse';
export * from './addForwardedAttachmentResponseFilename';
export * from './addForwardedAttachmentResponseMimeType';
export * from './addForwardedAttachmentResponseSizeBytes';
-export * from './aPIThread';
-export * from './aPIThreadLatestInboundMessageTs';
-export * from './aPIThreadLatestNonSpamMessageTs';
-export * from './aPIThreadLatestOutboundMessageTs';
-export * from './aPIThreadProviderId';
export * from './apiAttachment';
export * from './apiAttachmentContentId';
+export * from './apiAttachmentDraft';
export * from './apiAttachmentFilename';
+export * from './apiAttachmentForwarded';
+export * from './apiAttachmentForwardedFilename';
+export * from './apiAttachmentForwardedMimeType';
+export * from './apiAttachmentForwardedProviderAttachmentId';
+export * from './apiAttachmentForwardedSizeBytes';
export * from './apiAttachmentMimeType';
export * from './apiAttachmentProviderAttachmentId';
export * from './apiAttachmentSizeBytes';
export * from './apiContact';
export * from './apiContactEmailAddress';
+export * from './apiContactInfo';
+export * from './apiContactInfoName';
+export * from './apiContactInfoPhotoUrl';
export * from './apiContactName';
export * from './apiContactSfsPhotoUrl';
export * from './apiLabel';
export * from './apiLabelListVisibility';
export * from './apiLabelType';
+export * from './apiMessage';
+export * from './apiMessageAttachment';
+export * from './apiMessageAttachmentContentId';
+export * from './apiMessageAttachmentDataUrl';
+export * from './apiMessageAttachmentFilename';
+export * from './apiMessageAttachmentMimeType';
+export * from './apiMessageAttachmentProviderId';
+export * from './apiMessageAttachmentSfsId';
+export * from './apiMessageAttachmentSizeBytes';
+export * from './apiMessageBodyHtmlSanitized';
+export * from './apiMessageBodyMacro';
+export * from './apiMessageBodyReplyless';
+export * from './apiMessageBodyText';
+export * from './apiMessageFrom';
+export * from './apiMessageGlobalId';
+export * from './apiMessageInternalDateTs';
+export * from './apiMessageLabel';
+export * from './apiMessageLabelId';
+export * from './apiMessageLabelLabelListVisibility';
+export * from './apiMessageLabelMessageListVisibility';
+export * from './apiMessageLabelName';
+export * from './apiMessageLabelType';
export * from './apiMessageListVisibility';
+export * from './apiMessageProviderHistoryId';
+export * from './apiMessageProviderId';
+export * from './apiMessageProviderThreadId';
+export * from './apiMessageReplyingToId';
+export * from './apiMessageScheduledSendTime';
+export * from './apiMessageSentAt';
+export * from './apiMessageSizeEstimate';
+export * from './apiMessageSnippet';
+export * from './apiMessageSubject';
export * from './apiPaginatedThreadCursor';
export * from './apiPaginatedThreadCursorNextCursor';
export * from './apiSortMethod';
+export * from './apiThread';
+export * from './apiThreadLatestInboundMessageTs';
+export * from './apiThreadLatestNonSpamMessageTs';
+export * from './apiThreadLatestOutboundMessageTs';
export * from './apiThreadPreviewCursor';
export * from './apiThreadPreviewCursorAllOf';
export * from './apiThreadPreviewCursorAllOfFrecencyScore';
@@ -46,6 +85,7 @@ export * from './apiThreadPreviewCursorInnerSenderName';
export * from './apiThreadPreviewCursorInnerSenderPhotoUrl';
export * from './apiThreadPreviewCursorInnerSnippet';
export * from './apiThreadPreviewCursorInnerViewedAt';
+export * from './apiThreadProviderId';
export * from './archiveThreadRequest';
export * from './attachment';
export * from './attachmentContentId';
@@ -149,9 +189,6 @@ export * from './messageToSendReplyingToId';
export * from './messageToSendSendTime';
export * from './messageToSendThreadDbId';
export * from './messageToSendTo';
-export * from './messageWithBodyReplyless';
-export * from './messageWithBodyReplylessAllOf';
-export * from './messageWithBodyReplylessAllOfBodyReplyless';
export * from './parsedMessage';
export * from './parsedMessageBodyParsed';
export * from './parsedMessageFrom';
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageWithBodyReplyless.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageWithBodyReplyless.ts
deleted file mode 100644
index 4f47e44be4..0000000000
--- a/js/app/packages/service-clients/service-email/generated/schemas/messageWithBodyReplyless.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * email_service
- * OpenAPI spec version: 0.1.0
- */
-import type { Message } from './message';
-import type { MessageWithBodyReplylessAllOf } from './messageWithBodyReplylessAllOf';
-
-export type MessageWithBodyReplyless = Message & MessageWithBodyReplylessAllOf;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/messageWithBodyReplylessAllOf.ts b/js/app/packages/service-clients/service-email/generated/schemas/messageWithBodyReplylessAllOf.ts
deleted file mode 100644
index 50d68d5499..0000000000
--- a/js/app/packages/service-clients/service-email/generated/schemas/messageWithBodyReplylessAllOf.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * email_service
- * OpenAPI spec version: 0.1.0
- */
-import type { MessageWithBodyReplylessAllOfBodyReplyless } from './messageWithBodyReplylessAllOfBodyReplyless';
-
-export type MessageWithBodyReplylessAllOf = {
- body_replyless?: MessageWithBodyReplylessAllOfBodyReplyless;
-};
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index 565a84463c..2abf3a1c01 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -1751,97 +1751,6 @@
}
}
},
- "/email/threads/{id}": {
- "get": {
- "tags": ["Threads"],
- "summary": "Get a thread with a paginated number of messages.",
- "operationId": "get_thread",
- "parameters": [
- {
- "name": "id",
- "in": "path",
- "description": "Thread ID.",
- "required": true,
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- },
- {
- "name": "offset",
- "in": "query",
- "description": "Offset for message pagination. Default is 0.",
- "required": true,
- "schema": {
- "type": "integer",
- "format": "int64"
- }
- },
- {
- "name": "limit",
- "in": "query",
- "description": "Limit for message pagination. Default is 5.",
- "required": true,
- "schema": {
- "type": "integer",
- "format": "int64"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/GetThreadResponse"
- }
- }
- }
- },
- "400": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
- "401": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
- "404": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
- "500": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- }
- }
- }
- },
"/email/threads/{id}/archived": {
"patch": {
"tags": ["Threads"],
@@ -2146,6 +2055,96 @@
}
}
},
+ "/email/threads/{thread_id}": {
+ "get": {
+ "tags": ["Threads"],
+ "summary": "Get a thread with paginated messages.",
+ "operationId": "get_thread",
+ "parameters": [
+ {
+ "name": "thread_id",
+ "in": "path",
+ "description": "Thread ID",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "offset",
+ "in": "query",
+ "description": "Offset for message pagination. Default is 0.",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int64"
+ }
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "description": "Limit for message pagination. Default is 5, max 100.",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int64"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetThreadResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/health": {
"get": {
"tags": ["Health"],
@@ -2168,68 +2167,6 @@
},
"components": {
"schemas": {
- "APIThread": {
- "type": "object",
- "description": "Thread object exposed to the FE in Get Threads Call",
- "required": [
- "db_id",
- "link_id",
- "inbox_visible",
- "is_read",
- "access_level",
- "created_at",
- "updated_at",
- "messages"
- ],
- "properties": {
- "access_level": {
- "$ref": "#/components/schemas/AccessLevel"
- },
- "created_at": {
- "type": "string",
- "format": "date-time"
- },
- "db_id": {
- "type": "string",
- "format": "uuid"
- },
- "inbox_visible": {
- "type": "boolean"
- },
- "is_read": {
- "type": "boolean"
- },
- "latest_inbound_message_ts": {
- "type": ["string", "null"],
- "format": "date-time"
- },
- "latest_non_spam_message_ts": {
- "type": ["string", "null"],
- "format": "date-time"
- },
- "latest_outbound_message_ts": {
- "type": ["string", "null"],
- "format": "date-time"
- },
- "link_id": {
- "type": "string",
- "format": "uuid"
- },
- "messages": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/MessageWithBodyReplyless"
- }
- },
- "provider_id": {
- "type": ["string", "null"]
- },
- "updated_at": {
- "type": "string",
- "format": "date-time"
- }
- }
- },
"AccessLevel": {
"type": "string",
"description": "Ordered from least to most access top -> bottom",
@@ -2316,106 +2253,444 @@
"contentId": {
"type": ["string", "null"]
},
- "createdAt": {
- "type": "string",
- "format": "date-time"
+ "createdAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "filename": {
+ "type": ["string", "null"]
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "messageId": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "mimeType": {
+ "type": ["string", "null"]
+ },
+ "providerAttachmentId": {
+ "type": ["string", "null"]
+ },
+ "sizeBytes": {
+ "type": ["integer", "null"],
+ "format": "int64"
+ }
+ }
+ },
+ "ApiAttachmentDraft": {
+ "type": "object",
+ "description": "API representation of a draft attachment on a message.",
+ "required": [
+ "id",
+ "draft_id",
+ "file_name",
+ "content_type",
+ "sha",
+ "size",
+ "s3_key"
+ ],
+ "properties": {
+ "content_type": {
+ "type": "string"
+ },
+ "draft_id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "file_name": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "s3_key": {
+ "type": "string"
+ },
+ "sha": {
+ "type": "string"
+ },
+ "size": {
+ "type": "integer",
+ "format": "int32"
+ }
+ }
+ },
+ "ApiAttachmentForwarded": {
+ "type": "object",
+ "description": "API representation of a forwarded attachment on a message.",
+ "required": ["attachment_id", "draft_id", "message_provider_id"],
+ "properties": {
+ "attachment_id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "draft_id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "filename": {
+ "type": ["string", "null"]
+ },
+ "message_provider_id": {
+ "type": "string"
+ },
+ "mime_type": {
+ "type": ["string", "null"]
+ },
+ "provider_attachment_id": {
+ "type": ["string", "null"]
+ },
+ "size_bytes": {
+ "type": ["integer", "null"],
+ "format": "int64"
+ }
+ }
+ },
+ "ApiContact": {
+ "type": "object",
+ "required": ["id", "linkId"],
+ "properties": {
+ "emailAddress": {
+ "type": ["string", "null"]
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "linkId": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "name": {
+ "type": ["string", "null"]
+ },
+ "sfsPhotoUrl": {
+ "type": ["string", "null"]
+ }
+ }
+ },
+ "ApiContactInfo": {
+ "type": "object",
+ "description": "API representation of a contact (sender or recipient).",
+ "required": ["email"],
+ "properties": {
+ "email": {
+ "type": "string"
+ },
+ "name": {
+ "type": ["string", "null"]
+ },
+ "photo_url": {
+ "type": ["string", "null"]
+ }
+ }
+ },
+ "ApiLabel": {
+ "type": "object",
+ "required": [
+ "id",
+ "linkId",
+ "providerLabelId",
+ "name",
+ "createdAt",
+ "messageListVisibility",
+ "labelListVisibility",
+ "type"
+ ],
+ "properties": {
+ "createdAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "labelListVisibility": {
+ "$ref": "#/components/schemas/ApiLabelListVisibility"
+ },
+ "linkId": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "messageListVisibility": {
+ "$ref": "#/components/schemas/ApiMessageListVisibility"
+ },
+ "name": {
+ "type": "string"
+ },
+ "providerLabelId": {
+ "type": "string"
+ },
+ "type": {
+ "$ref": "#/components/schemas/ApiLabelType"
+ }
+ }
+ },
+ "ApiLabelListVisibility": {
+ "type": "string",
+ "enum": ["LabelShow", "LabelShowIfUnread", "LabelHide"]
+ },
+ "ApiLabelType": {
+ "type": "string",
+ "enum": ["System", "User"]
+ },
+ "ApiMessage": {
+ "type": "object",
+ "description": "API representation of a fully assembled email message.",
+ "required": [
+ "db_id",
+ "thread_db_id",
+ "link_id",
+ "is_read",
+ "is_starred",
+ "is_sent",
+ "is_draft",
+ "has_attachments",
+ "to",
+ "cc",
+ "bcc",
+ "labels",
+ "attachments",
+ "attachments_draft",
+ "attachments_forwarded",
+ "created_at",
+ "updated_at"
+ ],
+ "properties": {
+ "attachments": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiMessageAttachment"
+ }
+ },
+ "attachments_draft": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiAttachmentDraft"
+ }
+ },
+ "attachments_forwarded": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiAttachmentForwarded"
+ }
+ },
+ "bcc": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiContactInfo"
+ }
+ },
+ "body_html_sanitized": {
+ "type": ["string", "null"]
+ },
+ "body_macro": {
+ "type": ["string", "null"]
},
- "filename": {
+ "body_replyless": {
"type": ["string", "null"]
},
- "id": {
+ "body_text": {
+ "type": ["string", "null"]
+ },
+ "cc": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiContactInfo"
+ }
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "db_id": {
"type": "string",
"format": "uuid"
},
- "messageId": {
+ "from": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ApiContactInfo"
+ }
+ ]
+ },
+ "global_id": {
+ "type": ["string", "null"]
+ },
+ "has_attachments": {
+ "type": "boolean"
+ },
+ "headers_json": {},
+ "internal_date_ts": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "is_draft": {
+ "type": "boolean"
+ },
+ "is_read": {
+ "type": "boolean"
+ },
+ "is_sent": {
+ "type": "boolean"
+ },
+ "is_starred": {
+ "type": "boolean"
+ },
+ "labels": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiMessageLabel"
+ }
+ },
+ "link_id": {
"type": "string",
"format": "uuid"
},
- "mimeType": {
+ "provider_history_id": {
"type": ["string", "null"]
},
- "providerAttachmentId": {
+ "provider_id": {
"type": ["string", "null"]
},
- "sizeBytes": {
+ "provider_thread_id": {
+ "type": ["string", "null"]
+ },
+ "replying_to_id": {
+ "type": ["string", "null"],
+ "format": "uuid"
+ },
+ "scheduled_send_time": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "sent_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "size_estimate": {
"type": ["integer", "null"],
"format": "int64"
+ },
+ "snippet": {
+ "type": ["string", "null"]
+ },
+ "subject": {
+ "type": ["string", "null"]
+ },
+ "thread_db_id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "to": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiContactInfo"
+ }
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time"
}
}
},
- "ApiContact": {
+ "ApiMessageAttachment": {
"type": "object",
- "required": ["id", "linkId"],
+ "description": "API representation of a provider attachment on a message.",
+ "required": ["db_id"],
"properties": {
- "emailAddress": {
+ "content_id": {
"type": ["string", "null"]
},
- "id": {
- "type": "string",
- "format": "uuid"
+ "data_url": {
+ "type": ["string", "null"]
},
- "linkId": {
+ "db_id": {
"type": "string",
"format": "uuid"
},
- "name": {
+ "filename": {
"type": ["string", "null"]
},
- "sfsPhotoUrl": {
+ "mime_type": {
+ "type": ["string", "null"]
+ },
+ "provider_id": {
"type": ["string", "null"]
+ },
+ "sfs_id": {
+ "type": ["string", "null"],
+ "format": "uuid"
+ },
+ "size_bytes": {
+ "type": ["integer", "null"],
+ "format": "int64"
}
}
},
- "ApiLabel": {
+ "ApiMessageLabel": {
"type": "object",
- "required": [
- "id",
- "linkId",
- "providerLabelId",
- "name",
- "createdAt",
- "messageListVisibility",
- "labelListVisibility",
- "type"
- ],
+ "description": "API representation of a label on a message.",
+ "required": ["link_id", "provider_label_id", "created_at"],
"properties": {
- "createdAt": {
+ "created_at": {
"type": "string",
"format": "date-time"
},
"id": {
- "type": "string",
+ "type": ["string", "null"],
"format": "uuid"
},
- "labelListVisibility": {
- "$ref": "#/components/schemas/ApiLabelListVisibility"
+ "label_list_visibility": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ApiLabelListVisibility"
+ }
+ ]
},
- "linkId": {
+ "link_id": {
"type": "string",
"format": "uuid"
},
- "messageListVisibility": {
- "$ref": "#/components/schemas/ApiMessageListVisibility"
+ "message_list_visibility": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ApiMessageListVisibility"
+ }
+ ]
},
"name": {
- "type": "string"
+ "type": ["string", "null"]
},
- "providerLabelId": {
+ "provider_label_id": {
"type": "string"
},
- "type": {
- "$ref": "#/components/schemas/ApiLabelType"
+ "type_": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ApiLabelType"
+ }
+ ]
}
}
},
- "ApiLabelListVisibility": {
- "type": "string",
- "enum": ["LabelShow", "LabelShowIfUnread", "LabelHide"]
- },
- "ApiLabelType": {
- "type": "string",
- "enum": ["System", "User"]
- },
"ApiMessageListVisibility": {
"type": "string",
"enum": ["Show", "Hide"]
@@ -2440,6 +2715,68 @@
"description": "common types of sorts based on timestamps",
"enum": ["viewed_at", "updated_at", "created_at", "viewed_updated"]
},
+ "ApiThread": {
+ "type": "object",
+ "description": "API representation of a fully assembled email thread.",
+ "required": [
+ "db_id",
+ "link_id",
+ "inbox_visible",
+ "is_read",
+ "access_level",
+ "created_at",
+ "updated_at",
+ "messages"
+ ],
+ "properties": {
+ "access_level": {
+ "$ref": "#/components/schemas/AccessLevel"
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "db_id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "inbox_visible": {
+ "type": "boolean"
+ },
+ "is_read": {
+ "type": "boolean"
+ },
+ "latest_inbound_message_ts": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "latest_non_spam_message_ts": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "latest_outbound_message_ts": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "link_id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "messages": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiMessage"
+ }
+ },
+ "provider_id": {
+ "type": ["string", "null"]
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time"
+ }
+ }
+ },
"ApiThreadPreviewCursor": {
"allOf": [
{
@@ -2968,12 +3305,11 @@
},
"GetThreadResponse": {
"type": "object",
- "description": "The response returned from the get thread endpoint",
+ "description": "Response body for the get-thread endpoint.",
"required": ["thread"],
"properties": {
"thread": {
- "$ref": "#/components/schemas/APIThread",
- "description": "the thread, with messages inside"
+ "$ref": "#/components/schemas/ApiThread"
}
}
},
@@ -3413,21 +3749,6 @@
}
}
},
- "MessageWithBodyReplyless": {
- "allOf": [
- {
- "$ref": "#/components/schemas/Message"
- },
- {
- "type": "object",
- "properties": {
- "body_replyless": {
- "type": ["string", "null"]
- }
- }
- }
- ]
- },
"ParsedMessage": {
"type": "object",
"required": [
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index b56af7d669..55a53c0d3e 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3302,8 +3302,10 @@ dependencies = [
"doppleganger",
"either",
"email_utils",
+ "entity_access",
"filter_ast",
"frecency",
+ "futures",
"item_filters",
"macro_db_migrator",
"macro_user_id",
@@ -3445,6 +3447,7 @@ dependencies = [
"email",
"email_db_client",
"email_utils",
+ "entity_access",
"frecency",
"futures",
"gmail_client",
@@ -3560,8 +3563,10 @@ dependencies = [
name = "email_utils"
version = "0.1.0"
dependencies = [
+ "ego-tree",
"lazy_static",
"regex",
+ "scraper",
]
[[package]]
@@ -5933,7 +5938,6 @@ dependencies = [
"model_user",
"models_bulk_upload",
"models_comms",
- "models_email",
"models_pagination",
"models_permissions",
"schemars",
@@ -6064,6 +6068,7 @@ dependencies = [
"doppleganger",
"ego-tree",
"email",
+ "email_utils",
"html2text",
"lazy_static",
"macro_user_id",
@@ -9020,6 +9025,7 @@ dependencies = [
"doppleganger",
"either",
"email",
+ "entity_access",
"filter_ast",
"frecency",
"futures",
diff --git a/rust/cloud-storage/email/.sqlx/query-0fa68fc475c11aef694e24ffa9db39d6823782c2a53f7fb0944f2d5720371b23.json b/rust/cloud-storage/email/.sqlx/query-0fa68fc475c11aef694e24ffa9db39d6823782c2a53f7fb0944f2d5720371b23.json
new file mode 100644
index 0000000000..1d88eeb713
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-0fa68fc475c11aef694e24ffa9db39d6823782c2a53f7fb0944f2d5720371b23.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT t.id, t.provider_id, t.link_id, t.inbox_visible, t.is_read,\n t.latest_inbound_message_ts, t.latest_outbound_message_ts,\n t.latest_non_spam_message_ts, t.created_at, t.updated_at\n FROM email_threads t\n WHERE t.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "latest_inbound_message_ts",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "latest_outbound_message_ts",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "latest_non_spam_message_ts",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "0fa68fc475c11aef694e24ffa9db39d6823782c2a53f7fb0944f2d5720371b23"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-183fbda8d590393f7f3faa763c2cb6344b42556f949b59a0f8f77a01ec8572c4.json b/rust/cloud-storage/email/.sqlx/query-183fbda8d590393f7f3faa763c2cb6344b42556f949b59a0f8f77a01ec8572c4.json
new file mode 100644
index 0000000000..3a8125cf5d
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-183fbda8d590393f7f3faa763c2cb6344b42556f949b59a0f8f77a01ec8572c4.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n ea.message_id,\n ea.id,\n ea.provider_attachment_id,\n ea.filename,\n ea.mime_type,\n ea.size_bytes,\n eas.sfs_id as \"sfs_id?\",\n ea.content_id\n FROM email_attachments ea\n LEFT JOIN email_attachments_sfs eas ON ea.id = eas.attachment_id\n WHERE ea.message_id = ANY($1)\n ORDER BY ea.message_id, ea.filename NULLS LAST\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "provider_attachment_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "filename",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "mime_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "size_bytes",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 6,
+ "name": "sfs_id?",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "content_id",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ false,
+ true
+ ]
+ },
+ "hash": "183fbda8d590393f7f3faa763c2cb6344b42556f949b59a0f8f77a01ec8572c4"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-29496c090bdffe2b771ad704687525136fcd17a1d3e680142e5d0f9e253af578.json b/rust/cloud-storage/email/.sqlx/query-29496c090bdffe2b771ad704687525136fcd17a1d3e680142e5d0f9e253af578.json
new file mode 100644
index 0000000000..918f0d6d3d
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-29496c090bdffe2b771ad704687525136fcd17a1d3e680142e5d0f9e253af578.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT message_id, send_time\n FROM email_scheduled_messages\n WHERE message_id = ANY($1) AND sent = false\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "send_time",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "29496c090bdffe2b771ad704687525136fcd17a1d3e680142e5d0f9e253af578"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-5872188529ff33ad61652722274e0b1a9725cd2ce86589e9669470a819554d93.json b/rust/cloud-storage/email/.sqlx/query-2c1ca56683bc4ff97f5b9768e6da72ee6558c2ea8bb9b58237370e3cb80d309c.json
similarity index 64%
rename from rust/cloud-storage/email/.sqlx/query-5872188529ff33ad61652722274e0b1a9725cd2ce86589e9669470a819554d93.json
rename to rust/cloud-storage/email/.sqlx/query-2c1ca56683bc4ff97f5b9768e6da72ee6558c2ea8bb9b58237370e3cb80d309c.json
index 4fb1968443..54b0e1cd14 100644
--- a/rust/cloud-storage/email/.sqlx/query-5872188529ff33ad61652722274e0b1a9725cd2ce86589e9669470a819554d93.json
+++ b/rust/cloud-storage/email/.sqlx/query-2c1ca56683bc4ff97f5b9768e6da72ee6558c2ea8bb9b58237370e3cb80d309c.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n a.id,\n a.message_id,\n a.provider_attachment_id,\n a.filename,\n a.mime_type,\n a.size_bytes,\n a.content_id,\n a.created_at,\n m.thread_id\n FROM\n email_attachments a\n JOIN\n email_messages m ON a.message_id = m.id\n WHERE\n m.thread_id = ANY($1)\n ORDER BY\n a.created_at ASC\n ",
+ "query": "\n SELECT\n a.id,\n a.message_id,\n a.provider_attachment_id,\n a.filename,\n a.mime_type,\n a.size_bytes,\n a.content_id,\n a.created_at,\n m.thread_id\n FROM\n email_attachments a\n JOIN\n email_messages m ON a.message_id = m.id\n WHERE\n m.thread_id = ANY($1)\n ORDER BY\n a.created_at ASC\n ",
"describe": {
"columns": [
{
@@ -66,5 +66,5 @@
false
]
},
- "hash": "5872188529ff33ad61652722274e0b1a9725cd2ce86589e9669470a819554d93"
+ "hash": "2c1ca56683bc4ff97f5b9768e6da72ee6558c2ea8bb9b58237370e3cb80d309c"
}
diff --git a/rust/cloud-storage/email/.sqlx/query-38a0912ba2639fa895a2ab9735276426f9f905984ca0e66b2203783760fb658b.json b/rust/cloud-storage/email/.sqlx/query-45a55e0ea2f0cc2d7583ede119ffd4059933d25cca50775c74f1ef5a0224493c.json
similarity index 63%
rename from rust/cloud-storage/email/.sqlx/query-38a0912ba2639fa895a2ab9735276426f9f905984ca0e66b2203783760fb658b.json
rename to rust/cloud-storage/email/.sqlx/query-45a55e0ea2f0cc2d7583ede119ffd4059933d25cca50775c74f1ef5a0224493c.json
index 2d8d74ef9e..58bc367329 100644
--- a/rust/cloud-storage/email/.sqlx/query-38a0912ba2639fa895a2ab9735276426f9f905984ca0e66b2203783760fb658b.json
+++ b/rust/cloud-storage/email/.sqlx/query-45a55e0ea2f0cc2d7583ede119ffd4059933d25cca50775c74f1ef5a0224493c.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n m.thread_id,\n c.id, c.link_id, c.email_address, COALESCE(m.from_name, c.name) as \"name\", c.sfs_photo_url\n FROM email_messages m\n JOIN email_contacts c ON m.from_contact_id = c.id\n WHERE m.thread_id = ANY($1) AND m.from_contact_id IS NOT NULL\n ORDER BY m.created_at ASC\n ",
+ "query": "\n SELECT\n m.thread_id,\n c.id, c.link_id, c.email_address, COALESCE(m.from_name, c.name) as \"name\", c.sfs_photo_url\n FROM email_messages m\n JOIN email_contacts c ON m.from_contact_id = c.id\n WHERE m.thread_id = ANY($1) AND m.from_contact_id IS NOT NULL\n ORDER BY m.created_at ASC\n ",
"describe": {
"columns": [
{
@@ -48,5 +48,5 @@
true
]
},
- "hash": "38a0912ba2639fa895a2ab9735276426f9f905984ca0e66b2203783760fb658b"
+ "hash": "45a55e0ea2f0cc2d7583ede119ffd4059933d25cca50775c74f1ef5a0224493c"
}
diff --git a/rust/cloud-storage/email/.sqlx/query-4cc88f2a38cb0722282ef262adefd9fcb0d4778c5dc308720710e8f5e9995911.json b/rust/cloud-storage/email/.sqlx/query-4cc88f2a38cb0722282ef262adefd9fcb0d4778c5dc308720710e8f5e9995911.json
new file mode 100644
index 0000000000..e243f96402
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-4cc88f2a38cb0722282ef262adefd9fcb0d4778c5dc308720710e8f5e9995911.json
@@ -0,0 +1,57 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n mr.message_id,\n c.email_address,\n COALESCE(mr.name, c.name) as \"name\",\n c.sfs_photo_url,\n mr.recipient_type as \"recipient_type!: DbRecipientType\"\n FROM email_messages m\n JOIN email_message_recipients mr ON m.id = mr.message_id\n JOIN email_contacts c ON mr.contact_id = c.id\n WHERE m.id = ANY($1)\n ORDER BY mr.message_id, mr.recipient_type\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 3,
+ "name": "sfs_photo_url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "recipient_type!: DbRecipientType",
+ "type_info": {
+ "Custom": {
+ "name": "email_recipient_type",
+ "kind": {
+ "Enum": [
+ "TO",
+ "CC",
+ "BCC"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ true,
+ false
+ ]
+ },
+ "hash": "4cc88f2a38cb0722282ef262adefd9fcb0d4778c5dc308720710e8f5e9995911"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-87e0c17146266f40e2f76a27c0e60bd057a7efe02fe027f9514cc8fbdba2159b.json b/rust/cloud-storage/email/.sqlx/query-87e0c17146266f40e2f76a27c0e60bd057a7efe02fe027f9514cc8fbdba2159b.json
new file mode 100644
index 0000000000..e8401c2e59
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-87e0c17146266f40e2f76a27c0e60bd057a7efe02fe027f9514cc8fbdba2159b.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.id as message_id,\n c.email_address,\n COALESCE(m.from_name, c.name) as \"name\",\n c.sfs_photo_url\n FROM email_messages m\n INNER JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.id = ANY($1)\n AND m.from_contact_id IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 3,
+ "name": "sfs_photo_url",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ true
+ ]
+ },
+ "hash": "87e0c17146266f40e2f76a27c0e60bd057a7efe02fe027f9514cc8fbdba2159b"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-922f058d237b9ffe46e13677ce2e6c4f4b39b7ae7b8b4dd248f54714d842a08e.json b/rust/cloud-storage/email/.sqlx/query-922f058d237b9ffe46e13677ce2e6c4f4b39b7ae7b8b4dd248f54714d842a08e.json
new file mode 100644
index 0000000000..0fd14fd3e9
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-922f058d237b9ffe46e13677ce2e6c4f4b39b7ae7b8b4dd248f54714d842a08e.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n eaf.message_id as draft_id,\n eaf.attachment_id,\n ea.provider_attachment_id,\n orig_msg.provider_id as \"message_provider_id!\",\n ea.filename,\n ea.mime_type,\n ea.size_bytes\n FROM email_attachments_fwd eaf\n JOIN email_attachments ea ON eaf.attachment_id = ea.id\n JOIN email_messages orig_msg ON ea.message_id = orig_msg.id\n WHERE eaf.message_id = ANY($1)\n ORDER BY eaf.message_id, ea.filename ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "draft_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "attachment_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "provider_attachment_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "message_provider_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "filename",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "mime_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 6,
+ "name": "size_bytes",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "922f058d237b9ffe46e13677ce2e6c4f4b39b7ae7b8b4dd248f54714d842a08e"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-9f5c0108230743e209902d457637931a2cbc77192ce513473a4f5e3498b8533c.json b/rust/cloud-storage/email/.sqlx/query-9f5c0108230743e209902d457637931a2cbc77192ce513473a4f5e3498b8533c.json
new file mode 100644
index 0000000000..e8b14cc25a
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-9f5c0108230743e209902d457637931a2cbc77192ce513473a4f5e3498b8533c.json
@@ -0,0 +1,101 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n ml.message_id,\n l.id,\n l.link_id,\n l.provider_label_id,\n l.name,\n l.created_at,\n l.message_list_visibility as \"message_list_visibility: _\",\n l.label_list_visibility as \"label_list_visibility: _\",\n l.type as \"type_: _\"\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = ANY($1)\n ORDER BY ml.message_id, l.name\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "provider_label_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "message_list_visibility: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_message_list_visibility_enum",
+ "kind": {
+ "Enum": [
+ "Show",
+ "Hide"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 7,
+ "name": "label_list_visibility: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_label_list_visibility_enum",
+ "kind": {
+ "Enum": [
+ "LabelShow",
+ "LabelShowIfUnread",
+ "LabelHide"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 8,
+ "name": "type_: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_label_type_enum",
+ "kind": {
+ "Enum": [
+ "System",
+ "User"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "9f5c0108230743e209902d457637931a2cbc77192ce513473a4f5e3498b8533c"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-f3037d59872cb8e1e2921a05cbd4b0e5b5a9a48ee90e22ab1824611688854692.json b/rust/cloud-storage/email/.sqlx/query-c8569a737734eab039a3ca9759478b203596330442305a6f3925edf67a8b52a3.json
similarity index 78%
rename from rust/cloud-storage/email/.sqlx/query-f3037d59872cb8e1e2921a05cbd4b0e5b5a9a48ee90e22ab1824611688854692.json
rename to rust/cloud-storage/email/.sqlx/query-c8569a737734eab039a3ca9759478b203596330442305a6f3925edf67a8b52a3.json
index adfb9780cf..dec05aa8a8 100644
--- a/rust/cloud-storage/email/.sqlx/query-f3037d59872cb8e1e2921a05cbd4b0e5b5a9a48ee90e22ab1824611688854692.json
+++ b/rust/cloud-storage/email/.sqlx/query-c8569a737734eab039a3ca9759478b203596330442305a6f3925edf67a8b52a3.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, created_at, updated_at\n FROM email_links\n WHERE fusionauth_user_id = $1 AND macro_id = $2 AND provider = $3\n LIMIT 1\n ",
+ "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, created_at, updated_at\n FROM email_links\n WHERE fusionauth_user_id = $1 AND macro_id = $2 AND provider = $3\n LIMIT 1\n ",
"describe": {
"columns": [
{
@@ -80,5 +80,5 @@
false
]
},
- "hash": "f3037d59872cb8e1e2921a05cbd4b0e5b5a9a48ee90e22ab1824611688854692"
+ "hash": "c8569a737734eab039a3ca9759478b203596330442305a6f3925edf67a8b52a3"
}
diff --git a/rust/cloud-storage/email/.sqlx/query-c8e8b950c4f8645562fb36042b549b0c1f6ec3da1b9beb4d212ddd5bc640948e.json b/rust/cloud-storage/email/.sqlx/query-c8e8b950c4f8645562fb36042b549b0c1f6ec3da1b9beb4d212ddd5bc640948e.json
new file mode 100644
index 0000000000..c15673d65f
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-c8e8b950c4f8645562fb36042b549b0c1f6ec3da1b9beb4d212ddd5bc640948e.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, draft_id, file_name, content_type, sha, size, s3_key\n FROM email_attachments_drafts\n WHERE draft_id = ANY($1)\n ORDER BY draft_id, file_name ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "draft_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "file_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "content_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "sha",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "size",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 6,
+ "name": "s3_key",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "c8e8b950c4f8645562fb36042b549b0c1f6ec3da1b9beb4d212ddd5bc640948e"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-f33cae291a4c2d553de0f61e5c32bcc09c162de5ca96535567a6e307e86b5fb9.json b/rust/cloud-storage/email/.sqlx/query-d501983b009e4418f1753f03db0ea12db11f18e4a89a76c87b4c8ddda431cbdb.json
similarity index 73%
rename from rust/cloud-storage/email/.sqlx/query-f33cae291a4c2d553de0f61e5c32bcc09c162de5ca96535567a6e307e86b5fb9.json
rename to rust/cloud-storage/email/.sqlx/query-d501983b009e4418f1753f03db0ea12db11f18e4a89a76c87b4c8ddda431cbdb.json
index 1ac755ddfb..07bca28bb4 100644
--- a/rust/cloud-storage/email/.sqlx/query-f33cae291a4c2d553de0f61e5c32bcc09c162de5ca96535567a6e307e86b5fb9.json
+++ b/rust/cloud-storage/email/.sqlx/query-d501983b009e4418f1753f03db0ea12db11f18e4a89a76c87b4c8ddda431cbdb.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT DISTINCT ON (l.id, m.thread_id)\n l.id,\n m.thread_id as \"thread_id!\",\n l.link_id,\n l.provider_label_id,\n l.name,\n l.created_at,\n l.message_list_visibility as \"message_list_visibility: _\",\n l.label_list_visibility as \"label_list_visibility: _\",\n l.type as \"type_: _\"\n FROM\n email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = ANY($1)\n ",
+ "query": "\n SELECT DISTINCT ON (l.id, m.thread_id)\n l.id,\n m.thread_id as \"thread_id!\",\n l.link_id,\n l.provider_label_id,\n l.name,\n l.created_at,\n l.message_list_visibility as \"message_list_visibility: _\",\n l.label_list_visibility as \"label_list_visibility: _\",\n l.type as \"type_: _\"\n FROM\n email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = ANY($1)\n ",
"describe": {
"columns": [
{
@@ -97,5 +97,5 @@
false
]
},
- "hash": "f33cae291a4c2d553de0f61e5c32bcc09c162de5ca96535567a6e307e86b5fb9"
+ "hash": "d501983b009e4418f1753f03db0ea12db11f18e4a89a76c87b4c8ddda431cbdb"
}
diff --git a/rust/cloud-storage/email/.sqlx/query-f95b295c9ffa7b96a7907c43c0557d60af3f02fc72c3f541bc94c903034a6748.json b/rust/cloud-storage/email/.sqlx/query-f95b295c9ffa7b96a7907c43c0557d60af3f02fc72c3f541bc94c903034a6748.json
new file mode 100644
index 0000000000..8f396b9fba
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-f95b295c9ffa7b96a7907c43c0557d60af3f02fc72c3f541bc94c903034a6748.json
@@ -0,0 +1,162 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id, provider_id, thread_id, provider_thread_id, replying_to_id,\n global_id, link_id, provider_history_id, internal_date_ts, snippet,\n size_estimate, subject, sent_at, has_attachments, is_read, is_starred,\n is_sent, is_draft, body_text, body_html_sanitized, body_macro,\n headers_jsonb, created_at, updated_at\n FROM email_messages\n WHERE thread_id = $1\n ORDER BY internal_date_ts DESC\n LIMIT $2 OFFSET $3\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "provider_thread_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "replying_to_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 5,
+ "name": "global_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "provider_history_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "internal_date_ts",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "snippet",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "size_estimate",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 11,
+ "name": "subject",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
+ "name": "sent_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 13,
+ "name": "has_attachments",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 14,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 15,
+ "name": "is_starred",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 16,
+ "name": "is_sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 17,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 18,
+ "name": "body_text",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 19,
+ "name": "body_html_sanitized",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 20,
+ "name": "body_macro",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 21,
+ "name": "headers_jsonb",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 22,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 23,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ true,
+ true,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "f95b295c9ffa7b96a7907c43c0557d60af3f02fc72c3f541bc94c903034a6748"
+}
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index dcb1fa34c7..a9fe34215c 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -21,6 +21,8 @@ ports = ["dep:tokio", "frecency/ports"]
[dependencies]
anyhow = { workspace = true }
+entity_access = { path = "../entity_access" }
+futures = { workspace = true }
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
chrono = { workspace = true, features = ["serde"] }
@@ -38,6 +40,7 @@ models_pagination = { path = "../models_pagination" }
recursion = { workspace = true }
schemars = { workspace = true, optional = true, features = ["uuid1"] }
serde = { workspace = true }
+serde_json = { workspace = true }
serde_with = { workspace = true }
sqlx = { workspace = true, optional = true }
strum = { workspace = true }
diff --git a/rust/cloud-storage/email/fixtures/email_message.sql b/rust/cloud-storage/email/fixtures/email_message.sql
new file mode 100644
index 0000000000..f2d0ff0b85
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_message.sql
@@ -0,0 +1,120 @@
+-- Fixture for testing message-level queries:
+-- senders_by_message_ids, recipients_by_message_ids, labels_by_message_ids,
+-- attachments_by_message_ids, draft_attachments_by_message_ids,
+-- forwarded_attachments_by_message_ids, scheduled_send_times_by_message_ids,
+-- attachments_by_thread_ids, contacts_by_thread_ids
+
+-- Insert test link
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'fa-user-1', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Insert contacts
+-- c1 = alice, c2 = bob, c3 = carol
+INSERT INTO email_contacts (id, link_id, email_address, name, sfs_photo_url, created_at, updated_at)
+VALUES
+ ('c0000001-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Alice Smith', 'https://photos.example.com/alice.jpg', NOW(), NOW()),
+ ('c0000002-0000-0000-0000-000000000002', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Bob Jones', NULL, NOW(), NOW()),
+ ('c0000003-0000-0000-0000-000000000003', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Carol White', 'https://photos.example.com/carol.jpg', NOW(), NOW());
+
+-- Insert threads
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES
+ ('11111111-1111-1111-1111-111111111111', 'thread-1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW()),
+ ('22222222-2222-2222-2222-222222222222', 'thread-2', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW()),
+ ('33333333-3333-3333-3333-333333333333', 'thread-3', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW());
+
+-- Insert labels
+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)
+VALUES
+ ('bb000001-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),
+ ('bb000002-0000-0000-0000-000000000002', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'IMPORTANT', 'IMPORTANT', 'Hide', 'LabelHide', 'System', NOW()),
+ ('bb000003-0000-0000-0000-000000000003', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Label_custom', 'Work', 'Show', 'LabelShow', 'User', NOW());
+
+-- Insert messages
+-- msg1: thread 1, from alice, has from_name override, has attachments
+INSERT INTO email_messages (id, provider_id, thread_id, link_id, from_contact_id, from_name, internal_date_ts, snippet, subject, is_read, is_sent, is_draft, has_attachments, created_at, updated_at)
+VALUES
+ ('ee000001-0000-0000-0000-000000000001', 'provider-msg-1', '11111111-1111-1111-1111-111111111111', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ 'c0000001-0000-0000-0000-000000000001', 'Alice S.', '2025-01-10 10:00:00+00', 'Hello snippet', 'Hello', true, false, false, true, '2025-01-10 10:00:00+00', '2025-01-10 10:00:00+00');
+
+-- msg2: thread 1, from bob, no from_name override
+INSERT INTO email_messages (id, provider_id, thread_id, link_id, from_contact_id, internal_date_ts, snippet, subject, is_read, is_sent, is_draft, has_attachments, created_at, updated_at)
+VALUES
+ ('ee000002-0000-0000-0000-000000000002', 'provider-msg-2', '11111111-1111-1111-1111-111111111111', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ 'c0000002-0000-0000-0000-000000000002', '2025-01-11 11:00:00+00', 'Reply snippet', 'Re: Hello', false, true, false, false, '2025-01-11 11:00:00+00', '2025-01-11 11:00:00+00');
+
+-- msg3: thread 2, a draft (no from_contact)
+INSERT INTO email_messages (id, provider_id, thread_id, link_id, internal_date_ts, snippet, subject, is_read, is_sent, is_draft, has_attachments, created_at, updated_at)
+VALUES
+ ('ee000003-0000-0000-0000-000000000003', 'provider-msg-3', '22222222-2222-2222-2222-222222222222', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ '2025-02-01 12:00:00+00', 'Draft snippet', 'Draft subject', false, false, true, false, '2025-02-01 12:00:00+00', '2025-02-01 12:00:00+00');
+
+-- msg4: thread 3, from alice (no from_name override, so contact.name is used)
+INSERT INTO email_messages (id, provider_id, thread_id, link_id, from_contact_id, internal_date_ts, snippet, subject, is_read, is_sent, is_draft, has_attachments, created_at, updated_at)
+VALUES
+ ('ee000004-0000-0000-0000-000000000004', 'provider-msg-4', '33333333-3333-3333-3333-333333333333', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ 'c0000001-0000-0000-0000-000000000001', '2025-03-01 08:00:00+00', 'Thread 3 snippet', 'Thread 3 subject', true, false, false, false, '2025-03-01 08:00:00+00', '2025-03-01 08:00:00+00');
+
+-- Recipients for msg1: bob=TO, carol=CC
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)
+VALUES
+ ('ee000001-0000-0000-0000-000000000001', 'c0000002-0000-0000-0000-000000000002', 'TO', NULL),
+ ('ee000001-0000-0000-0000-000000000001', 'c0000003-0000-0000-0000-000000000003', 'CC', 'Carol W.');
+
+-- Recipients for msg2: alice=TO, carol=BCC
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)
+VALUES
+ ('ee000002-0000-0000-0000-000000000002', 'c0000001-0000-0000-0000-000000000001', 'TO', NULL),
+ ('ee000002-0000-0000-0000-000000000002', 'c0000003-0000-0000-0000-000000000003', 'BCC', NULL);
+
+-- Message labels
+-- msg1: INBOX + IMPORTANT
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('ee000001-0000-0000-0000-000000000001', 'bb000001-0000-0000-0000-000000000001'),
+ ('ee000001-0000-0000-0000-000000000001', 'bb000002-0000-0000-0000-000000000002');
+
+-- msg2: INBOX + Work (user label)
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('ee000002-0000-0000-0000-000000000002', 'bb000001-0000-0000-0000-000000000001'),
+ ('ee000002-0000-0000-0000-000000000002', 'bb000003-0000-0000-0000-000000000003');
+
+-- Attachments on msg1
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at)
+VALUES
+ ('aa000001-0000-0000-0000-000000000001', 'ee000001-0000-0000-0000-000000000001', 'prov-att-1', 'document.pdf', 'application/pdf', 102400, NULL, '2025-01-10 10:00:00+00'),
+ ('aa000002-0000-0000-0000-000000000002', 'ee000001-0000-0000-0000-000000000001', 'prov-att-2', 'image.png', 'image/png', 51200, 'cid-inline-1', '2025-01-10 10:01:00+00');
+
+-- Attachment on msg4 (thread 3)
+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at)
+VALUES
+ ('aa000003-0000-0000-0000-000000000003', 'ee000004-0000-0000-0000-000000000004', 'prov-att-3', 'report.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 204800, NULL, '2025-03-01 08:00:00+00');
+
+-- SFS mapping for attachment aa000001
+INSERT INTO email_attachments_sfs (id, attachment_id, sfs_id, created_at)
+VALUES
+ ('ff000001-0000-0000-0000-000000000001', 'aa000001-0000-0000-0000-000000000001', 'ff000002-0000-0000-0000-000000000002', NOW());
+
+-- Draft attachments for msg3 (the draft)
+INSERT INTO email_attachments_drafts (id, draft_id, file_name, content_type, sha, size, s3_key, created_at)
+VALUES
+ ('dd000001-0000-0000-0000-000000000001', 'ee000003-0000-0000-0000-000000000003', 'alpha.txt', 'text/plain', 'sha256-aaa', 100, 's3://bucket/alpha.txt', NOW()),
+ ('dd000002-0000-0000-0000-000000000002', 'ee000003-0000-0000-0000-000000000003', 'beta.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'sha256-bbb', 5000, 's3://bucket/beta.docx', NOW());
+
+-- Forwarded attachments: msg3 (draft) forwards attachment aa000001 from msg1
+INSERT INTO email_attachments_fwd (message_id, attachment_id, created_at)
+VALUES
+ ('ee000003-0000-0000-0000-000000000003', 'aa000001-0000-0000-0000-000000000001', NOW());
+
+-- Scheduled sends
+-- msg3: scheduled, not sent
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'ee000003-0000-0000-0000-000000000003', '2025-03-01 09:00:00+00', false, NOW(), NOW());
+
+-- msg2: scheduled but already sent (should be excluded)
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'ee000002-0000-0000-0000-000000000002', '2025-01-11 12:00:00+00', true, NOW(), NOW());
diff --git a/rust/cloud-storage/email/fixtures/email_thread.sql b/rust/cloud-storage/email/fixtures/email_thread.sql
new file mode 100644
index 0000000000..18e0c57147
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_thread.sql
@@ -0,0 +1,40 @@
+-- Fixture for testing thread_by_id and messages_by_thread_id_paginated queries
+
+-- Insert test link
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'fa-user-1', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Insert test threads
+-- Thread 1: inbox_visible, unread, with timestamps
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts, created_at, updated_at)
+VALUES
+ ('11111111-1111-1111-1111-111111111111', 'provider-thread-1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false,
+ '2025-01-15 10:00:00+00', '2025-01-14 09:00:00+00', '2025-01-15 10:00:00+00', '2025-01-01 00:00:00+00', '2025-01-15 10:00:00+00');
+
+-- Thread 2: read, not inbox_visible, no outbound
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, latest_inbound_message_ts, latest_non_spam_message_ts, created_at, updated_at)
+VALUES
+ ('22222222-2222-2222-2222-222222222222', 'provider-thread-2', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, true,
+ '2025-02-01 12:00:00+00', '2025-02-01 12:00:00+00', '2025-01-10 00:00:00+00', '2025-02-01 12:00:00+00');
+
+-- Thread 3: empty thread (no messages) for edge case testing
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES
+ ('33333333-3333-3333-3333-333333333333', 'provider-thread-3', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW());
+
+-- Insert messages for Thread 1 (3 messages with different timestamps for pagination testing)
+INSERT INTO email_messages (id, provider_id, thread_id, link_id, internal_date_ts, snippet, subject, is_read, is_sent, is_draft, has_attachments, created_at, updated_at)
+VALUES
+ ('11111111-aaaa-0001-aaaa-111111111111', 'msg-1-oldest', '11111111-1111-1111-1111-111111111111', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ '2025-01-13 08:00:00+00', 'First message snippet', 'Hello', false, false, false, false, '2025-01-13 08:00:00+00', '2025-01-13 08:00:00+00'),
+ ('11111111-aaaa-0002-aaaa-111111111111', 'msg-1-middle', '11111111-1111-1111-1111-111111111111', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ '2025-01-14 09:00:00+00', 'Reply snippet', 'Re: Hello', true, true, false, false, '2025-01-14 09:00:00+00', '2025-01-14 09:00:00+00'),
+ ('11111111-aaaa-0003-aaaa-111111111111', 'msg-1-newest', '11111111-1111-1111-1111-111111111111', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ '2025-01-15 10:00:00+00', 'Latest reply', 'Re: Re: Hello', false, false, false, true, '2025-01-15 10:00:00+00', '2025-01-15 10:00:00+00');
+
+-- Insert messages for Thread 2 (1 message)
+INSERT INTO email_messages (id, provider_id, thread_id, link_id, internal_date_ts, snippet, subject, is_read, is_sent, is_draft, has_attachments, created_at, updated_at)
+VALUES
+ ('22222222-aaaa-0001-aaaa-222222222222', 'msg-2-only', '22222222-2222-2222-2222-222222222222', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ '2025-02-01 12:00:00+00', 'Thread 2 message', 'Different thread', true, false, false, false, '2025-02-01 12:00:00+00', '2025-02-01 12:00:00+00');
diff --git a/rust/cloud-storage/email/src/domain.rs b/rust/cloud-storage/email/src/domain.rs
index 2b79af4ee0..9b812e494c 100644
--- a/rust/cloud-storage/email/src/domain.rs
+++ b/rust/cloud-storage/email/src/domain.rs
@@ -1,5 +1,7 @@
pub mod models;
+#[cfg(feature = "ports")]
+pub mod assembler;
#[cfg(feature = "ports")]
pub mod ports;
#[cfg(feature = "ports")]
diff --git a/rust/cloud-storage/email/src/domain/assembler.rs b/rust/cloud-storage/email/src/domain/assembler.rs
new file mode 100644
index 0000000000..8bf9f5833b
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/assembler.rs
@@ -0,0 +1,76 @@
+use crate::domain::models::{
+ AttachmentDraft, AttachmentForwarded, ContactInfo, Message, MessageAttachment, MessageLabel,
+ MessageRow, RecipientType, Thread, ThreadRow,
+};
+
+pub fn split_recipients(
+ recipients: Vec<(ContactInfo, RecipientType)>,
+) -> (Vec<ContactInfo>, Vec<ContactInfo>, Vec<ContactInfo>) {
+ let mut to = Vec::new();
+ let mut cc = Vec::new();
+ let mut bcc = Vec::new();
+ for (contact, r_type) in recipients {
+ match r_type {
+ RecipientType::To => to.push(contact),
+ RecipientType::Cc => cc.push(contact),
+ RecipientType::Bcc => bcc.push(contact),
+ }
+ }
+ (to, cc, bcc)
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn message_from_row(
+ row: MessageRow,
+ from: Option<ContactInfo>,
+ to: Vec<ContactInfo>,
+ cc: Vec<ContactInfo>,
+ bcc: Vec<ContactInfo>,
+ labels: Vec<MessageLabel>,
+ attachments: Vec<MessageAttachment>,
+ attachments_draft: Vec<AttachmentDraft>,
+ attachments_forwarded: Vec<AttachmentForwarded>,
+ scheduled_send_time: Option<chrono::DateTime<chrono::Utc>>,
+ body_replyless: Option<String>,
+) -> Message {
+ Message {
+ db_id: row.db_id,
+ provider_id: row.provider_id,
+ thread_db_id: row.thread_db_id,
+ provider_thread_id: row.provider_thread_id,
+ replying_to_id: row.replying_to_id,
+ global_id: row.global_id,
+ link_id: row.link_id,
+ subject: row.subject,
+ snippet: row.snippet,
+ provider_history_id: row.provider_history_id,
+ internal_date_ts: row.internal_date_ts,
+ sent_at: row.sent_at,
+ size_estimate: row.size_estimate,
+ is_read: row.is_read,
+ is_starred: row.is_starred,
+ is_sent: row.is_sent,
+ is_draft: row.is_draft,
+ has_attachments: row.has_attachments,
+ scheduled_send_time,
+ from,
+ to,
+ cc,
+ bcc,
+ labels,
+ body_text: row.body_text,
+ body_html_sanitized: row.body_html_sanitized,
+ body_macro: row.body_macro,
+ body_replyless,
+ attachments,
+ attachments_draft,
+ attachments_forwarded,
+ headers_json: row.headers_json,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ }
+}
+
+pub fn thread_from_row(row: ThreadRow, messages: Vec<Message>) -> Thread {
+ Thread { row, messages }
+}
diff --git a/rust/cloud-storage/email/src/domain/models/attachment.rs b/rust/cloud-storage/email/src/domain/models/attachment.rs
new file mode 100644
index 0000000000..ad5389d67a
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/attachment.rs
@@ -0,0 +1,84 @@
+use chrono::{DateTime, Utc};
+use models_pagination::Identify;
+use uuid::Uuid;
+
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct Attachment {
+ pub id: Uuid,
+ pub(crate) thread_id: Uuid,
+ pub message_id: Uuid,
+ // a different value is returned by the gmail API for this each time you fetch a message -
+ // don't make the mistake of using it to uniquely identify an attachment
+ pub provider_attachment_id: Option<String>,
+ pub filename: Option<String>,
+ pub mime_type: Option<String>,
+ pub size_bytes: Option<i64>,
+ pub content_id: Option<String>,
+ pub created_at: DateTime<Utc>,
+}
+
+impl Identify for Attachment {
+ type Id = Uuid;
+
+ fn id(&self) -> Self::Id {
+ self.id
+ }
+}
+
+/// A provider attachment on a message.
+#[derive(Debug, Clone)]
+pub struct MessageAttachment {
+ /// Database ID of the attachment.
+ pub db_id: uuid::Uuid,
+ /// Provider attachment ID.
+ pub provider_id: Option<String>,
+ /// Original filename.
+ pub filename: Option<String>,
+ /// MIME type.
+ pub mime_type: Option<String>,
+ /// Size in bytes.
+ pub size_bytes: Option<i64>,
+ /// SFS (static file storage) ID.
+ pub sfs_id: Option<uuid::Uuid>,
+ /// Content ID (for inline attachments).
+ pub content_id: Option<String>,
+}
+
+/// A draft attachment uploaded to S3.
+#[derive(Debug, Clone)]
+pub struct AttachmentDraft {
+ /// Unique ID of the draft attachment record.
+ pub id: uuid::Uuid,
+ /// ID of the draft message this attachment belongs to.
+ pub draft_id: uuid::Uuid,
+ /// Original file name.
+ pub file_name: String,
+ /// MIME type.
+ pub content_type: String,
+ /// SHA-256 hash.
+ pub sha: String,
+ /// File size in bytes.
+ pub size: i32,
+ /// S3 object key.
+ pub s3_key: String,
+}
+
+/// A forwarded attachment linking a draft to an original message's attachment.
+#[derive(Debug, Clone)]
+pub struct AttachmentForwarded {
+ /// UUID of the original attachment.
+ pub attachment_id: uuid::Uuid,
+ /// ID of the draft message.
+ pub draft_id: uuid::Uuid,
+ /// Provider attachment ID for fetching from the provider API.
+ pub provider_attachment_id: Option<String>,
+ /// Provider message ID of the original message.
+ pub message_provider_id: String,
+ /// Original filename.
+ pub filename: Option<String>,
+ /// MIME type.
+ pub mime_type: Option<String>,
+ /// Size in bytes.
+ pub size_bytes: Option<i64>,
+}
diff --git a/rust/cloud-storage/email/src/domain/models/contact.rs b/rust/cloud-storage/email/src/domain/models/contact.rs
new file mode 100644
index 0000000000..62139e6941
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/contact.rs
@@ -0,0 +1,34 @@
+use uuid::Uuid;
+
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct Contact {
+ pub id: Uuid,
+ pub(crate) thread_id: Uuid,
+ pub link_id: Uuid,
+ pub name: Option<String>,
+ pub email_address: Option<String>,
+ pub sfs_photo_url: Option<String>,
+}
+
+/// Contact information for a message sender or recipient.
+#[derive(Debug, Clone)]
+pub struct ContactInfo {
+ /// Email address of the contact.
+ pub email: String,
+ /// Display name of the contact.
+ pub name: Option<String>,
+ /// Profile photo URL of the contact.
+ pub photo_url: Option<String>,
+}
+
+/// The type of recipient for a message.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RecipientType {
+ /// To recipient.
+ To,
+ /// Cc recipient.
+ Cc,
+ /// Bcc recipient.
+ Bcc,
+}
diff --git a/rust/cloud-storage/email/src/domain/models/error.rs b/rust/cloud-storage/email/src/domain/models/error.rs
new file mode 100644
index 0000000000..326d4d103a
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/error.rs
@@ -0,0 +1,10 @@
+use frecency::domain::models::FrecencyQueryErr;
+use thiserror::Error;
+
+#[derive(Debug, Error)]
+pub enum EmailErr {
+ #[error(transparent)]
+ RepoErr(#[from] anyhow::Error),
+ #[error(transparent)]
+ Frecency(#[from] FrecencyQueryErr),
+}
diff --git a/rust/cloud-storage/email/src/domain/models/label.rs b/rust/cloud-storage/email/src/domain/models/label.rs
new file mode 100644
index 0000000000..63a5209cc1
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/label.rs
@@ -0,0 +1,55 @@
+use chrono::{DateTime, Utc};
+use uuid::Uuid;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MessageListVisibility {
+ Show,
+ Hide,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LabelListVisibility {
+ LabelShow,
+ LabelShowIfUnread,
+ LabelHide,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LabelType {
+ System,
+ User,
+}
+
+#[derive(Debug, Clone)]
+pub struct Label {
+ pub id: Uuid,
+ pub(crate) thread_id: Uuid,
+ pub link_id: Uuid,
+ pub provider_label_id: String,
+ pub name: String,
+ pub created_at: DateTime<Utc>,
+ pub message_list_visibility: MessageListVisibility,
+ pub label_list_visibility: LabelListVisibility,
+ pub type_: LabelType,
+}
+
+/// A label on a message.
+#[derive(Debug, Clone)]
+pub struct MessageLabel {
+ /// Database ID of the label.
+ pub id: Option<uuid::Uuid>,
+ /// Link ID the label belongs to.
+ pub link_id: uuid::Uuid,
+ /// Provider label ID (e.g. "INBOX", "SENT").
+ pub provider_label_id: String,
+ /// Human-readable label name.
+ pub name: Option<String>,
+ /// When the label was created.
+ pub created_at: DateTime<Utc>,
+ /// Message list visibility setting.
+ pub message_list_visibility: Option<MessageListVisibility>,
+ /// Label list visibility setting.
+ pub label_list_visibility: Option<LabelListVisibility>,
+ /// Label type (system or user).
+ pub type_: Option<LabelType>,
+}
diff --git a/rust/cloud-storage/email/src/domain/models/link.rs b/rust/cloud-storage/email/src/domain/models/link.rs
new file mode 100644
index 0000000000..fc025bc3bd
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/link.rs
@@ -0,0 +1,29 @@
+use chrono::{DateTime, Utc};
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
+use uuid::Uuid;
+
+/// The provider of this email
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UserProvider {
+ Gmail,
+}
+
+impl UserProvider {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ UserProvider::Gmail => "GMAIL",
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct Link {
+ pub id: Uuid,
+ pub macro_id: MacroUserIdStr<'static>,
+ pub fusionauth_user_id: String,
+ pub email_address: EmailStr<'static>,
+ pub provider: UserProvider,
+ pub is_sync_active: bool,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
diff --git a/rust/cloud-storage/email/src/domain/models/message.rs b/rust/cloud-storage/email/src/domain/models/message.rs
new file mode 100644
index 0000000000..32992037dd
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/message.rs
@@ -0,0 +1,131 @@
+use chrono::{DateTime, Utc};
+
+use super::attachment::{AttachmentDraft, AttachmentForwarded, MessageAttachment};
+use super::contact::ContactInfo;
+use super::label::MessageLabel;
+
+/// A raw message record without assembled sub-types.
+#[derive(Debug, Clone)]
+pub struct MessageRow {
+ /// Database ID of the message.
+ pub db_id: uuid::Uuid,
+ /// Provider message ID.
+ pub provider_id: Option<String>,
+ /// Database ID of the thread this message belongs to.
+ pub thread_db_id: uuid::Uuid,
+ /// Provider thread ID.
+ pub provider_thread_id: Option<String>,
+ /// Database ID of the message this is replying to.
+ pub replying_to_id: Option<uuid::Uuid>,
+ /// Globally unique Message-ID header value.
+ pub global_id: Option<String>,
+ /// Link ID this message belongs to.
+ pub link_id: uuid::Uuid,
+ /// Message subject.
+ pub subject: Option<String>,
+ /// Message snippet.
+ pub snippet: Option<String>,
+ /// Provider history ID.
+ pub provider_history_id: Option<String>,
+ /// Internal date timestamp from the provider.
+ pub internal_date_ts: Option<DateTime<Utc>>,
+ /// When the message was sent.
+ pub sent_at: Option<DateTime<Utc>>,
+ /// Estimated size of the message.
+ pub size_estimate: Option<i64>,
+ /// Whether the message has been read.
+ pub is_read: bool,
+ /// Whether the message is starred.
+ pub is_starred: bool,
+ /// Whether the message was sent by the user.
+ pub is_sent: bool,
+ /// Whether the message is a draft.
+ pub is_draft: bool,
+ /// Whether the message has attachments.
+ pub has_attachments: bool,
+ /// Plain text body.
+ pub body_text: Option<String>,
+ /// Sanitized HTML body.
+ pub body_html_sanitized: Option<String>,
+ /// Macro-format body.
+ pub body_macro: Option<String>,
+ /// Raw headers as JSON.
+ pub headers_json: Option<serde_json::Value>,
+ /// When the message was created.
+ pub created_at: DateTime<Utc>,
+ /// When the message was last updated.
+ pub updated_at: DateTime<Utc>,
+}
+
+/// A fully assembled message with all sub-types resolved.
+#[derive(Debug, Clone)]
+pub struct Message {
+ /// Database ID of the message.
+ pub db_id: uuid::Uuid,
+ /// Provider message ID.
+ pub provider_id: Option<String>,
+ /// Database ID of the thread this message belongs to.
+ pub thread_db_id: uuid::Uuid,
+ /// Provider thread ID.
+ pub provider_thread_id: Option<String>,
+ /// Database ID of the message this is replying to.
+ pub replying_to_id: Option<uuid::Uuid>,
+ /// Globally unique Message-ID header value.
+ pub global_id: Option<String>,
+ /// Link ID this message belongs to.
+ pub link_id: uuid::Uuid,
+ /// Message subject.
+ pub subject: Option<String>,
+ /// Message snippet.
+ pub snippet: Option<String>,
+ /// Provider history ID.
+ pub provider_history_id: Option<String>,
+ /// Internal date timestamp from the provider.
+ pub internal_date_ts: Option<DateTime<Utc>>,
+ /// When the message was sent.
+ pub sent_at: Option<DateTime<Utc>>,
+ /// Estimated size of the message.
+ pub size_estimate: Option<i64>,
+ /// Whether the message has been read.
+ pub is_read: bool,
+ /// Whether the message is starred.
+ pub is_starred: bool,
+ /// Whether the message was sent by the user.
+ pub is_sent: bool,
+ /// Whether the message is a draft.
+ pub is_draft: bool,
+ /// Whether the message has attachments.
+ pub has_attachments: bool,
+ /// Scheduled send time for draft messages.
+ pub scheduled_send_time: Option<DateTime<Utc>>,
+ /// Sender contact info.
+ pub from: Option<ContactInfo>,
+ /// To recipients.
+ pub to: Vec<ContactInfo>,
+ /// Cc recipients.
+ pub cc: Vec<ContactInfo>,
+ /// Bcc recipients.
+ pub bcc: Vec<ContactInfo>,
+ /// Labels on this message.
+ pub labels: Vec<MessageLabel>,
+ /// Plain text body.
+ pub body_text: Option<String>,
+ /// Sanitized HTML body.
+ pub body_html_sanitized: Option<String>,
+ /// Macro-format body.
+ pub body_macro: Option<String>,
+ /// Body with reply/forwarded thread content stripped.
+ pub body_replyless: Option<String>,
+ /// Provider attachments.
+ pub attachments: Vec<MessageAttachment>,
+ /// Draft (uploaded) attachments.
+ pub attachments_draft: Vec<AttachmentDraft>,
+ /// Forwarded attachments.
+ pub attachments_forwarded: Vec<AttachmentForwarded>,
+ /// Raw headers as JSON.
+ pub headers_json: Option<serde_json::Value>,
+ /// When the message was created.
+ pub created_at: DateTime<Utc>,
+ /// When the message was last updated.
+ pub updated_at: DateTime<Utc>,
+}
diff --git a/rust/cloud-storage/email/src/domain/models/mod.rs b/rust/cloud-storage/email/src/domain/models/mod.rs
new file mode 100644
index 0000000000..adaa368471
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/mod.rs
@@ -0,0 +1,23 @@
+pub mod attachment;
+pub mod contact;
+pub mod error;
+pub mod label;
+pub mod link;
+pub mod message;
+pub mod preview;
+pub mod thread;
+
+#[cfg(test)]
+mod tests;
+
+pub use attachment::{Attachment, AttachmentDraft, AttachmentForwarded, MessageAttachment};
+pub use contact::{Contact, ContactInfo, RecipientType};
+pub use error::EmailErr;
+pub use label::{Label, LabelListVisibility, LabelType, MessageLabel, MessageListVisibility};
+pub use link::{Link, UserProvider};
+pub use message::{Message, MessageRow};
+pub use preview::{
+ EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery,
+ PreviewView, PreviewViewStandardLabel,
+};
+pub use thread::{Thread, ThreadRow};
diff --git a/rust/cloud-storage/email/src/domain/models.rs b/rust/cloud-storage/email/src/domain/models/preview.rs
similarity index 60%
rename from rust/cloud-storage/email/src/domain/models.rs
rename to rust/cloud-storage/email/src/domain/models/preview.rs
index 91881e0b35..20473ccd2b 100644
--- a/rust/cloud-storage/email/src/domain/models.rs
+++ b/rust/cloud-storage/email/src/domain/models/preview.rs
@@ -1,16 +1,16 @@
use chrono::{DateTime, Utc};
-use frecency::domain::models::{AggregateFrecency, FrecencyQueryErr};
+use frecency::domain::models::AggregateFrecency;
use item_filters::ast::{LiteralTree, email::EmailLiteral};
-use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
+use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{Identify, Query, SimpleSortMethod, SortOn};
use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::str::FromStr;
use strum::{Display, EnumString};
-use thiserror::Error;
use uuid::Uuid;
-#[cfg(test)]
-mod tests;
+use super::attachment::Attachment;
+use super::contact::Contact;
+use super::label::Label;
#[derive(Debug)]
pub struct PreviewCursorQuery {
@@ -128,49 +128,6 @@ impl SortOn<SimpleSortMethod> for EnrichedEmailThreadPreview {
}
}
-#[derive(Debug, Clone)]
-#[non_exhaustive]
-pub struct Attachment {
- pub id: Uuid,
- pub(crate) thread_id: Uuid,
- pub message_id: Uuid,
- // a different value is returned by the gmail API for this each time you fetch a message -
- // don't make the mistake of using it to uniquely identify an attachment
- pub provider_attachment_id: Option<String>,
- pub filename: Option<String>,
- pub mime_type: Option<String>,
- pub size_bytes: Option<i64>,
- pub content_id: Option<String>,
- pub created_at: DateTime<Utc>,
-}
-
-impl Identify for Attachment {
- type Id = Uuid;
-
- fn id(&self) -> Self::Id {
- self.id
- }
-}
-
-#[derive(Debug, Clone)]
-#[non_exhaustive]
-pub struct Contact {
- pub id: Uuid,
- pub(crate) thread_id: Uuid,
- pub link_id: Uuid,
- pub name: Option<String>,
- pub email_address: Option<String>,
- pub sfs_photo_url: Option<String>,
-}
-
-#[derive(Debug, Error)]
-pub enum EmailErr {
- #[error(transparent)]
- RepoErr(#[from] anyhow::Error),
- #[error(transparent)]
- Frecency(#[from] FrecencyQueryErr),
-}
-
pub struct GetEmailsRequest {
pub view: PreviewView,
pub link_id: Uuid,
@@ -178,61 +135,3 @@ pub struct GetEmailsRequest {
pub limit: Option<u32>,
pub query: Query<Uuid, SimpleSortMethod, LiteralTree<EmailLiteral>>,
}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum MessageListVisibility {
- Show,
- Hide,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum LabelListVisibility {
- LabelShow,
- LabelShowIfUnread,
- LabelHide,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum LabelType {
- System,
- User,
-}
-
-#[derive(Debug, Clone)]
-pub struct Label {
- pub id: Uuid,
- pub(crate) thread_id: Uuid,
- pub link_id: Uuid,
- pub provider_label_id: String,
- pub name: String,
- pub created_at: DateTime<Utc>,
- pub message_list_visibility: MessageListVisibility,
- pub label_list_visibility: LabelListVisibility,
- pub type_: LabelType,
-}
-
-/// The provider of this email
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum UserProvider {
- Gmail,
-}
-
-impl UserProvider {
- pub fn as_str(&self) -> &'static str {
- match self {
- UserProvider::Gmail => "GMAIL",
- }
- }
-}
-
-#[derive(Clone)]
-pub struct Link {
- pub id: Uuid,
- pub macro_id: MacroUserIdStr<'static>,
- pub fusionauth_user_id: String,
- pub email_address: EmailStr<'static>,
- pub provider: UserProvider,
- pub is_sync_active: bool,
- pub created_at: DateTime<Utc>,
- pub updated_at: DateTime<Utc>,
-}
diff --git a/rust/cloud-storage/email/src/domain/models/tests.rs b/rust/cloud-storage/email/src/domain/models/tests.rs
index 3eb4b2c509..da2d749352 100644
--- a/rust/cloud-storage/email/src/domain/models/tests.rs
+++ b/rust/cloud-storage/email/src/domain/models/tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use std::str::FromStr;
#[test]
fn test_preview_view_display() {
diff --git a/rust/cloud-storage/email/src/domain/models/thread.rs b/rust/cloud-storage/email/src/domain/models/thread.rs
new file mode 100644
index 0000000000..ea158a3418
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/thread.rs
@@ -0,0 +1,37 @@
+use chrono::{DateTime, Utc};
+
+use super::message::Message;
+
+/// A thread record without messages.
+#[derive(Debug, Clone)]
+pub struct ThreadRow {
+ /// Database ID of the thread.
+ pub db_id: uuid::Uuid,
+ /// Provider thread ID.
+ pub provider_id: Option<String>,
+ /// Link ID this thread belongs to.
+ pub link_id: uuid::Uuid,
+ /// Whether the thread is visible in the inbox.
+ pub inbox_visible: bool,
+ /// Whether the thread has been read.
+ pub is_read: bool,
+ /// Timestamp of the latest inbound message.
+ pub latest_inbound_message_ts: Option<DateTime<Utc>>,
+ /// Timestamp of the latest outbound message.
+ pub latest_outbound_message_ts: Option<DateTime<Utc>>,
+ /// Timestamp of the latest non-spam message.
+ pub latest_non_spam_message_ts: Option<DateTime<Utc>>,
+ /// When the thread was created.
+ pub created_at: DateTime<Utc>,
+ /// When the thread was last updated.
+ pub updated_at: DateTime<Utc>,
+}
+
+/// A fully assembled email thread with paginated messages.
+#[derive(Debug, Clone)]
+pub struct Thread {
+ /// The thread metadata.
+ pub row: ThreadRow,
+ /// Paginated messages in the thread.
+ pub messages: Vec<Message>,
+}
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index 492904ed7f..02ffe20c34 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -1,11 +1,19 @@
use crate::domain::models::{
- Attachment, Contact, EmailErr, EmailThreadPreview, EnrichedEmailThreadPreview,
- GetEmailsRequest, Label, Link, PreviewCursorQuery, UserProvider,
+ Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailErr,
+ EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest, Label, Link,
+ MessageAttachment, MessageLabel, MessageRow, PreviewCursorQuery, RecipientType, Thread,
+ ThreadRow, UserProvider,
};
+use chrono::{DateTime, Utc};
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{PaginatedCursor, SimpleSortMethod};
+use std::collections::HashMap;
use uuid::Uuid;
+/// Keyed map of message recipients grouped by message ID.
+pub type RecipientsByMessageId = HashMap<Uuid, Vec<(ContactInfo, RecipientType)>>;
+
pub trait EmailRepo: Send + Sync + 'static {
type Err: Send;
fn previews_for_view_cursor(
@@ -35,6 +43,63 @@ pub trait EmailRepo: Send + Sync + 'static {
macro_id: MacroUserIdStr<'_>,
provider: UserProvider,
) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;
+
+ /// Fetch a thread by its database ID (without messages).
+ fn thread_by_id(
+ &self,
+ thread_id: Uuid,
+ ) -> impl Future<Output = Result<Option<ThreadRow>, Self::Err>> + Send;
+
+ /// Fetch paginated messages for a thread, ordered by internal_date_ts descending.
+ fn messages_by_thread_id_paginated(
+ &self,
+ thread_id: Uuid,
+ offset: i64,
+ limit: i64,
+ ) -> impl Future<Output = Result<Vec<MessageRow>, Self::Err>> + Send;
+
+ /// Fetch sender contact info for a set of message IDs, keyed by message ID.
+ fn senders_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> impl Future<Output = Result<HashMap<Uuid, ContactInfo>, Self::Err>> + Send;
+
+ /// Fetch recipient contact info for a set of message IDs, keyed by message ID.
+ fn recipients_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> impl Future<Output = Result<RecipientsByMessageId, Self::Err>> + Send;
+
+ /// Fetch labels for a set of message IDs, keyed by message ID.
+ fn labels_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> impl Future<Output = Result<HashMap<Uuid, Vec<MessageLabel>>, Self::Err>> + Send;
+
+ /// Fetch provider attachments for a set of message IDs, keyed by message ID.
+ fn attachments_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> impl Future<Output = Result<HashMap<Uuid, Vec<MessageAttachment>>, Self::Err>> + Send;
+
+ /// Fetch draft attachments for a set of message IDs, keyed by message ID.
+ fn draft_attachments_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> impl Future<Output = Result<HashMap<Uuid, Vec<AttachmentDraft>>, Self::Err>> + Send;
+
+ /// Fetch forwarded attachments for a set of message IDs, keyed by message ID.
+ fn forwarded_attachments_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> impl Future<Output = Result<HashMap<Uuid, Vec<AttachmentForwarded>>, Self::Err>> + Send;
+
+ /// Fetch scheduled send times for a set of message IDs, keyed by message ID.
+ /// Only returns entries for unsent scheduled messages.
+ fn scheduled_send_times_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> impl Future<Output = Result<HashMap<Uuid, DateTime<Utc>>, Self::Err>> + Send;
}
pub trait EmailService: Send + Sync + 'static {
@@ -53,4 +118,12 @@ pub trait EmailService: Send + Sync + 'static {
auth_id: &str,
macro_id: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;
+
+ /// Fetch a thread with paginated messages, verifying access via the provided receipt.
+ fn get_thread_with_messages(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ offset: i64,
+ limit: i64,
+ ) -> impl Future<Output = Result<Option<Thread>, EmailErr>> + Send;
}
diff --git a/rust/cloud-storage/email/src/domain/service.rs b/rust/cloud-storage/email/src/domain/service.rs
index 6eb6547458..0060536765 100644
--- a/rust/cloud-storage/email/src/domain/service.rs
+++ b/rust/cloud-storage/email/src/domain/service.rs
@@ -1,9 +1,14 @@
use crate::domain::{
+ assembler::{message_from_row, split_recipients, thread_from_row},
models::{
- EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery, UserProvider,
+ EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest, Message, PreviewCursorQuery,
+ Thread, UserProvider,
},
ports::{EmailRepo, EmailService},
};
+use entity_access::domain::models::{
+ AccessLevel, EntityAccessReceipt, EntityPermission, ViewAccessLevel,
+};
use frecency::domain::{
models::{AggregateId, FrecencyByIdsRequest, FrecencyData},
ports::FrecencyQueryService,
@@ -141,4 +146,156 @@ where
.await
.map_err(anyhow::Error::from)?)
}
+
+ #[tracing::instrument(err, skip(self, receipt))]
+ async fn get_thread_with_messages(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ offset: i64,
+ limit: i64,
+ ) -> Result<Option<Thread>, EmailErr> {
+ let thread_id = Uuid::parse_str(&receipt.entity().entity_id)
+ .map_err(|e| EmailErr::RepoErr(anyhow::anyhow!("invalid thread id: {}", e)))?;
+
+ let thread_row = self
+ .email_repo
+ .thread_by_id(thread_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ let Some(thread_row) = thread_row else {
+ return Ok(None);
+ };
+
+ let message_rows = self
+ .email_repo
+ .messages_by_thread_id_paginated(thread_id, offset, limit)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ if message_rows.is_empty() {
+ return Ok(Some(thread_from_row(thread_row, vec![])));
+ }
+
+ let message_ids: Vec<Uuid> = message_rows.iter().map(|m| m.db_id).collect();
+ let message_ids_with_attachments: Vec<Uuid> = message_rows
+ .iter()
+ .filter(|m| m.has_attachments)
+ .map(|m| m.db_id)
+ .collect();
+ let draft_message_ids: Vec<Uuid> = message_rows
+ .iter()
+ .filter(|m| m.provider_id.is_none())
+ .map(|m| m.db_id)
+ .collect();
+
+ let (
+ senders_result,
+ recipients_result,
+ scheduled_result,
+ labels_result,
+ attachments_result,
+ draft_attachments_result,
+ forwarded_attachments_result,
+ ) = tokio::try_join!(
+ async {
+ self.email_repo
+ .senders_by_message_ids(&message_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ async {
+ self.email_repo
+ .recipients_by_message_ids(&message_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ async {
+ self.email_repo
+ .scheduled_send_times_by_message_ids(&message_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ async {
+ self.email_repo
+ .labels_by_message_ids(&message_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ async {
+ self.email_repo
+ .attachments_by_message_ids(&message_ids_with_attachments)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ async {
+ self.email_repo
+ .draft_attachments_by_message_ids(&draft_message_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ async {
+ self.email_repo
+ .forwarded_attachments_by_message_ids(&draft_message_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ )?;
+
+ let mut senders = senders_result;
+ let mut recipients = recipients_result;
+ let mut scheduled = scheduled_result;
+ let mut labels = labels_result;
+ let mut attachments = attachments_result;
+ let mut draft_attachments = draft_attachments_result;
+ let mut forwarded_attachments = forwarded_attachments_result;
+
+ let is_owner = matches!(
+ receipt.entity_permission(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner
+ }
+ );
+
+ let messages: Vec<Message> = message_rows
+ .into_iter()
+ // don't include drafts for non-owners
+ .filter(|row| is_owner || !row.is_draft)
+ .map(|row| {
+ let sender = senders.remove(&row.db_id);
+ let recipient_list = recipients.remove(&row.db_id).unwrap_or_default();
+ let scheduled_send_time = scheduled.remove(&row.db_id);
+ let message_labels = labels.remove(&row.db_id).unwrap_or_default();
+ let message_attachments = attachments.remove(&row.db_id).unwrap_or_default();
+ let message_draft_attachments =
+ draft_attachments.remove(&row.db_id).unwrap_or_default();
+ let message_forwarded_attachments =
+ forwarded_attachments.remove(&row.db_id).unwrap_or_default();
+
+ let (to, cc, bcc) = split_recipients(recipient_list);
+
+ let body_replyless = email_utils::body_replyless::compute_body_replyless(
+ row.subject.as_deref(),
+ row.body_html_sanitized.as_deref(),
+ row.body_text.as_deref(),
+ );
+
+ message_from_row(
+ row,
+ sender,
+ to,
+ cc,
+ bcc,
+ message_labels,
+ message_attachments,
+ message_draft_attachments,
+ message_forwarded_attachments,
+ scheduled_send_time,
+ body_replyless,
+ )
+ })
+ .collect();
+
+ Ok(Some(thread_from_row(thread_row, messages)))
+ }
}
diff --git a/rust/cloud-storage/email/src/inbound/axum.rs b/rust/cloud-storage/email/src/inbound/axum.rs
index 5037b9fe97..4be9af914d 100644
--- a/rust/cloud-storage/email/src/inbound/axum.rs
+++ b/rust/cloud-storage/email/src/inbound/axum.rs
@@ -1,7 +1,9 @@
mod api_types;
mod axum_impls;
-mod router;
+mod get_thread_router;
+mod previews_router;
pub use api_types::*;
pub use axum_impls::*;
-pub use router::*;
+pub use get_thread_router::*;
+pub use previews_router::*;
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/label.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/label.rs
new file mode 100644
index 0000000000..90c9e50be9
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/label.rs
@@ -0,0 +1,58 @@
+use doppleganger::Doppleganger;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+use crate::domain::models::{LabelListVisibility, LabelType, MessageListVisibility};
+
+#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[dg(backward = MessageListVisibility)]
+pub enum ApiMessageListVisibility {
+ Show,
+ Hide,
+}
+
+#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[dg(backward = LabelListVisibility)]
+pub enum ApiLabelListVisibility {
+ LabelShow,
+ LabelShowIfUnread,
+ LabelHide,
+}
+
+#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+#[dg(backward = LabelType)]
+pub enum ApiLabelType {
+ System,
+ User,
+}
+
+impl From<MessageListVisibility> for ApiMessageListVisibility {
+ fn from(v: MessageListVisibility) -> Self {
+ match v {
+ MessageListVisibility::Show => ApiMessageListVisibility::Show,
+ MessageListVisibility::Hide => ApiMessageListVisibility::Hide,
+ }
+ }
+}
+
+impl From<LabelListVisibility> for ApiLabelListVisibility {
+ fn from(v: LabelListVisibility) -> Self {
+ match v {
+ LabelListVisibility::LabelShow => ApiLabelListVisibility::LabelShow,
+ LabelListVisibility::LabelShowIfUnread => ApiLabelListVisibility::LabelShowIfUnread,
+ LabelListVisibility::LabelHide => ApiLabelListVisibility::LabelHide,
+ }
+ }
+}
+
+impl From<LabelType> for ApiLabelType {
+ fn from(v: LabelType) -> Self {
+ match v {
+ LabelType::System => ApiLabelType::System,
+ LabelType::User => ApiLabelType::User,
+ }
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/message.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/message.rs
new file mode 100644
index 0000000000..97387ac3bd
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/message.rs
@@ -0,0 +1,258 @@
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::domain::models::{
+ AttachmentDraft, AttachmentForwarded, ContactInfo, Message, MessageAttachment, MessageLabel,
+ RecipientType,
+};
+
+use super::label::{ApiLabelListVisibility, ApiLabelType, ApiMessageListVisibility};
+
+/// API representation of a contact (sender or recipient).
+#[derive(Debug, Serialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct ApiContactInfo {
+ pub email: String,
+ pub name: Option<String>,
+ pub photo_url: Option<String>,
+}
+
+impl From<ContactInfo> for ApiContactInfo {
+ fn from(c: ContactInfo) -> Self {
+ ApiContactInfo {
+ email: c.email,
+ name: c.name,
+ photo_url: c.photo_url,
+ }
+ }
+}
+
+/// Recipient type for a message.
+#[derive(Debug, Serialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub enum ApiRecipientType {
+ To,
+ Cc,
+ Bcc,
+}
+
+impl From<RecipientType> for ApiRecipientType {
+ fn from(r: RecipientType) -> Self {
+ match r {
+ RecipientType::To => ApiRecipientType::To,
+ RecipientType::Cc => ApiRecipientType::Cc,
+ RecipientType::Bcc => ApiRecipientType::Bcc,
+ }
+ }
+}
+
+/// API representation of a label on a message.
+#[derive(Debug, Serialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct ApiMessageLabel {
+ pub id: Option<Uuid>,
+ pub link_id: Uuid,
+ pub provider_label_id: String,
+ pub name: Option<String>,
+ pub created_at: DateTime<Utc>,
+ pub message_list_visibility: Option<ApiMessageListVisibility>,
+ pub label_list_visibility: Option<ApiLabelListVisibility>,
+ pub type_: Option<ApiLabelType>,
+}
+
+impl From<MessageLabel> for ApiMessageLabel {
+ fn from(l: MessageLabel) -> Self {
+ ApiMessageLabel {
+ id: l.id,
+ link_id: l.link_id,
+ provider_label_id: l.provider_label_id,
+ name: l.name,
+ created_at: l.created_at,
+ message_list_visibility: l
+ .message_list_visibility
+ .map(ApiMessageListVisibility::from),
+ label_list_visibility: l.label_list_visibility.map(ApiLabelListVisibility::from),
+ type_: l.type_.map(ApiLabelType::from),
+ }
+ }
+}
+
+/// API representation of a provider attachment on a message.
+#[derive(Debug, Serialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct ApiMessageAttachment {
+ pub db_id: Uuid,
+ pub provider_id: Option<String>,
+ pub filename: Option<String>,
+ pub mime_type: Option<String>,
+ pub size_bytes: Option<i64>,
+ pub sfs_id: Option<Uuid>,
+ pub content_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub data_url: Option<String>,
+}
+
+impl From<MessageAttachment> for ApiMessageAttachment {
+ fn from(a: MessageAttachment) -> Self {
+ ApiMessageAttachment {
+ db_id: a.db_id,
+ provider_id: a.provider_id,
+ filename: a.filename,
+ mime_type: a.mime_type,
+ size_bytes: a.size_bytes,
+ sfs_id: a.sfs_id,
+ content_id: a.content_id,
+ data_url: None,
+ }
+ }
+}
+
+/// API representation of a draft attachment on a message.
+#[derive(Debug, Serialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct ApiAttachmentDraft {
+ pub id: Uuid,
+ pub draft_id: Uuid,
+ pub file_name: String,
+ pub content_type: String,
+ pub sha: String,
+ pub size: i32,
+ pub s3_key: String,
+}
+
+impl From<AttachmentDraft> for ApiAttachmentDraft {
+ fn from(a: AttachmentDraft) -> Self {
+ ApiAttachmentDraft {
+ id: a.id,
+ draft_id: a.draft_id,
+ file_name: a.file_name,
+ content_type: a.content_type,
+ sha: a.sha,
+ size: a.size,
+ s3_key: a.s3_key,
+ }
+ }
+}
+
+/// API representation of a forwarded attachment on a message.
+#[derive(Debug, Serialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct ApiAttachmentForwarded {
+ pub attachment_id: Uuid,
+ pub draft_id: Uuid,
+ pub provider_attachment_id: Option<String>,
+ pub message_provider_id: String,
+ pub filename: Option<String>,
+ pub mime_type: Option<String>,
+ pub size_bytes: Option<i64>,
+}
+
+impl From<AttachmentForwarded> for ApiAttachmentForwarded {
+ fn from(a: AttachmentForwarded) -> Self {
+ ApiAttachmentForwarded {
+ attachment_id: a.attachment_id,
+ draft_id: a.draft_id,
+ provider_attachment_id: a.provider_attachment_id,
+ message_provider_id: a.message_provider_id,
+ filename: a.filename,
+ mime_type: a.mime_type,
+ size_bytes: a.size_bytes,
+ }
+ }
+}
+
+/// API representation of a fully assembled email message.
+#[derive(Debug, Serialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct ApiMessage {
+ pub db_id: Uuid,
+ pub provider_id: Option<String>,
+ pub thread_db_id: Uuid,
+ pub provider_thread_id: Option<String>,
+ pub replying_to_id: Option<Uuid>,
+ pub global_id: Option<String>,
+ pub link_id: Uuid,
+ pub subject: Option<String>,
+ pub snippet: Option<String>,
+ pub provider_history_id: Option<String>,
+ pub sent_at: Option<DateTime<Utc>>,
+ pub internal_date_ts: Option<DateTime<Utc>>,
+ pub size_estimate: Option<i64>,
+ pub is_read: bool,
+ pub is_starred: bool,
+ pub is_sent: bool,
+ pub is_draft: bool,
+ pub has_attachments: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub scheduled_send_time: Option<DateTime<Utc>>,
+ pub from: Option<ApiContactInfo>,
+ pub to: Vec<ApiContactInfo>,
+ pub cc: Vec<ApiContactInfo>,
+ pub bcc: Vec<ApiContactInfo>,
+ pub labels: Vec<ApiMessageLabel>,
+ pub body_text: Option<String>,
+ pub body_html_sanitized: Option<String>,
+ pub body_macro: Option<String>,
+ pub body_replyless: Option<String>,
+ pub attachments: Vec<ApiMessageAttachment>,
+ pub attachments_draft: Vec<ApiAttachmentDraft>,
+ pub attachments_forwarded: Vec<ApiAttachmentForwarded>,
+ pub headers_json: Option<serde_json::Value>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+impl From<Message> for ApiMessage {
+ fn from(m: Message) -> Self {
+ ApiMessage {
+ db_id: m.db_id,
+ provider_id: m.provider_id,
+ thread_db_id: m.thread_db_id,
+ provider_thread_id: m.provider_thread_id,
+ replying_to_id: m.replying_to_id,
+ global_id: m.global_id,
+ link_id: m.link_id,
+ subject: m.subject,
+ snippet: m.snippet,
+ provider_history_id: m.provider_history_id,
+ sent_at: m.sent_at,
+ internal_date_ts: m.internal_date_ts,
+ size_estimate: m.size_estimate,
+ is_read: m.is_read,
+ is_starred: m.is_starred,
+ is_sent: m.is_sent,
+ is_draft: m.is_draft,
+ has_attachments: m.has_attachments,
+ scheduled_send_time: m.scheduled_send_time,
+ from: m.from.map(ApiContactInfo::from),
+ to: m.to.into_iter().map(ApiContactInfo::from).collect(),
+ cc: m.cc.into_iter().map(ApiContactInfo::from).collect(),
+ bcc: m.bcc.into_iter().map(ApiContactInfo::from).collect(),
+ labels: m.labels.into_iter().map(ApiMessageLabel::from).collect(),
+ body_text: m.body_text,
+ body_html_sanitized: m.body_html_sanitized,
+ body_macro: m.body_macro,
+ body_replyless: m.body_replyless,
+ attachments: m
+ .attachments
+ .into_iter()
+ .map(ApiMessageAttachment::from)
+ .collect(),
+ attachments_draft: m
+ .attachments_draft
+ .into_iter()
+ .map(ApiAttachmentDraft::from)
+ .collect(),
+ attachments_forwarded: m
+ .attachments_forwarded
+ .into_iter()
+ .map(ApiAttachmentForwarded::from)
+ .collect(),
+ headers_json: m.headers_json,
+ created_at: m.created_at,
+ updated_at: m.updated_at,
+ }
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rs
new file mode 100644
index 0000000000..dfacafbebd
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rs
@@ -0,0 +1,16 @@
+mod label;
+mod message;
+mod preview;
+mod sort;
+mod thread;
+
+pub use label::{ApiLabelListVisibility, ApiLabelType, ApiMessageListVisibility};
+pub use message::{
+ ApiAttachmentDraft, ApiAttachmentForwarded, ApiContactInfo, ApiMessage, ApiMessageAttachment,
+ ApiMessageLabel, ApiRecipientType,
+};
+pub use preview::{
+ ApiAttachment, ApiContact, ApiLabel, ApiPaginatedThreadCursor, ApiThreadPreviewCursorInner,
+};
+pub use sort::ApiSortMethod;
+pub use thread::{ApiThread, GetThreadParams, GetThreadResponse};
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/preview.rs
similarity index 69%
rename from rust/cloud-storage/email/src/inbound/axum/api_types.rs
rename to rust/cloud-storage/email/src/inbound/axum/api_types/preview.rs
index b35a563a99..a56f5a562b 100644
--- a/rust/cloud-storage/email/src/inbound/axum/api_types.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/preview.rs
@@ -2,40 +2,16 @@ use chrono::{DateTime, Utc};
use doppleganger::{Doppleganger, Mirror};
use frecency::domain::models::AggregateFrecency;
use macro_user_id::user_id::MacroUserIdStr;
-use models_pagination::{PaginatedOpaqueCursor, SimpleSortMethod};
+use models_pagination::PaginatedOpaqueCursor;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
use crate::domain::models::{
Attachment, Contact, EmailThreadPreview, EnrichedEmailThreadPreview, Label,
- LabelListVisibility, LabelType, MessageListVisibility,
};
-/// common types of sorts based on timestamps
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)]
-#[serde(rename_all = "snake_case")]
-pub enum ApiSortMethod {
- /// we are sorting by the viewed_at time
- ViewedAt,
- /// we are sorting by the updated_at time
- UpdatedAt,
- /// we are sorting by the created_at time
- CreatedAt,
- /// we are sorting by the viewed/updated time
- ViewedUpdated,
-}
-
-impl ApiSortMethod {
- pub fn into_simple_sort(self) -> SimpleSortMethod {
- match self {
- ApiSortMethod::ViewedAt => SimpleSortMethod::ViewedAt,
- ApiSortMethod::UpdatedAt => SimpleSortMethod::UpdatedAt,
- ApiSortMethod::CreatedAt => SimpleSortMethod::CreatedAt,
- ApiSortMethod::ViewedUpdated => SimpleSortMethod::ViewedUpdated,
- }
- }
-}
+use super::label::{ApiLabelListVisibility, ApiLabelType, ApiMessageListVisibility};
#[derive(Debug, ToSchema, Serialize, Deserialize, Doppleganger)]
#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
@@ -127,31 +103,6 @@ pub struct ApiLabel {
type_: ApiLabelType,
}
-#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]
-#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
-#[dg(backward = MessageListVisibility)]
-pub enum ApiMessageListVisibility {
- Show,
- Hide,
-}
-
-#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]
-#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
-#[dg(backward = LabelListVisibility)]
-pub enum ApiLabelListVisibility {
- LabelShow,
- LabelShowIfUnread,
- LabelHide,
-}
-
-#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]
-#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
-#[dg(backward = LabelType)]
-pub enum ApiLabelType {
- System,
- User,
-}
-
#[derive(Debug, ToSchema, Serialize, Deserialize)]
#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
pub struct ApiPaginatedThreadCursor {
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/sort.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/sort.rs
new file mode 100644
index 0000000000..505d744adf
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/sort.rs
@@ -0,0 +1,28 @@
+use models_pagination::SimpleSortMethod;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+/// common types of sorts based on timestamps
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ApiSortMethod {
+ /// we are sorting by the viewed_at time
+ ViewedAt,
+ /// we are sorting by the updated_at time
+ UpdatedAt,
+ /// we are sorting by the created_at time
+ CreatedAt,
+ /// we are sorting by the viewed/updated time
+ ViewedUpdated,
+}
+
+impl ApiSortMethod {
+ pub fn into_simple_sort(self) -> SimpleSortMethod {
+ match self {
+ ApiSortMethod::ViewedAt => SimpleSortMethod::ViewedAt,
+ ApiSortMethod::UpdatedAt => SimpleSortMethod::UpdatedAt,
+ ApiSortMethod::CreatedAt => SimpleSortMethod::CreatedAt,
+ ApiSortMethod::ViewedUpdated => SimpleSortMethod::ViewedUpdated,
+ }
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/thread.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/thread.rs
new file mode 100644
index 0000000000..dfa64181c7
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/thread.rs
@@ -0,0 +1,63 @@
+use chrono::{DateTime, Utc};
+use entity_access::domain::models::AccessLevel;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::domain::models::Thread;
+
+use super::message::ApiMessage;
+
+/// Query parameters for the get-thread endpoint.
+#[derive(Debug, Deserialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct GetThreadParams {
+ /// Offset for message pagination. Default is 0.
+ pub offset: Option<i64>,
+ /// Maximum number of messages to return. Default is 5, max is 100.
+ pub limit: Option<i64>,
+}
+
+/// Response body for the get-thread endpoint.
+#[derive(Debug, Serialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct GetThreadResponse {
+ pub thread: ApiThread,
+}
+
+/// API representation of a fully assembled email thread.
+#[derive(Debug, Serialize, ToSchema)]
+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]
+pub struct ApiThread {
+ pub db_id: Uuid,
+ pub provider_id: Option<String>,
+ pub link_id: Uuid,
+ pub inbox_visible: bool,
+ pub is_read: bool,
+ pub access_level: AccessLevel,
+ pub latest_inbound_message_ts: Option<DateTime<Utc>>,
+ pub latest_outbound_message_ts: Option<DateTime<Utc>>,
+ pub latest_non_spam_message_ts: Option<DateTime<Utc>>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ pub messages: Vec<ApiMessage>,
+}
+
+impl ApiThread {
+ pub fn from_thread(t: Thread, access_level: AccessLevel) -> Self {
+ ApiThread {
+ db_id: t.row.db_id,
+ provider_id: t.row.provider_id,
+ link_id: t.row.link_id,
+ inbox_visible: t.row.inbox_visible,
+ is_read: t.row.is_read,
+ access_level,
+ latest_inbound_message_ts: t.row.latest_inbound_message_ts,
+ latest_outbound_message_ts: t.row.latest_outbound_message_ts,
+ latest_non_spam_message_ts: t.row.latest_non_spam_message_ts,
+ created_at: t.row.created_at,
+ updated_at: t.row.updated_at,
+ messages: t.messages.into_iter().map(ApiMessage::from).collect(),
+ }
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/get_thread_router.rs b/rust/cloud-storage/email/src/inbound/axum/get_thread_router.rs
new file mode 100644
index 0000000000..18f6df69b5
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/get_thread_router.rs
@@ -0,0 +1,152 @@
+use std::sync::Arc;
+
+use axum::{
+ Json, Router,
+ extract::{self, FromRef, State},
+ http::StatusCode,
+ response::IntoResponse,
+ routing::get,
+};
+use entity_access::domain::models::{EntityPermission, ViewAccessLevel};
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::ThreadAccessLevelExtractor;
+use model_error_response::ErrorResponse;
+use thiserror::Error;
+
+use crate::domain::{models::EmailErr, ports::EmailService};
+
+use super::api_types::{ApiThread, GetThreadParams, GetThreadResponse};
+
+/// The default number of messages to return per page.
+const DEFAULT_MESSAGE_LIMIT: i64 = 5;
+/// The maximum number of messages that can be returned per request.
+const MESSAGE_MAX: i64 = 100;
+
+pub struct EmailThreadRouterState<T, Svc> {
+ pub service: Arc<T>,
+ pub access_service: Arc<Svc>,
+}
+
+impl<T, Svc> Clone for EmailThreadRouterState<T, Svc> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ access_service: self.access_service.clone(),
+ }
+ }
+}
+
+impl<T, Svc> FromRef<EmailThreadRouterState<T, Svc>> for Arc<Svc> {
+ fn from_ref(state: &EmailThreadRouterState<T, Svc>) -> Self {
+ state.access_service.clone()
+ }
+}
+
+pub fn thread_router<S, T, Svc>(state: EmailThreadRouterState<T, Svc>) -> Router<S>
+where
+ S: Send + Sync + 'static,
+ T: EmailService,
+ Svc: EntityAccessService,
+{
+ Router::new()
+ .route("/:thread_id", get(get_thread_handler::<T, Svc>))
+ .with_state(state)
+}
+
+#[derive(Debug, Error)]
+pub enum GetThreadError {
+ #[error("Thread not found")]
+ NotFound,
+ #[error("Validation error: {0}")]
+ Validation(String),
+ #[error("Internal error")]
+ Internal(#[from] EmailErr),
+}
+
+impl IntoResponse for GetThreadError {
+ fn into_response(self) -> axum::response::Response {
+ if matches!(self, GetThreadError::Internal(_)) {
+ tracing::error!(error=?self, "get thread error");
+ }
+
+ let status = match &self {
+ GetThreadError::NotFound => StatusCode::NOT_FOUND,
+ GetThreadError::Validation(_) => StatusCode::BAD_REQUEST,
+ GetThreadError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ let message = self.to_string();
+ (status, Json(ErrorResponse { message: &message })).into_response()
+ }
+}
+
+/// Get a thread with paginated messages.
+#[utoipa::path(
+ get,
+ tag = "Threads",
+ path = "/email/threads/{thread_id}",
+ operation_id = "get_thread",
+ params(
+ ("thread_id" = String, Path, description = "Thread ID"),
+ ("offset" = Option<i64>, Query, description = "Offset for message pagination. Default is 0."),
+ ("limit" = Option<i64>, Query, description = "Limit for message pagination. Default is 5, max 100."),
+ ),
+ responses(
+ (status = 200, body = GetThreadResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip(state, access))]
+pub async fn get_thread_handler<T: EmailService, Svc: EntityAccessService>(
+ State(state): State<EmailThreadRouterState<T, Svc>>,
+ access: ThreadAccessLevelExtractor<ViewAccessLevel, Svc>,
+ extract::Query(params): extract::Query<GetThreadParams>,
+) -> Result<Json<GetThreadResponse>, GetThreadError> {
+ let (offset, limit) = parse_pagination_params(&params)?;
+
+ let access_level = match access.entity_access_receipt.entity_permission() {
+ EntityPermission::AccessLevel { access_level } => *access_level,
+ _ => unreachable!("thread permissions should always be access level"),
+ };
+
+ let thread = state
+ .service
+ .get_thread_with_messages(access.entity_access_receipt, offset, limit)
+ .await?
+ .ok_or(GetThreadError::NotFound)?;
+
+ Ok(Json(GetThreadResponse {
+ thread: ApiThread::from_thread(thread, access_level),
+ }))
+}
+
+fn parse_pagination_params(params: &GetThreadParams) -> Result<(i64, i64), GetThreadError> {
+ if let Some(offset) = params.offset
+ && offset < 0
+ {
+ return Err(GetThreadError::Validation(
+ "offset must be non-negative".to_string(),
+ ));
+ }
+
+ if let Some(limit) = params.limit {
+ if limit <= 0 {
+ return Err(GetThreadError::Validation(
+ "limit must be positive".to_string(),
+ ));
+ }
+ if limit > MESSAGE_MAX {
+ return Err(GetThreadError::Validation(format!(
+ "limit must not exceed {MESSAGE_MAX}"
+ )));
+ }
+ }
+
+ Ok((
+ params.offset.unwrap_or(0),
+ params.limit.unwrap_or(DEFAULT_MESSAGE_LIMIT),
+ ))
+}
diff --git a/rust/cloud-storage/email/src/inbound/axum/router.rs b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
similarity index 96%
rename from rust/cloud-storage/email/src/inbound/axum/router.rs
rename to rust/cloud-storage/email/src/inbound/axum/previews_router.rs
index 381cf22ba2..1ff1a76371 100644
--- a/rust/cloud-storage/email/src/inbound/axum/router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/previews_router.rs
@@ -41,6 +41,11 @@ where
inner: Arc::new(state),
}
}
+
+ /// Returns an `Arc` to the inner service.
+ pub fn service(&self) -> Arc<T> {
+ Arc::clone(&self.inner)
+ }
}
pub fn router<S, T>(state: EmailPreviewState<T>) -> Router<S>
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
deleted file mode 100644
index 6ddd9e2876..0000000000
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
+++ /dev/null
@@ -1,249 +0,0 @@
-use crate::domain::models::Label;
-use crate::domain::{
- models::{
- Attachment, Contact, EmailThreadPreview, Link, PreviewCursorQuery, PreviewView,
- PreviewViewStandardLabel, UserProvider,
- },
- ports::EmailRepo,
-};
-use db_types::*;
-use doppleganger::{Doppleganger, Mirror};
-use either::Either;
-use macro_user_id::user_id::MacroUserIdStr;
-use sqlx::PgPool;
-use uuid::Uuid;
-
-mod db_types;
-mod dynamic;
-mod queries;
-
-#[cfg(test)]
-mod test;
-
-#[derive(Clone)]
-pub struct EmailPgRepo {
- pool: PgPool,
-}
-
-impl EmailPgRepo {
- pub fn new(pool: PgPool) -> Self {
- EmailPgRepo { pool }
- }
-}
-
-impl EmailRepo for EmailPgRepo {
- type Err = sqlx::Error;
-
- #[tracing::instrument(err, skip(self, query), fields(link_id = %query.link_id, view = %query.view))]
- async fn previews_for_view_cursor(
- &self,
- query: PreviewCursorQuery,
- user_id: MacroUserIdStr<'static>,
- ) -> Result<Vec<EmailThreadPreview>, Self::Err> {
- let PreviewCursorQuery {
- view,
- link_id,
- limit,
- query,
- } = query;
-
- let query = query.split_option();
-
- Ok(match (view, query) {
- (view, Either::Right(dynamic_query)) => {
- dynamic::dynamic_email_thread_cursor(
- &self.pool,
- &link_id,
- limit,
- &view,
- dynamic_query,
- )
- .await?
- }
- (PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox), Either::Left(query)) => {
- queries::new_inbox::new_inbox_preview_cursor(&self.pool, &link_id, limit, &query)
- .await?
- }
- (PreviewView::StandardLabel(PreviewViewStandardLabel::Sent), Either::Left(query)) => {
- queries::sent::sent_preview_cursor(&self.pool, &link_id, limit, &query).await?
- }
- (PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts), Either::Left(query)) => {
- queries::draft::drafts_preview_cursor(&self.pool, &link_id, limit, &query).await?
- }
- (
- PreviewView::StandardLabel(PreviewViewStandardLabel::Starred),
- Either::Left(query),
- ) => {
- queries::starred::starred_preview_cursor(&self.pool, &link_id, limit, &query)
- .await?
- }
- (PreviewView::StandardLabel(PreviewViewStandardLabel::All), Either::Left(query)) => {
- queries::all_mail::all_mail_preview_cursor(&self.pool, &link_id, limit, &query)
- .await?
- }
- (
- PreviewView::StandardLabel(PreviewViewStandardLabel::Important),
- Either::Left(query),
- ) => {
- queries::important::important_preview_cursor(&self.pool, &link_id, limit, &query)
- .await?
- }
- (PreviewView::StandardLabel(PreviewViewStandardLabel::Other), Either::Left(query)) => {
- queries::other_inbox::other_inbox_preview_cursor(
- &self.pool, &link_id, limit, &query,
- )
- .await?
- }
- (PreviewView::UserLabel(label_name), Either::Left(query)) => {
- queries::user_label::user_label_preview_cursor(
- &self.pool,
- &link_id,
- limit,
- &query,
- &label_name,
- )
- .await?
- }
- }
- .into_iter()
- .map(|row| row.with_user_id(user_id.clone()))
- .collect())
- }
-
- #[tracing::instrument(err, skip(self, thread_ids))]
- async fn attachments_by_thread_ids(
- &self,
- thread_ids: &[Uuid],
- ) -> Result<Vec<Attachment>, Self::Err> {
- // Query all attachments for messages in the provided threads
- // Include thread_id in the result set
- Ok(sqlx::query_as!(
- AttachmentDbRow,
- r#"
- SELECT
- a.id,
- a.message_id,
- a.provider_attachment_id,
- a.filename,
- a.mime_type,
- a.size_bytes,
- a.content_id,
- a.created_at,
- m.thread_id
- FROM
- email_attachments a
- JOIN
- email_messages m ON a.message_id = m.id
- WHERE
- m.thread_id = ANY($1)
- ORDER BY
- a.created_at ASC
- "#,
- thread_ids
- )
- .fetch_all(&self.pool)
- .await?
- .into_iter()
- .map(AttachmentDbRow::mirror)
- .collect())
- }
-
- #[tracing::instrument(err, skip(self, thread_ids))]
- async fn contacts_by_thread_ids(&self, thread_ids: &[Uuid]) -> Result<Vec<Contact>, Self::Err> {
- // Define a struct to hold the joined results
- #[derive(Debug, Doppleganger)]
- #[dg(forward = Contact)]
- struct ThreadContactResult {
- thread_id: Uuid,
- id: Uuid,
- link_id: Uuid,
- email_address: Option<String>,
- name: Option<String>,
- sfs_photo_url: Option<String>,
- }
-
- Ok(sqlx::query_as!(
- ThreadContactResult,
- r#"
- SELECT
- m.thread_id,
- c.id, c.link_id, c.email_address, COALESCE(m.from_name, c.name) as "name", c.sfs_photo_url
- FROM email_messages m
- JOIN email_contacts c ON m.from_contact_id = c.id
- WHERE m.thread_id = ANY($1) AND m.from_contact_id IS NOT NULL
- ORDER BY m.created_at ASC
- "#,
- thread_ids
- )
- .fetch_all(&self.pool)
- .await?
- .into_iter()
- .map(ThreadContactResult::mirror)
- .collect())
- }
-
- #[tracing::instrument(err, skip(self, thread_ids))]
- async fn labels_by_thread_ids(&self, thread_ids: &[Uuid]) -> Result<Vec<Label>, Self::Err> {
- // Query all labels for email_messages in the provided threads
- // Include thread_id in the result set
- Ok(sqlx::query_as!(
- LabelDbRow,
- r#"
- SELECT DISTINCT ON (l.id, m.thread_id)
- l.id,
- m.thread_id as "thread_id!",
- l.link_id,
- l.provider_label_id,
- l.name,
- l.created_at,
- l.message_list_visibility as "message_list_visibility: _",
- l.label_list_visibility as "label_list_visibility: _",
- l.type as "type_: _"
- FROM
- email_messages m
- JOIN email_message_labels ml ON m.id = ml.message_id
- JOIN email_labels l ON ml.label_id = l.id
- WHERE m.thread_id = ANY($1)
- "#,
- thread_ids
- )
- .fetch_all(&self.pool)
- .await?
- .into_iter()
- .map(LabelDbRow::mirror)
- .collect())
- }
-
- #[tracing::instrument(err, skip(self))]
- async fn link_by_fusionauth_and_macro_id(
- &self,
- fusionauth_user_id: &str,
- macro_id: MacroUserIdStr<'_>,
- provider: UserProvider,
- ) -> Result<Option<Link>, Self::Err> {
- let provider: DbUserProvider = match provider {
- UserProvider::Gmail => DbUserProvider::Gmail,
- };
-
- let db_link = sqlx::query_as!(
- db_types::DbLink,
- r#"
- SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
- is_sync_active, created_at, updated_at
- FROM email_links
- WHERE fusionauth_user_id = $1 AND macro_id = $2 AND provider = $3
- LIMIT 1
- "#,
- fusionauth_user_id,
- macro_id.as_ref(),
- provider as _
- )
- .fetch_optional(&self.pool)
- .await?;
-
- db_link
- .map(|v| v.try_into_model())
- .transpose()
- .map_err(|e| sqlx::Error::Decode(Box::new(e)))
- }
-}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
index bb592a0e81..2d5ad16538 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
@@ -1,6 +1,7 @@
use crate::domain::models::{
- Attachment, EmailThreadPreview, Label, LabelListVisibility, LabelType, Link,
- MessageListVisibility,
+ Attachment, AttachmentDraft, AttachmentForwarded, ContactInfo, EmailThreadPreview, Label,
+ LabelListVisibility, LabelType, Link, MessageAttachment, MessageLabel, MessageListVisibility,
+ MessageRow, RecipientType, ThreadRow,
};
use chrono::{DateTime, Utc};
use doppleganger::{Doppleganger, Mirror};
@@ -151,6 +152,281 @@ pub(crate) struct DbLink {
pub updated_at: DateTime<Utc>,
}
+/// DB row for a thread record.
+pub struct DbThreadRow {
+ pub id: uuid::Uuid,
+ pub provider_id: Option<String>,
+ pub link_id: uuid::Uuid,
+ pub inbox_visible: bool,
+ pub is_read: bool,
+ pub latest_inbound_message_ts: Option<DateTime<Utc>>,
+ pub latest_outbound_message_ts: Option<DateTime<Utc>>,
+ pub latest_non_spam_message_ts: Option<DateTime<Utc>>,
+ pub created_at: chrono::DateTime<Utc>,
+ pub updated_at: chrono::DateTime<Utc>,
+}
+
+impl From<DbThreadRow> for ThreadRow {
+ fn from(row: DbThreadRow) -> Self {
+ Self {
+ db_id: row.id,
+ provider_id: row.provider_id,
+ link_id: row.link_id,
+ inbox_visible: row.inbox_visible,
+ is_read: row.is_read,
+ latest_inbound_message_ts: row.latest_inbound_message_ts,
+ latest_outbound_message_ts: row.latest_outbound_message_ts,
+ latest_non_spam_message_ts: row.latest_non_spam_message_ts,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ }
+ }
+}
+
+/// DB row for a message record.
+pub struct DbMessageRow {
+ pub id: uuid::Uuid,
+ pub provider_id: Option<String>,
+ pub thread_id: uuid::Uuid,
+ pub provider_thread_id: Option<String>,
+ pub replying_to_id: Option<uuid::Uuid>,
+ pub global_id: Option<String>,
+ pub link_id: uuid::Uuid,
+ pub provider_history_id: Option<String>,
+ pub internal_date_ts: Option<DateTime<Utc>>,
+ pub snippet: Option<String>,
+ pub size_estimate: Option<i64>,
+ pub subject: Option<String>,
+ pub sent_at: Option<DateTime<Utc>>,
+ pub has_attachments: bool,
+ pub is_read: bool,
+ pub is_starred: bool,
+ pub is_sent: bool,
+ pub is_draft: bool,
+ pub body_text: Option<String>,
+ pub body_html_sanitized: Option<String>,
+ pub body_macro: Option<String>,
+ pub headers_jsonb: Option<serde_json::Value>,
+ pub created_at: chrono::DateTime<Utc>,
+ pub updated_at: chrono::DateTime<Utc>,
+}
+
+impl From<DbMessageRow> for MessageRow {
+ fn from(row: DbMessageRow) -> Self {
+ Self {
+ db_id: row.id,
+ provider_id: row.provider_id,
+ thread_db_id: row.thread_id,
+ provider_thread_id: row.provider_thread_id,
+ replying_to_id: row.replying_to_id,
+ global_id: row.global_id,
+ link_id: row.link_id,
+ subject: row.subject,
+ snippet: row.snippet,
+ provider_history_id: row.provider_history_id,
+ internal_date_ts: row.internal_date_ts,
+ sent_at: row.sent_at,
+ size_estimate: row.size_estimate,
+ is_read: row.is_read,
+ is_starred: row.is_starred,
+ is_sent: row.is_sent,
+ is_draft: row.is_draft,
+ has_attachments: row.has_attachments,
+ body_text: row.body_text,
+ body_html_sanitized: row.body_html_sanitized,
+ body_macro: row.body_macro,
+ headers_json: row.headers_jsonb,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ }
+ }
+}
+
+/// DB row for a message label, including the message_id for grouping.
+pub struct DbMessageLabelRow {
+ pub message_id: uuid::Uuid,
+ pub id: uuid::Uuid,
+ pub link_id: uuid::Uuid,
+ pub provider_label_id: String,
+ pub name: String,
+ pub created_at: chrono::DateTime<Utc>,
+ pub message_list_visibility: MessageListVisibilityDbRow,
+ pub label_list_visibility: LabelListVisibilityDbRow,
+ pub type_: LabelTypeDbRow,
+}
+
+impl From<DbMessageLabelRow> for (uuid::Uuid, MessageLabel) {
+ fn from(row: DbMessageLabelRow) -> Self {
+ let label = MessageLabel {
+ id: Some(row.id),
+ link_id: row.link_id,
+ provider_label_id: row.provider_label_id,
+ name: Some(row.name),
+ created_at: row.created_at,
+ message_list_visibility: Some(match row.message_list_visibility {
+ MessageListVisibilityDbRow::Show => MessageListVisibility::Show,
+ MessageListVisibilityDbRow::Hide => MessageListVisibility::Hide,
+ }),
+ label_list_visibility: Some(match row.label_list_visibility {
+ LabelListVisibilityDbRow::LabelShow => LabelListVisibility::LabelShow,
+ LabelListVisibilityDbRow::LabelShowIfUnread => {
+ LabelListVisibility::LabelShowIfUnread
+ }
+ LabelListVisibilityDbRow::LabelHide => LabelListVisibility::LabelHide,
+ }),
+ type_: Some(match row.type_ {
+ LabelTypeDbRow::System => LabelType::System,
+ LabelTypeDbRow::User => LabelType::User,
+ }),
+ };
+ (row.message_id, label)
+ }
+}
+
+/// DB row for a provider attachment, including the message_id for grouping.
+pub struct DbMessageAttachmentRow {
+ pub message_id: uuid::Uuid,
+ pub id: uuid::Uuid,
+ pub provider_attachment_id: Option<String>,
+ pub filename: Option<String>,
+ pub mime_type: Option<String>,
+ pub size_bytes: Option<i64>,
+ pub sfs_id: Option<uuid::Uuid>,
+ pub content_id: Option<String>,
+}
+
+impl From<DbMessageAttachmentRow> for (uuid::Uuid, MessageAttachment) {
+ fn from(row: DbMessageAttachmentRow) -> Self {
+ let att = MessageAttachment {
+ db_id: row.id,
+ provider_id: row.provider_attachment_id,
+ filename: row.filename,
+ mime_type: row.mime_type,
+ size_bytes: row.size_bytes,
+ sfs_id: row.sfs_id,
+ content_id: row.content_id,
+ };
+ (row.message_id, att)
+ }
+}
+
+/// DB row for a draft attachment.
+pub struct DbDraftAttachmentRow {
+ pub draft_id: uuid::Uuid,
+ pub id: uuid::Uuid,
+ pub file_name: String,
+ pub content_type: String,
+ pub sha: String,
+ pub size: i32,
+ pub s3_key: String,
+}
+
+impl From<DbDraftAttachmentRow> for (uuid::Uuid, AttachmentDraft) {
+ fn from(row: DbDraftAttachmentRow) -> Self {
+ let att = AttachmentDraft {
+ id: row.id,
+ draft_id: row.draft_id,
+ file_name: row.file_name,
+ content_type: row.content_type,
+ sha: row.sha,
+ size: row.size,
+ s3_key: row.s3_key,
+ };
+ (row.draft_id, att)
+ }
+}
+
+/// DB row for a forwarded attachment.
+pub struct DbForwardedAttachmentRow {
+ pub draft_id: uuid::Uuid,
+ pub attachment_id: uuid::Uuid,
+ pub provider_attachment_id: Option<String>,
+ pub message_provider_id: String,
+ pub filename: Option<String>,
+ pub mime_type: Option<String>,
+ pub size_bytes: Option<i64>,
+}
+
+impl From<DbForwardedAttachmentRow> for (uuid::Uuid, AttachmentForwarded) {
+ fn from(row: DbForwardedAttachmentRow) -> Self {
+ let att = AttachmentForwarded {
+ attachment_id: row.attachment_id,
+ draft_id: row.draft_id,
+ provider_attachment_id: row.provider_attachment_id,
+ message_provider_id: row.message_provider_id,
+ filename: row.filename,
+ mime_type: row.mime_type,
+ size_bytes: row.size_bytes,
+ };
+ (row.draft_id, att)
+ }
+}
+
+/// DB row for a sender contact, including the message_id for grouping.
+pub struct DbSenderRow {
+ pub message_id: uuid::Uuid,
+ pub email_address: Option<String>,
+ pub name: Option<String>,
+ pub sfs_photo_url: Option<String>,
+}
+
+impl From<DbSenderRow> for (uuid::Uuid, ContactInfo) {
+ fn from(row: DbSenderRow) -> Self {
+ let contact = ContactInfo {
+ email: row.email_address.unwrap_or_default(),
+ name: row.name,
+ photo_url: row.sfs_photo_url,
+ };
+ (row.message_id, contact)
+ }
+}
+
+/// DB row for a recipient, including the message_id and recipient type.
+pub struct DbRecipientRow {
+ pub message_id: uuid::Uuid,
+ pub email_address: String,
+ pub name: Option<String>,
+ pub sfs_photo_url: Option<String>,
+ pub recipient_type: DbRecipientType,
+}
+
+/// DB-layer recipient type enum, matching the `email_recipient_type` postgres enum.
+#[derive(Debug, sqlx::Type, Clone, Copy, PartialEq, Eq)]
+#[sqlx(type_name = "email_recipient_type", rename_all = "UPPERCASE")]
+pub enum DbRecipientType {
+ /// To recipient.
+ To,
+ /// Cc recipient.
+ Cc,
+ /// Bcc recipient.
+ Bcc,
+}
+
+impl From<DbRecipientType> for RecipientType {
+ fn from(v: DbRecipientType) -> Self {
+ match v {
+ DbRecipientType::To => RecipientType::To,
+ DbRecipientType::Cc => RecipientType::Cc,
+ DbRecipientType::Bcc => RecipientType::Bcc,
+ }
+ }
+}
+
+impl From<DbRecipientRow> for (uuid::Uuid, ContactInfo, RecipientType) {
+ fn from(row: DbRecipientRow) -> Self {
+ let contact = ContactInfo {
+ email: row.email_address,
+ name: row.name,
+ photo_url: row.sfs_photo_url,
+ };
+ (
+ row.message_id,
+ contact,
+ RecipientType::from(row.recipient_type),
+ )
+ }
+}
+
impl DbLink {
pub(crate) fn try_into_model(self) -> Result<Link, macro_user_id::error::ParseErr> {
let DbLink {
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
new file mode 100644
index 0000000000..e959ae9f27
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
@@ -0,0 +1,38 @@
+use crate::domain::models::{Link, UserProvider};
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+
+use super::db_types::{DbLink, DbUserProvider};
+
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn link_by_fusionauth_and_macro_id(
+ pool: &PgPool,
+ fusionauth_user_id: &str,
+ macro_id: MacroUserIdStr<'_>,
+ provider: UserProvider,
+) -> Result<Option<Link>, sqlx::Error> {
+ let provider: DbUserProvider = match provider {
+ UserProvider::Gmail => DbUserProvider::Gmail,
+ };
+
+ let db_link = sqlx::query_as!(
+ DbLink,
+ r#"
+ SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
+ is_sync_active, created_at, updated_at
+ FROM email_links
+ WHERE fusionauth_user_id = $1 AND macro_id = $2 AND provider = $3
+ LIMIT 1
+ "#,
+ fusionauth_user_id,
+ macro_id.as_ref(),
+ provider as _
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ db_link
+ .map(|v| v.try_into_model())
+ .transpose()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs
new file mode 100644
index 0000000000..8244819aab
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs
@@ -0,0 +1,272 @@
+use crate::domain::{
+ models::{
+ AttachmentDraft, AttachmentForwarded, ContactInfo, MessageAttachment, MessageLabel,
+ RecipientType,
+ },
+ ports::RecipientsByMessageId,
+};
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use std::collections::HashMap;
+use uuid::Uuid;
+
+use super::db_types::{
+ DbDraftAttachmentRow, DbForwardedAttachmentRow, DbMessageAttachmentRow, DbMessageLabelRow,
+ DbRecipientRow, DbRecipientType, DbSenderRow,
+};
+
+#[tracing::instrument(err, skip(pool, message_ids))]
+pub(super) async fn senders_by_message_ids(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+) -> Result<HashMap<Uuid, ContactInfo>, sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = sqlx::query_as!(
+ DbSenderRow,
+ r#"
+ SELECT
+ m.id as message_id,
+ c.email_address,
+ COALESCE(m.from_name, c.name) as "name",
+ c.sfs_photo_url
+ FROM email_messages m
+ INNER JOIN email_contacts c ON c.id = m.from_contact_id
+ WHERE m.id = ANY($1)
+ AND m.from_contact_id IS NOT NULL
+ "#,
+ message_ids,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| {
+ let (message_id, contact): (Uuid, ContactInfo) = row.into();
+ (message_id, contact)
+ })
+ .collect())
+}
+
+#[tracing::instrument(err, skip(pool, message_ids))]
+pub(super) async fn recipients_by_message_ids(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+) -> Result<RecipientsByMessageId, sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = sqlx::query_as!(
+ DbRecipientRow,
+ r#"
+ SELECT
+ mr.message_id,
+ c.email_address,
+ COALESCE(mr.name, c.name) as "name",
+ c.sfs_photo_url,
+ mr.recipient_type as "recipient_type!: DbRecipientType"
+ FROM email_messages m
+ JOIN email_message_recipients mr ON m.id = mr.message_id
+ JOIN email_contacts c ON mr.contact_id = c.id
+ WHERE m.id = ANY($1)
+ ORDER BY mr.message_id, mr.recipient_type
+ "#,
+ message_ids,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let mut map: HashMap<Uuid, Vec<(ContactInfo, RecipientType)>> = HashMap::new();
+ for row in rows {
+ let (message_id, contact, r_type) =
+ <DbRecipientRow as Into<(Uuid, ContactInfo, RecipientType)>>::into(row);
+ map.entry(message_id).or_default().push((contact, r_type));
+ }
+ Ok(map)
+}
+
+#[tracing::instrument(err, skip(pool, message_ids))]
+pub(super) async fn labels_by_message_ids(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+) -> Result<HashMap<Uuid, Vec<MessageLabel>>, sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = sqlx::query_as!(
+ DbMessageLabelRow,
+ r#"
+ SELECT
+ ml.message_id,
+ l.id,
+ l.link_id,
+ l.provider_label_id,
+ l.name,
+ l.created_at,
+ l.message_list_visibility as "message_list_visibility: _",
+ l.label_list_visibility as "label_list_visibility: _",
+ l.type as "type_: _"
+ FROM email_message_labels ml
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = ANY($1)
+ ORDER BY ml.message_id, l.name
+ "#,
+ message_ids,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let mut map: HashMap<Uuid, Vec<MessageLabel>> = HashMap::new();
+ for row in rows {
+ let (message_id, label) = <DbMessageLabelRow as Into<(Uuid, MessageLabel)>>::into(row);
+ map.entry(message_id).or_default().push(label);
+ }
+ Ok(map)
+}
+
+#[tracing::instrument(err, skip(pool, message_ids))]
+pub(super) async fn attachments_by_message_ids(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+) -> Result<HashMap<Uuid, Vec<MessageAttachment>>, sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = sqlx::query_as!(
+ DbMessageAttachmentRow,
+ r#"
+ SELECT
+ ea.message_id,
+ ea.id,
+ ea.provider_attachment_id,
+ ea.filename,
+ ea.mime_type,
+ ea.size_bytes,
+ eas.sfs_id as "sfs_id?",
+ ea.content_id
+ FROM email_attachments ea
+ LEFT JOIN email_attachments_sfs eas ON ea.id = eas.attachment_id
+ WHERE ea.message_id = ANY($1)
+ ORDER BY ea.message_id, ea.filename NULLS LAST
+ "#,
+ message_ids,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let mut map: HashMap<Uuid, Vec<MessageAttachment>> = HashMap::new();
+ for row in rows {
+ let (message_id, att) =
+ <DbMessageAttachmentRow as Into<(Uuid, MessageAttachment)>>::into(row);
+ map.entry(message_id).or_default().push(att);
+ }
+ Ok(map)
+}
+
+#[tracing::instrument(err, skip(pool, message_ids))]
+pub(super) async fn draft_attachments_by_message_ids(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+) -> Result<HashMap<Uuid, Vec<AttachmentDraft>>, sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = sqlx::query_as!(
+ DbDraftAttachmentRow,
+ r#"
+ SELECT id, draft_id, file_name, content_type, sha, size, s3_key
+ FROM email_attachments_drafts
+ WHERE draft_id = ANY($1)
+ ORDER BY draft_id, file_name ASC
+ "#,
+ message_ids,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let mut map: HashMap<Uuid, Vec<AttachmentDraft>> = HashMap::new();
+ for row in rows {
+ let (draft_id, att) = <DbDraftAttachmentRow as Into<(Uuid, AttachmentDraft)>>::into(row);
+ map.entry(draft_id).or_default().push(att);
+ }
+ Ok(map)
+}
+
+#[tracing::instrument(err, skip(pool, message_ids))]
+pub(super) async fn forwarded_attachments_by_message_ids(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+) -> Result<HashMap<Uuid, Vec<AttachmentForwarded>>, sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = sqlx::query_as!(
+ DbForwardedAttachmentRow,
+ r#"
+ SELECT
+ eaf.message_id as draft_id,
+ eaf.attachment_id,
+ ea.provider_attachment_id,
+ orig_msg.provider_id as "message_provider_id!",
+ ea.filename,
+ ea.mime_type,
+ ea.size_bytes
+ FROM email_attachments_fwd eaf
+ JOIN email_attachments ea ON eaf.attachment_id = ea.id
+ JOIN email_messages orig_msg ON ea.message_id = orig_msg.id
+ WHERE eaf.message_id = ANY($1)
+ ORDER BY eaf.message_id, ea.filename ASC
+ "#,
+ message_ids,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let mut map: HashMap<Uuid, Vec<AttachmentForwarded>> = HashMap::new();
+ for row in rows {
+ let (draft_id, att) =
+ <DbForwardedAttachmentRow as Into<(Uuid, AttachmentForwarded)>>::into(row);
+ map.entry(draft_id).or_default().push(att);
+ }
+ Ok(map)
+}
+
+#[tracing::instrument(err, skip(pool, message_ids))]
+pub(super) async fn scheduled_send_times_by_message_ids(
+ pool: &PgPool,
+ message_ids: &[Uuid],
+) -> Result<HashMap<Uuid, DateTime<Utc>>, sqlx::Error> {
+ if message_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ struct DbScheduledRow {
+ message_id: Uuid,
+ send_time: DateTime<Utc>,
+ }
+
+ let rows = sqlx::query_as!(
+ DbScheduledRow,
+ r#"
+ SELECT message_id, send_time
+ FROM email_scheduled_messages
+ WHERE message_id = ANY($1) AND sent = false
+ "#,
+ message_ids,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|r| (r.message_id, r.send_time))
+ .collect())
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
new file mode 100644
index 0000000000..498e33e073
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
@@ -0,0 +1,134 @@
+use crate::domain::{
+ models::{
+ Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailThreadPreview,
+ Label, Link, MessageAttachment, MessageLabel, MessageRow, PreviewCursorQuery, ThreadRow,
+ UserProvider,
+ },
+ ports::{EmailRepo, RecipientsByMessageId},
+};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use std::collections::HashMap;
+use uuid::Uuid;
+
+mod db_types;
+mod dynamic;
+mod link;
+mod message;
+mod preview;
+mod preview_views;
+mod thread;
+
+#[cfg(test)]
+mod test;
+
+#[derive(Clone)]
+pub struct EmailPgRepo {
+ pool: PgPool,
+}
+
+impl EmailPgRepo {
+ pub fn new(pool: PgPool) -> Self {
+ EmailPgRepo { pool }
+ }
+}
+
+impl EmailRepo for EmailPgRepo {
+ type Err = sqlx::Error;
+
+ async fn previews_for_view_cursor(
+ &self,
+ query: PreviewCursorQuery,
+ user_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<EmailThreadPreview>, Self::Err> {
+ preview::previews_for_view_cursor(&self.pool, query, user_id).await
+ }
+
+ async fn attachments_by_thread_ids(
+ &self,
+ thread_ids: &[Uuid],
+ ) -> Result<Vec<Attachment>, Self::Err> {
+ preview::attachments_by_thread_ids(&self.pool, thread_ids).await
+ }
+
+ async fn contacts_by_thread_ids(&self, thread_ids: &[Uuid]) -> Result<Vec<Contact>, Self::Err> {
+ preview::contacts_by_thread_ids(&self.pool, thread_ids).await
+ }
+
+ async fn labels_by_thread_ids(&self, thread_ids: &[Uuid]) -> Result<Vec<Label>, Self::Err> {
+ preview::labels_by_thread_ids(&self.pool, thread_ids).await
+ }
+
+ async fn link_by_fusionauth_and_macro_id(
+ &self,
+ fusionauth_user_id: &str,
+ macro_id: MacroUserIdStr<'_>,
+ provider: UserProvider,
+ ) -> Result<Option<Link>, Self::Err> {
+ link::link_by_fusionauth_and_macro_id(&self.pool, fusionauth_user_id, macro_id, provider)
+ .await
+ }
+
+ async fn thread_by_id(&self, thread_id: Uuid) -> Result<Option<ThreadRow>, Self::Err> {
+ thread::thread_by_id(&self.pool, thread_id).await
+ }
+
+ async fn messages_by_thread_id_paginated(
+ &self,
+ thread_id: Uuid,
+ offset: i64,
+ limit: i64,
+ ) -> Result<Vec<MessageRow>, Self::Err> {
+ thread::messages_by_thread_id_paginated(&self.pool, thread_id, offset, limit).await
+ }
+
+ async fn senders_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, ContactInfo>, Self::Err> {
+ message::senders_by_message_ids(&self.pool, message_ids).await
+ }
+
+ async fn recipients_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> Result<RecipientsByMessageId, Self::Err> {
+ message::recipients_by_message_ids(&self.pool, message_ids).await
+ }
+
+ async fn labels_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, Vec<MessageLabel>>, Self::Err> {
+ message::labels_by_message_ids(&self.pool, message_ids).await
+ }
+
+ async fn attachments_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, Vec<MessageAttachment>>, Self::Err> {
+ message::attachments_by_message_ids(&self.pool, message_ids).await
+ }
+
+ async fn draft_attachments_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, Vec<AttachmentDraft>>, Self::Err> {
+ message::draft_attachments_by_message_ids(&self.pool, message_ids).await
+ }
+
+ async fn forwarded_attachments_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, Vec<AttachmentForwarded>>, Self::Err> {
+ message::forwarded_attachments_by_message_ids(&self.pool, message_ids).await
+ }
+
+ async fn scheduled_send_times_by_message_ids(
+ &self,
+ message_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, DateTime<Utc>>, Self::Err> {
+ message::scheduled_send_times_by_message_ids(&self.pool, message_ids).await
+ }
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs
new file mode 100644
index 0000000000..19a7219750
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs
@@ -0,0 +1,181 @@
+use crate::domain::models::{
+ Attachment, Contact, EmailThreadPreview, Label, PreviewCursorQuery, PreviewView,
+ PreviewViewStandardLabel,
+};
+use doppleganger::{Doppleganger, Mirror};
+use either::Either;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::db_types::{AttachmentDbRow, LabelDbRow, ThreadPreviewCursorDbRow};
+
+#[tracing::instrument(err, skip(pool, query), fields(link_id = %query.link_id, view = %query.view))]
+pub(super) async fn previews_for_view_cursor(
+ pool: &PgPool,
+ query: PreviewCursorQuery,
+ user_id: MacroUserIdStr<'static>,
+) -> Result<Vec<EmailThreadPreview>, sqlx::Error> {
+ let PreviewCursorQuery {
+ view,
+ link_id,
+ limit,
+ query,
+ } = query;
+
+ let query = query.split_option();
+
+ Ok(match (view, query) {
+ (view, Either::Right(dynamic_query)) => {
+ super::dynamic::dynamic_email_thread_cursor(pool, &link_id, limit, &view, dynamic_query)
+ .await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox), Either::Left(query)) => {
+ super::preview_views::new_inbox::new_inbox_preview_cursor(pool, &link_id, limit, &query)
+ .await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Sent), Either::Left(query)) => {
+ super::preview_views::sent::sent_preview_cursor(pool, &link_id, limit, &query).await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts), Either::Left(query)) => {
+ super::preview_views::draft::drafts_preview_cursor(pool, &link_id, limit, &query)
+ .await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Starred), Either::Left(query)) => {
+ super::preview_views::starred::starred_preview_cursor(pool, &link_id, limit, &query)
+ .await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::All), Either::Left(query)) => {
+ super::preview_views::all_mail::all_mail_preview_cursor(pool, &link_id, limit, &query)
+ .await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Important), Either::Left(query)) => {
+ super::preview_views::important::important_preview_cursor(pool, &link_id, limit, &query)
+ .await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Other), Either::Left(query)) => {
+ super::preview_views::other_inbox::other_inbox_preview_cursor(
+ pool, &link_id, limit, &query,
+ )
+ .await?
+ }
+ (PreviewView::UserLabel(label_name), Either::Left(query)) => {
+ super::preview_views::user_label::user_label_preview_cursor(
+ pool,
+ &link_id,
+ limit,
+ &query,
+ &label_name,
+ )
+ .await?
+ }
+ }
+ .into_iter()
+ .map(|row: ThreadPreviewCursorDbRow| row.with_user_id(user_id.clone()))
+ .collect())
+}
+
+#[tracing::instrument(err, skip(pool, thread_ids))]
+pub(super) async fn attachments_by_thread_ids(
+ pool: &PgPool,
+ thread_ids: &[Uuid],
+) -> Result<Vec<Attachment>, sqlx::Error> {
+ Ok(sqlx::query_as!(
+ AttachmentDbRow,
+ r#"
+ SELECT
+ a.id,
+ a.message_id,
+ a.provider_attachment_id,
+ a.filename,
+ a.mime_type,
+ a.size_bytes,
+ a.content_id,
+ a.created_at,
+ m.thread_id
+ FROM
+ email_attachments a
+ JOIN
+ email_messages m ON a.message_id = m.id
+ WHERE
+ m.thread_id = ANY($1)
+ ORDER BY
+ a.created_at ASC
+ "#,
+ thread_ids
+ )
+ .fetch_all(pool)
+ .await?
+ .into_iter()
+ .map(AttachmentDbRow::mirror)
+ .collect())
+}
+
+#[tracing::instrument(err, skip(pool, thread_ids))]
+pub(super) async fn contacts_by_thread_ids(
+ pool: &PgPool,
+ thread_ids: &[Uuid],
+) -> Result<Vec<Contact>, sqlx::Error> {
+ #[derive(Debug, Doppleganger)]
+ #[dg(forward = Contact)]
+ struct ThreadContactResult {
+ thread_id: Uuid,
+ id: Uuid,
+ link_id: Uuid,
+ email_address: Option<String>,
+ name: Option<String>,
+ sfs_photo_url: Option<String>,
+ }
+
+ Ok(sqlx::query_as!(
+ ThreadContactResult,
+ r#"
+ SELECT
+ m.thread_id,
+ c.id, c.link_id, c.email_address, COALESCE(m.from_name, c.name) as "name", c.sfs_photo_url
+ FROM email_messages m
+ JOIN email_contacts c ON m.from_contact_id = c.id
+ WHERE m.thread_id = ANY($1) AND m.from_contact_id IS NOT NULL
+ ORDER BY m.created_at ASC
+ "#,
+ thread_ids
+ )
+ .fetch_all(pool)
+ .await?
+ .into_iter()
+ .map(ThreadContactResult::mirror)
+ .collect())
+}
+
+#[tracing::instrument(err, skip(pool, thread_ids))]
+pub(super) async fn labels_by_thread_ids(
+ pool: &PgPool,
+ thread_ids: &[Uuid],
+) -> Result<Vec<Label>, sqlx::Error> {
+ Ok(sqlx::query_as!(
+ LabelDbRow,
+ r#"
+ SELECT DISTINCT ON (l.id, m.thread_id)
+ l.id,
+ m.thread_id as "thread_id!",
+ l.link_id,
+ l.provider_label_id,
+ l.name,
+ l.created_at,
+ l.message_list_visibility as "message_list_visibility: _",
+ l.label_list_visibility as "label_list_visibility: _",
+ l.type as "type_: _"
+ FROM
+ email_messages m
+ JOIN email_message_labels ml ON m.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m.thread_id = ANY($1)
+ "#,
+ thread_ids
+ )
+ .fetch_all(pool)
+ .await?
+ .into_iter()
+ .map(LabelDbRow::mirror)
+ .collect())
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views.rs
similarity index 100%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/queries.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views.rs
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/all_mail.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs
similarity index 100%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/queries/all_mail.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs
similarity index 100%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/queries/draft.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/important.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs
similarity index 100%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/queries/important.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/new_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
similarity index 100%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/queries/new_inbox.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/other_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs
similarity index 100%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/queries/other_inbox.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/sent.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs
similarity index 100%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/queries/sent.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/starred.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs
similarity index 100%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/queries/starred.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/user_label.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs
similarity index 100%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/queries/user_label.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs
similarity index 81%
rename from rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs
rename to rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs
index 8437b132b5..18ee8bc052 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs
@@ -1,154 +1,8 @@
-use std::sync::Arc;
-
use super::*;
-use crate::domain::models::{LabelType, PreviewView, PreviewViewStandardLabel};
-use crate::domain::ports::EmailRepo;
-use filter_ast::Expr;
-use item_filters::ast::email::{Email, EmailLiteral};
-use macro_db_migrator::MACRO_DB_MIGRATIONS;
-use macro_user_id::cowlike::CowLike;
-use macro_user_id::email::EmailStr;
-use models_pagination::{Cursor, CursorVal, Query, SimpleSortMethod};
-use sqlx::{Pool, Postgres};
-use uuid::Uuid;
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_labels"))
-)]
-async fn test_labels_by_thread_ids_single_thread(pool: Pool<Postgres>) -> anyhow::Result<()> {
- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE
- let repo = EmailPgRepo::new(pool);
-
- let thread_ids = vec![Uuid::parse_str("11111111-1111-1111-1111-111111111111")?];
- let labels = repo.labels_by_thread_ids(&thread_ids).await?;
-
- assert_eq!(labels.len(), 2, "Thread 1 should have 2 labels");
-
- let inbox_label = labels.iter().find(|l| l.name == "INBOX");
- assert!(inbox_label.is_some(), "Should have INBOX label");
-
- let important_label = labels.iter().find(|l| l.name == "IMPORTANT");
- assert!(important_label.is_some(), "Should have IMPORTANT label");
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_labels"))
-)]
-async fn test_labels_by_thread_ids_multiple_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let repo = EmailPgRepo::new(pool);
-
- let thread_ids = vec![
- Uuid::parse_str("11111111-1111-1111-1111-111111111111")?,
- Uuid::parse_str("22222222-2222-2222-2222-222222222222")?,
- ];
- let labels = repo.labels_by_thread_ids(&thread_ids).await?;
-
- // Thread 1 has 2 labels (INBOX, IMPORTANT)
- // Thread 2 has 2 labels (INBOX, SENT)
- // Should get four unique labels as it's distinct across (thread_id, label_id)
- assert_eq!(
- labels.len(),
- 4,
- "Should have 4 unique labels across both threads"
- );
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_labels"))
-)]
-async fn test_labels_by_thread_ids_no_duplicate_labels_same_thread(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = EmailPgRepo::new(pool);
-
- // Thread 3 has multiple messages with the same label
- let thread_ids = vec![Uuid::parse_str("33333333-3333-3333-3333-333333333333")?];
- let labels = repo.labels_by_thread_ids(&thread_ids).await?;
-
- assert_eq!(
- labels.len(),
- 1,
- "Should have only 1 label despite multiple messages having it"
- );
- assert_eq!(labels[0].name, "INBOX");
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_labels"))
-)]
-async fn test_labels_by_thread_ids_thread_with_no_labels(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = EmailPgRepo::new(pool);
-
- let thread_ids = vec![Uuid::parse_str("44444444-4444-4444-4444-444444444444")?];
- let labels = repo.labels_by_thread_ids(&thread_ids).await?;
-
- assert_eq!(
- labels.len(),
- 0,
- "Thread with no messages/labels should return empty"
- );
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_labels"))
-)]
-async fn test_labels_by_thread_ids_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let repo = EmailPgRepo::new(pool);
-
- let thread_ids: Vec<Uuid> = vec![];
- let labels = repo.labels_by_thread_ids(&thread_ids).await?;
-
- assert_eq!(labels.len(), 0, "Empty input should return empty result");
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_labels"))
-)]
-async fn test_labels_by_thread_ids_different_label_types(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = EmailPgRepo::new(pool);
-
- let thread_ids = vec![Uuid::parse_str("55555555-5555-5555-5555-555555555555")?];
- let labels = repo.labels_by_thread_ids(&thread_ids).await?;
-
- assert_eq!(labels.len(), 2, "Should have both system and user labels");
-
- let system_label = labels.iter().find(|l| l.name == "INBOX");
- assert!(system_label.is_some());
- assert_eq!(system_label.unwrap().type_, LabelType::System);
-
- let user_label = labels.iter().find(|l| l.name == "MyCustomLabel");
- assert!(user_label.is_some());
- assert_eq!(user_label.unwrap().type_, LabelType::User);
-
- Ok(())
-}
-// ============================================================================
-// Dynamic Query Builder Integration Tests
-// ============================================================================
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_inbox_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -183,7 +37,7 @@ async fn test_dynamic_query_inbox_view(pool: Pool<Postgres>) -> anyhow::Result<(
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_sent_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -209,7 +63,7 @@ async fn test_dynamic_query_sent_view(pool: Pool<Postgres>) -> anyhow::Result<()
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_drafts_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -235,7 +89,7 @@ async fn test_dynamic_query_drafts_view(pool: Pool<Postgres>) -> anyhow::Result<
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_starred_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -261,7 +115,7 @@ async fn test_dynamic_query_starred_view(pool: Pool<Postgres>) -> anyhow::Result
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_important_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -300,7 +154,7 @@ async fn test_dynamic_query_important_view(pool: Pool<Postgres>) -> anyhow::Resu
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_static_important_query_includes_drafts(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -308,7 +162,7 @@ async fn test_static_important_query_includes_drafts(pool: Pool<Postgres>) -> an
let query = Query::Sort(SimpleSortMethod::UpdatedAt, ());
let results =
- queries::important::important_preview_cursor(&pool, &link_id, limit, &query).await?;
+ preview_views::important::important_preview_cursor(&pool, &link_id, limit, &query).await?;
assert_eq!(
results.len(),
@@ -339,7 +193,7 @@ async fn test_static_important_query_includes_drafts(pool: Pool<Postgres>) -> an
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_user_label_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -365,7 +219,7 @@ async fn test_dynamic_query_user_label_view(pool: Pool<Postgres>) -> anyhow::Res
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_with_sender_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -399,7 +253,7 @@ async fn test_dynamic_query_with_sender_filter(pool: Pool<Postgres>) -> anyhow::
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_with_partial_sender_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -426,7 +280,7 @@ async fn test_dynamic_query_with_partial_sender_filter(pool: Pool<Postgres>) ->
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_with_recipient_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -453,7 +307,7 @@ async fn test_dynamic_query_with_recipient_filter(pool: Pool<Postgres>) -> anyho
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_with_cc_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -481,7 +335,7 @@ async fn test_dynamic_query_with_cc_filter(pool: Pool<Postgres>) -> anyhow::Resu
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_inbox_with_sender_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -517,7 +371,7 @@ async fn test_dynamic_query_inbox_with_sender_filter(pool: Pool<Postgres>) -> an
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_drafts_with_recipient_filter(
pool: Pool<Postgres>,
@@ -548,7 +402,7 @@ async fn test_dynamic_query_drafts_with_recipient_filter(
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_with_and_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -580,7 +434,7 @@ async fn test_dynamic_query_with_and_filter(pool: Pool<Postgres>) -> anyhow::Res
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_with_or_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -612,7 +466,7 @@ async fn test_dynamic_query_with_or_filter(pool: Pool<Postgres>) -> anyhow::Resu
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_pagination(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -683,7 +537,7 @@ async fn test_dynamic_query_pagination(pool: Pool<Postgres>) -> anyhow::Result<(
// Thread 8 (msg 8): DRAFT + CATEGORY_UPDATES → important (DRAFT priority overrides depriority)
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -785,7 +639,7 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyh
// Thread 7 (CATEGORY_PROMOTIONS) has importance=false AND inbox_visible=true → included.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_inbox_view_with_importance_false(
pool: Pool<Postgres>,
@@ -826,7 +680,7 @@ async fn test_dynamic_query_inbox_view_with_importance_false(
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_with_single_thread_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -849,7 +703,7 @@ async fn test_dynamic_query_with_single_thread_id(pool: Pool<Postgres>) -> anyho
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_dynamic_query_thread_id_with_sender_filter(
pool: Pool<Postgres>,
@@ -888,7 +742,7 @@ async fn test_dynamic_query_thread_id_with_sender_filter(
// even though it has a depriority label.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_importance_true_includes_drafts_with_depriority_label(
pool: Pool<Postgres>,
@@ -926,7 +780,7 @@ async fn test_importance_true_includes_drafts_with_depriority_label(
// DRAFT is a priority label, so it should NOT appear in importance=false results.
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
)]
async fn test_importance_false_excludes_drafts(pool: Pool<Postgres>) -> anyhow::Result<()> {
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/labels.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/labels.rs
new file mode 100644
index 0000000000..7891bc6fd9
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/labels.rs
@@ -0,0 +1,132 @@
+use super::*;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_single_thread(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids = vec![Uuid::parse_str("11111111-1111-1111-1111-111111111111")?];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(labels.len(), 2, "Thread 1 should have 2 labels");
+
+ let inbox_label = labels.iter().find(|l| l.name == "INBOX");
+ assert!(inbox_label.is_some(), "Should have INBOX label");
+
+ let important_label = labels.iter().find(|l| l.name == "IMPORTANT");
+ assert!(important_label.is_some(), "Should have IMPORTANT label");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_multiple_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids = vec![
+ Uuid::parse_str("11111111-1111-1111-1111-111111111111")?,
+ Uuid::parse_str("22222222-2222-2222-2222-222222222222")?,
+ ];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ // Thread 1 has 2 labels (INBOX, IMPORTANT)
+ // Thread 2 has 2 labels (INBOX, SENT)
+ // Should get four unique labels as it's distinct across (thread_id, label_id)
+ assert_eq!(
+ labels.len(),
+ 4,
+ "Should have 4 unique labels across both threads"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_no_duplicate_labels_same_thread(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ // Thread 3 has multiple messages with the same label
+ let thread_ids = vec![Uuid::parse_str("33333333-3333-3333-3333-333333333333")?];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(
+ labels.len(),
+ 1,
+ "Should have only 1 label despite multiple messages having it"
+ );
+ assert_eq!(labels[0].name, "INBOX");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_thread_with_no_labels(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids = vec![Uuid::parse_str("44444444-4444-4444-4444-444444444444")?];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(
+ labels.len(),
+ 0,
+ "Thread with no messages/labels should return empty"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids: Vec<Uuid> = vec![];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(labels.len(), 0, "Empty input should return empty result");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_labels"))
+)]
+async fn test_labels_by_thread_ids_different_label_types(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_ids = vec![Uuid::parse_str("55555555-5555-5555-5555-555555555555")?];
+ let labels = repo.labels_by_thread_ids(&thread_ids).await?;
+
+ assert_eq!(labels.len(), 2, "Should have both system and user labels");
+
+ let system_label = labels.iter().find(|l| l.name == "INBOX");
+ assert!(system_label.is_some());
+ assert_eq!(system_label.unwrap().type_, LabelType::System);
+
+ let user_label = labels.iter().find(|l| l.name == "MyCustomLabel");
+ assert!(user_label.is_some());
+ assert_eq!(user_label.unwrap().type_, LabelType::User);
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs
new file mode 100644
index 0000000000..01ad3fdd9b
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/link.rs
@@ -0,0 +1,67 @@
+use super::*;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_link_by_fusionauth_and_macro_id_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let link = repo
+ .link_by_fusionauth_and_macro_id("fa-user-1", macro_id, UserProvider::Gmail)
+ .await?;
+
+ assert!(link.is_some(), "Link should exist");
+ let link = link.unwrap();
+ assert_eq!(
+ link.id,
+ Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?
+ );
+ assert_eq!(link.fusionauth_user_id, "fa-user-1");
+ assert_eq!(link.provider, UserProvider::Gmail);
+ assert!(link.is_sync_active);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_link_by_fusionauth_and_macro_id_wrong_fusionauth(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let link = repo
+ .link_by_fusionauth_and_macro_id("nonexistent-fa-user", macro_id, UserProvider::Gmail)
+ .await?;
+
+ assert!(
+ link.is_none(),
+ "Wrong fusionauth_user_id should return None"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_link_by_fusionauth_and_macro_id_wrong_macro_id(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let link = repo
+ .link_by_fusionauth_and_macro_id("fa-user-1", macro_id, UserProvider::Gmail)
+ .await?;
+
+ assert!(link.is_none(), "Wrong macro_id should return None");
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/message.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/message.rs
new file mode 100644
index 0000000000..40eb6bd8c3
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/message.rs
@@ -0,0 +1,451 @@
+use super::*;
+
+// ── senders_by_message_ids ──────────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_senders_by_message_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg1 = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;
+ let msg2 = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;
+ let senders = repo.senders_by_message_ids(&[msg1, msg2]).await?;
+
+ assert_eq!(senders.len(), 2, "Both messages have senders");
+
+ let sender1 = senders.get(&msg1).expect("msg1 should have a sender");
+ assert_eq!(sender1.email, "[email protected]");
+ // from_name ('Alice S.') should take priority over contact.name ('Alice Smith')
+ assert_eq!(sender1.name.as_deref(), Some("Alice S."));
+ assert_eq!(
+ sender1.photo_url.as_deref(),
+ Some("https://photos.example.com/alice.jpg")
+ );
+
+ let sender2 = senders.get(&msg2).expect("msg2 should have a sender");
+ assert_eq!(sender2.email, "[email protected]");
+ // msg2 has no from_name, so contact.name is used
+ assert_eq!(sender2.name.as_deref(), Some("Bob Jones"));
+ assert!(sender2.photo_url.is_none());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_senders_by_message_ids_no_from_contact(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ // msg3 is a draft with no from_contact_id
+ let msg3 = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;
+ let senders = repo.senders_by_message_ids(&[msg3]).await?;
+
+ assert!(
+ senders.is_empty(),
+ "Message without from_contact should not appear"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_senders_by_message_ids_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let senders = repo.senders_by_message_ids(&[]).await?;
+ assert!(senders.is_empty());
+
+ Ok(())
+}
+
+// ── recipients_by_message_ids ───────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_recipients_by_message_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg1 = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;
+ let recipients = repo.recipients_by_message_ids(&[msg1]).await?;
+
+ let msg1_recips = recipients.get(&msg1).expect("msg1 should have recipients");
+ assert_eq!(msg1_recips.len(), 2, "msg1 has TO and CC recipients");
+
+ // Ordered by recipient_type: TO < CC < BCC
+ let (to_contact, to_type) = &msg1_recips[0];
+ assert_eq!(*to_type, RecipientType::To);
+ assert_eq!(to_contact.email, "[email protected]");
+ // recipient has no name override, falls back to contact.name
+ assert_eq!(to_contact.name.as_deref(), Some("Bob Jones"));
+
+ let (cc_contact, cc_type) = &msg1_recips[1];
+ assert_eq!(*cc_type, RecipientType::Cc);
+ assert_eq!(cc_contact.email, "[email protected]");
+ // recipient has name override 'Carol W.'
+ assert_eq!(cc_contact.name.as_deref(), Some("Carol W."));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_recipients_by_message_ids_multiple_messages(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg1 = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;
+ let msg2 = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;
+ let recipients = repo.recipients_by_message_ids(&[msg1, msg2]).await?;
+
+ assert_eq!(recipients.len(), 2, "Both messages should have recipients");
+
+ let msg2_recips = recipients.get(&msg2).expect("msg2 should have recipients");
+ assert_eq!(msg2_recips.len(), 2, "msg2 has TO and BCC recipients");
+
+ // TO comes before BCC in ordering
+ assert_eq!(msg2_recips[0].1, RecipientType::To);
+ assert_eq!(msg2_recips[1].1, RecipientType::Bcc);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_recipients_by_message_ids_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let recipients = repo.recipients_by_message_ids(&[]).await?;
+ assert!(recipients.is_empty());
+
+ Ok(())
+}
+
+// ── labels_by_message_ids ───────────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_labels_by_message_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg1 = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;
+ let labels = repo.labels_by_message_ids(&[msg1]).await?;
+
+ let msg1_labels = labels.get(&msg1).expect("msg1 should have labels");
+ assert_eq!(msg1_labels.len(), 2, "msg1 has INBOX and IMPORTANT");
+
+ // Ordered by label name: IMPORTANT < INBOX
+ assert_eq!(msg1_labels[0].name.as_deref(), Some("IMPORTANT"));
+ assert_eq!(msg1_labels[1].name.as_deref(), Some("INBOX"));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_labels_by_message_ids_multiple_messages(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg1 = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;
+ let msg2 = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;
+ let labels = repo.labels_by_message_ids(&[msg1, msg2]).await?;
+
+ assert_eq!(labels.len(), 2, "Both messages should have labels");
+
+ let msg2_labels = labels.get(&msg2).expect("msg2 should have labels");
+ assert_eq!(msg2_labels.len(), 2, "msg2 has INBOX and Work");
+
+ // Ordered by label name: INBOX < Work
+ assert_eq!(msg2_labels[0].name.as_deref(), Some("INBOX"));
+ assert_eq!(msg2_labels[0].type_, Some(LabelType::System));
+ assert_eq!(msg2_labels[1].name.as_deref(), Some("Work"));
+ assert_eq!(msg2_labels[1].type_, Some(LabelType::User));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_labels_by_message_ids_no_labels(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ // msg3 has no labels
+ let msg3 = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;
+ let labels = repo.labels_by_message_ids(&[msg3]).await?;
+
+ assert!(
+ labels.is_empty(),
+ "Message with no labels should return empty"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_labels_by_message_ids_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let labels = repo.labels_by_message_ids(&[]).await?;
+ assert!(labels.is_empty());
+
+ Ok(())
+}
+
+// ── attachments_by_message_ids ──────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_attachments_by_message_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg1 = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;
+ let attachments = repo.attachments_by_message_ids(&[msg1]).await?;
+
+ let msg1_atts = attachments
+ .get(&msg1)
+ .expect("msg1 should have attachments");
+ assert_eq!(msg1_atts.len(), 2, "msg1 has 2 attachments");
+
+ // Ordered by filename: document.pdf < image.png
+ assert_eq!(msg1_atts[0].filename.as_deref(), Some("document.pdf"));
+ assert_eq!(msg1_atts[0].mime_type.as_deref(), Some("application/pdf"));
+ assert_eq!(msg1_atts[0].size_bytes, Some(102400));
+ // a0000001 has an sfs mapping
+ assert_eq!(
+ msg1_atts[0].sfs_id,
+ Some(Uuid::parse_str("ff000002-0000-0000-0000-000000000002")?)
+ );
+
+ assert_eq!(msg1_atts[1].filename.as_deref(), Some("image.png"));
+ assert_eq!(msg1_atts[1].content_id.as_deref(), Some("cid-inline-1"));
+ // a0000002 has no sfs mapping
+ assert!(msg1_atts[1].sfs_id.is_none());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_attachments_by_message_ids_no_attachments(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg2 = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;
+ let attachments = repo.attachments_by_message_ids(&[msg2]).await?;
+
+ assert!(
+ attachments.is_empty(),
+ "Message without attachments should return empty"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_attachments_by_message_ids_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let attachments = repo.attachments_by_message_ids(&[]).await?;
+ assert!(attachments.is_empty());
+
+ Ok(())
+}
+
+// ── draft_attachments_by_message_ids ────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_draft_attachments_by_message_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg3 = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;
+ let drafts = repo.draft_attachments_by_message_ids(&[msg3]).await?;
+
+ let msg3_drafts = drafts
+ .get(&msg3)
+ .expect("msg3 should have draft attachments");
+ assert_eq!(msg3_drafts.len(), 2, "msg3 has 2 draft attachments");
+
+ // Ordered by file_name ASC: alpha.txt < beta.docx
+ assert_eq!(msg3_drafts[0].file_name, "alpha.txt");
+ assert_eq!(msg3_drafts[0].content_type, "text/plain");
+ assert_eq!(msg3_drafts[0].sha, "sha256-aaa");
+ assert_eq!(msg3_drafts[0].size, 100);
+ assert_eq!(msg3_drafts[0].s3_key, "s3://bucket/alpha.txt");
+ assert_eq!(msg3_drafts[0].draft_id, msg3);
+
+ assert_eq!(msg3_drafts[1].file_name, "beta.docx");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_draft_attachments_by_message_ids_no_drafts(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ // msg1 is not a draft, has no draft attachments
+ let msg1 = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;
+ let drafts = repo.draft_attachments_by_message_ids(&[msg1]).await?;
+
+ assert!(drafts.is_empty());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_draft_attachments_by_message_ids_empty_input(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let drafts = repo.draft_attachments_by_message_ids(&[]).await?;
+ assert!(drafts.is_empty());
+
+ Ok(())
+}
+
+// ── forwarded_attachments_by_message_ids ────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_forwarded_attachments_by_message_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg3 = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;
+ let forwarded = repo.forwarded_attachments_by_message_ids(&[msg3]).await?;
+
+ let msg3_fwd = forwarded
+ .get(&msg3)
+ .expect("msg3 should have forwarded attachments");
+ assert_eq!(msg3_fwd.len(), 1, "msg3 forwards 1 attachment from msg1");
+
+ let fwd = &msg3_fwd[0];
+ assert_eq!(
+ fwd.attachment_id,
+ Uuid::parse_str("aa000001-0000-0000-0000-000000000001")?
+ );
+ assert_eq!(fwd.draft_id, msg3);
+ assert_eq!(fwd.provider_attachment_id.as_deref(), Some("prov-att-1"));
+ // message_provider_id comes from the original message (msg1)
+ assert_eq!(fwd.message_provider_id, "provider-msg-1");
+ assert_eq!(fwd.filename.as_deref(), Some("document.pdf"));
+ assert_eq!(fwd.mime_type.as_deref(), Some("application/pdf"));
+ assert_eq!(fwd.size_bytes, Some(102400));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_forwarded_attachments_by_message_ids_empty_input(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let forwarded = repo.forwarded_attachments_by_message_ids(&[]).await?;
+ assert!(forwarded.is_empty());
+
+ Ok(())
+}
+
+// ── scheduled_send_times_by_message_ids ─────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_scheduled_send_times_by_message_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg3 = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;
+ let times = repo.scheduled_send_times_by_message_ids(&[msg3]).await?;
+
+ assert_eq!(times.len(), 1, "msg3 has a pending scheduled send");
+ let send_time = times.get(&msg3).expect("msg3 should have a send time");
+ assert_eq!(
+ send_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
+ "2025-03-01T09:00:00Z"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_scheduled_send_times_excludes_already_sent(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ // msg2 has a scheduled send but sent=true
+ let msg2 = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;
+ let times = repo.scheduled_send_times_by_message_ids(&[msg2]).await?;
+
+ assert!(
+ times.is_empty(),
+ "Already-sent scheduled messages should be excluded"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_scheduled_send_times_by_message_ids_empty_input(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let times = repo.scheduled_send_times_by_message_ids(&[]).await?;
+ assert!(times.is_empty());
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
new file mode 100644
index 0000000000..982da03ec0
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs
@@ -0,0 +1,21 @@
+mod dynamic_query;
+mod labels;
+mod link;
+mod message;
+mod preview;
+mod thread;
+
+use std::sync::Arc;
+
+use super::*;
+use crate::domain::models::{LabelType, PreviewView, PreviewViewStandardLabel, RecipientType};
+use crate::domain::ports::EmailRepo;
+use filter_ast::Expr;
+use item_filters::ast::email::{Email, EmailLiteral};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::email::EmailStr;
+use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Cursor, CursorVal, Query, SimpleSortMethod};
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/preview.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/preview.rs
new file mode 100644
index 0000000000..4c50544c31
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/preview.rs
@@ -0,0 +1,185 @@
+use super::*;
+
+// ── attachments_by_thread_ids ───────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_attachments_by_thread_ids_single_thread(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread1 = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let attachments = repo.attachments_by_thread_ids(&[thread1]).await?;
+
+ assert_eq!(
+ attachments.len(),
+ 2,
+ "Thread 1 has 2 attachments (both on msg1)"
+ );
+
+ // Ordered by created_at ASC
+ assert_eq!(attachments[0].filename.as_deref(), Some("document.pdf"));
+ assert_eq!(
+ attachments[0].message_id,
+ Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?
+ );
+ assert_eq!(attachments[1].filename.as_deref(), Some("image.png"));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_attachments_by_thread_ids_multiple_threads(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread1 = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let thread3 = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;
+ let attachments = repo.attachments_by_thread_ids(&[thread1, thread3]).await?;
+
+ assert_eq!(
+ attachments.len(),
+ 3,
+ "Thread 1 has 2 attachments, thread 3 has 1"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_attachments_by_thread_ids_no_attachments(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ // Thread 2 only has msg3 (a draft) which has no provider attachments
+ let thread2 = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;
+ let attachments = repo.attachments_by_thread_ids(&[thread2]).await?;
+
+ assert!(
+ attachments.is_empty(),
+ "Thread with no provider attachments should return empty"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_attachments_by_thread_ids_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let attachments = repo.attachments_by_thread_ids(&[]).await?;
+ assert!(attachments.is_empty());
+
+ Ok(())
+}
+
+// ── contacts_by_thread_ids ──────────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_contacts_by_thread_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread1 = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let contacts = repo.contacts_by_thread_ids(&[thread1]).await?;
+
+ // Thread 1 has msg1 (from alice) and msg2 (from bob), ordered by created_at ASC
+ assert_eq!(contacts.len(), 2, "Thread 1 has 2 sender contacts");
+
+ assert_eq!(
+ contacts[0].email_address.as_deref(),
+ );
+ // msg1 has from_name 'Alice S.' which overrides contact.name 'Alice Smith'
+ assert_eq!(contacts[0].name.as_deref(), Some("Alice S."));
+ assert_eq!(
+ contacts[0].sfs_photo_url.as_deref(),
+ Some("https://photos.example.com/alice.jpg")
+ );
+
+ assert_eq!(
+ contacts[1].email_address.as_deref(),
+ );
+ // msg2 has no from_name, so contact.name 'Bob Jones' is used
+ assert_eq!(contacts[1].name.as_deref(), Some("Bob Jones"));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_contacts_by_thread_ids_no_from_contact(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ // Thread 2 only has msg3 which has no from_contact_id
+ let thread2 = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;
+ let contacts = repo.contacts_by_thread_ids(&[thread2]).await?;
+
+ assert!(
+ contacts.is_empty(),
+ "Thread with no sender contacts should return empty"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_contacts_by_thread_ids_multiple_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread1 = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let thread3 = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;
+ let contacts = repo.contacts_by_thread_ids(&[thread1, thread3]).await?;
+
+ // Thread 1: alice + bob, Thread 3: alice (no from_name override)
+ assert_eq!(
+ contacts.len(),
+ 3,
+ "Should have 3 contacts across both threads"
+ );
+
+ // Thread 3's alice should use contact.name since msg4 has no from_name
+ let thread3_contact = &contacts[2];
+ assert_eq!(
+ thread3_contact.email_address.as_deref(),
+ );
+ assert_eq!(
+ thread3_contact.name.as_deref(),
+ Some("Alice Smith"),
+ "msg4 has no from_name, should use contact.name"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn test_contacts_by_thread_ids_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let contacts = repo.contacts_by_thread_ids(&[]).await?;
+ assert!(contacts.is_empty());
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rs
new file mode 100644
index 0000000000..b802aa66ac
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rs
@@ -0,0 +1,197 @@
+use super::*;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread"))
+)]
+async fn test_thread_by_id_exists(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let thread = repo.thread_by_id(thread_id).await?;
+
+ assert!(thread.is_some(), "Thread should exist");
+ let thread = thread.unwrap();
+ assert_eq!(thread.db_id, thread_id);
+ assert_eq!(thread.provider_id.as_deref(), Some("provider-thread-1"));
+ assert_eq!(
+ thread.link_id,
+ Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?
+ );
+ assert!(thread.inbox_visible);
+ assert!(!thread.is_read);
+ assert!(thread.latest_inbound_message_ts.is_some());
+ assert!(thread.latest_outbound_message_ts.is_some());
+ assert!(thread.latest_non_spam_message_ts.is_some());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread"))
+)]
+async fn test_thread_by_id_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_id = Uuid::parse_str("99999999-9999-9999-9999-999999999999")?;
+ let thread = repo.thread_by_id(thread_id).await?;
+
+ assert!(thread.is_none(), "Non-existent thread should return None");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread"))
+)]
+async fn test_thread_by_id_nullable_timestamps(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;
+ let thread = repo.thread_by_id(thread_id).await?.unwrap();
+
+ assert!(!thread.inbox_visible);
+ assert!(thread.is_read);
+ assert!(thread.latest_inbound_message_ts.is_some());
+ assert!(
+ thread.latest_outbound_message_ts.is_none(),
+ "Thread 2 has no outbound timestamp"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread"))
+)]
+async fn test_messages_by_thread_id_paginated_returns_all(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let messages = repo
+ .messages_by_thread_id_paginated(thread_id, 0, 50)
+ .await?;
+
+ assert_eq!(messages.len(), 3, "Thread 1 should have 3 messages");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread"))
+)]
+async fn test_messages_by_thread_id_paginated_ordered_by_date_desc(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let messages = repo
+ .messages_by_thread_id_paginated(thread_id, 0, 50)
+ .await?;
+
+ assert_eq!(messages.len(), 3);
+ assert_eq!(
+ messages[0].provider_id.as_deref(),
+ Some("msg-1-newest"),
+ "First message should be newest"
+ );
+ assert_eq!(
+ messages[1].provider_id.as_deref(),
+ Some("msg-1-middle"),
+ "Second message should be middle"
+ );
+ assert_eq!(
+ messages[2].provider_id.as_deref(),
+ Some("msg-1-oldest"),
+ "Third message should be oldest"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread"))
+)]
+async fn test_messages_by_thread_id_paginated_with_offset_and_limit(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+
+ // Get first page (limit 2)
+ let page1 = repo
+ .messages_by_thread_id_paginated(thread_id, 0, 2)
+ .await?;
+ assert_eq!(page1.len(), 2, "First page should have 2 messages");
+ assert_eq!(page1[0].provider_id.as_deref(), Some("msg-1-newest"));
+ assert_eq!(page1[1].provider_id.as_deref(), Some("msg-1-middle"));
+
+ // Get second page (offset 2, limit 2)
+ let page2 = repo
+ .messages_by_thread_id_paginated(thread_id, 2, 2)
+ .await?;
+ assert_eq!(page2.len(), 1, "Second page should have 1 message");
+ assert_eq!(page2[0].provider_id.as_deref(), Some("msg-1-oldest"));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread"))
+)]
+async fn test_messages_by_thread_id_paginated_empty_thread(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_id = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;
+ let messages = repo
+ .messages_by_thread_id_paginated(thread_id, 0, 50)
+ .await?;
+
+ assert_eq!(messages.len(), 0, "Empty thread should return no messages");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread"))
+)]
+async fn test_messages_by_thread_id_paginated_fields_populated(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let messages = repo
+ .messages_by_thread_id_paginated(thread_id, 0, 50)
+ .await?;
+
+ // Check the newest message has expected fields
+ let newest = &messages[0];
+ assert_eq!(newest.provider_id.as_deref(), Some("msg-1-newest"));
+ assert_eq!(newest.subject.as_deref(), Some("Re: Re: Hello"));
+ assert_eq!(newest.snippet.as_deref(), Some("Latest reply"));
+ assert!(!newest.is_read);
+ assert!(!newest.is_sent);
+ assert!(!newest.is_draft);
+ assert!(newest.has_attachments);
+
+ // Check the middle message
+ let middle = &messages[1];
+ assert!(middle.is_read);
+ assert!(middle.is_sent);
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs
new file mode 100644
index 0000000000..7b7197e0d2
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs
@@ -0,0 +1,58 @@
+use crate::domain::models::{MessageRow, ThreadRow};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::db_types::{DbMessageRow, DbThreadRow};
+
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn thread_by_id(
+ pool: &PgPool,
+ thread_id: Uuid,
+) -> Result<Option<ThreadRow>, sqlx::Error> {
+ let row = sqlx::query_as!(
+ DbThreadRow,
+ r#"
+ SELECT t.id, t.provider_id, t.link_id, t.inbox_visible, t.is_read,
+ t.latest_inbound_message_ts, t.latest_outbound_message_ts,
+ t.latest_non_spam_message_ts, t.created_at, t.updated_at
+ FROM email_threads t
+ WHERE t.id = $1
+ "#,
+ thread_id,
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ Ok(row.map(ThreadRow::from))
+}
+
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn messages_by_thread_id_paginated(
+ pool: &PgPool,
+ thread_id: Uuid,
+ offset: i64,
+ limit: i64,
+) -> Result<Vec<MessageRow>, sqlx::Error> {
+ let rows = sqlx::query_as!(
+ DbMessageRow,
+ r#"
+ SELECT
+ id, provider_id, thread_id, provider_thread_id, replying_to_id,
+ global_id, link_id, provider_history_id, internal_date_ts, snippet,
+ size_estimate, subject, sent_at, has_attachments, is_read, is_starred,
+ is_sent, is_draft, body_text, body_html_sanitized, body_macro,
+ headers_jsonb, created_at, updated_at
+ FROM email_messages
+ WHERE thread_id = $1
+ ORDER BY internal_date_ts DESC
+ LIMIT $2 OFFSET $3
+ "#,
+ thread_id,
+ limit,
+ offset,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows.into_iter().map(MessageRow::from).collect())
+}
diff --git a/rust/cloud-storage/email_db_client/src/messages/get.rs b/rust/cloud-storage/email_db_client/src/messages/get.rs
index ebfb4dbd45..4fd0548a7d 100644
--- a/rust/cloud-storage/email_db_client/src/messages/get.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/get.rs
@@ -409,59 +409,6 @@ pub async fn draft_exists_with_id(
Ok(exists)
}
-/// Fetches messages for a thread with pagination
-#[tracing::instrument(skip(pool), err)]
-pub async fn get_messages_by_thread_id(
- pool: &PgPool,
- thread_db_id: Uuid,
- offset: i64,
- limit: i64,
-) -> anyhow::Result<Vec<db::message::Message>> {
- let db_messages = sqlx::query_as!(
- db::message::Message,
- r#"
- SELECT
- id,
- provider_id,
- global_id,
- thread_id,
- provider_thread_id,
- replying_to_id,
- link_id,
- provider_history_id,
- internal_date_ts,
- snippet,
- size_estimate,
- subject,
- from_name,
- from_contact_id,
- sent_at,
- has_attachments,
- is_read,
- is_starred,
- is_sent,
- is_draft,
- body_text,
- body_html_sanitized,
- body_macro,
- headers_jsonb,
- created_at,
- updated_at
- FROM email_messages
- WHERE thread_id = $1
- ORDER BY internal_date_ts DESC
- LIMIT $2 OFFSET $3
- "#,
- thread_db_id,
- limit,
- offset
- )
- .fetch_all(pool)
- .await?;
-
- Ok(db_messages)
-}
-
/// Converts a list of db messages to service messages by fetching ALL associated data
/// in bulk (one query per data type for all messages), then mapping results back.
pub async fn convert_db_messages_to_service_concurrent(
diff --git a/rust/cloud-storage/email_db_client/src/threads/get.rs b/rust/cloud-storage/email_db_client/src/threads/get.rs
index c662a64aef..1c5ccbc37e 100644
--- a/rust/cloud-storage/email_db_client/src/threads/get.rs
+++ b/rust/cloud-storage/email_db_client/src/threads/get.rs
@@ -1,11 +1,9 @@
-use crate::messages::get::{convert_db_messages_to_service_concurrent, get_messages_by_thread_id};
use crate::parse::db_to_service;
use anyhow::anyhow;
-use models_email::email::db;
-use models_email::email::service::thread;
use models_email::email::service::thread::{
ThreadProviderMap, ThreadUserInfo, UserThreadIds, UserThreadsPage,
};
+use models_email::{db, service};
use sqlx::PgPool;
use sqlx::types::Uuid;
use std::collections::{HashMap, HashSet};
@@ -35,45 +33,6 @@ pub async fn get_paginated_thread_ids_with_macro_user_id(
Ok(result)
}
-/// fetch thread with number of most recent messages specified by limit and offset
-#[tracing::instrument(skip(pool), err)]
-pub async fn fetch_thread_with_messages_paginated(
- pool: &PgPool,
- thread_db_id: Uuid,
- offset: i64,
- limit: i64,
-) -> anyhow::Result<Option<thread::Thread>> {
- if offset < 0 || limit <= 0 {
- anyhow::bail!("Offset must be non-negative and limit must be positive");
- }
-
- let db_thread = sqlx::query_as!(
- db::thread::Thread,
- r#"
- SELECT t.id, t.provider_id, t.link_id, t.inbox_visible, t.is_read,
- t.latest_inbound_message_ts, t.latest_outbound_message_ts,
- t.latest_non_spam_message_ts, t.created_at, t.updated_at
- FROM email_threads t
- WHERE t.id = $1
- "#,
- thread_db_id,
- )
- .fetch_optional(pool)
- .await?;
-
- let Some(db_thread) = db_thread else {
- return Ok(None);
- };
-
- let db_messages = get_messages_by_thread_id(pool, thread_db_id, offset, limit).await?;
-
- let processed_messages = convert_db_messages_to_service_concurrent(pool, db_messages).await?;
-
- let full_thread = db_to_service::map_db_thread_to_service(db_thread, processed_messages);
-
- Ok(Some(full_thread))
-}
-
/// get the ids of the latest-updated threads for the user.
#[tracing::instrument(skip(pool), err)]
pub async fn get_latest_thread_ids_paginated(
@@ -295,7 +254,7 @@ pub async fn get_thread_by_id_and_link_id(
pool: &PgPool,
thread_id: Uuid,
link_id: Uuid,
-) -> anyhow::Result<Option<thread::Thread>> {
+) -> anyhow::Result<Option<service::thread::Thread>> {
// Fetch the thread record
let db_thread = sqlx::query_as!(
db::thread::Thread,
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index a76f4f3dc4..7d8bc12b06 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -82,6 +82,7 @@ document_storage_service_client = { path = "../document_storage_service_client"
doppleganger = { workspace = true }
ego-tree = { workspace = true }
email = { path = "../email", features = ["axum", "inbound", "outbound"] }
+entity_access = { path = "../entity_access", default-features = false, features = ["outbound"] }
email_db_client = { path = "../email_db_client" }
email_utils = { path = "../email_utils" }
frecency = { path = "../frecency", features = ["postgres"] }
diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rs
index 5f1e3ee016..6741a1de0a 100644
--- a/rust/cloud-storage/email_service/src/api/context.rs
+++ b/rust/cloud-storage/email_service/src/api/context.rs
@@ -1,8 +1,13 @@
use axum::extract::FromRef;
use document_storage_service_client::DocumentStorageServiceClient;
-use email::{domain::service::EmailServiceImpl, inbound::EmailPreviewState, outbound::EmailPgRepo};
+use email::{
+ domain::service::EmailServiceImpl,
+ inbound::{EmailPreviewState, EmailThreadRouterState},
+ outbound::EmailPgRepo,
+};
use email_service::config::Config;
use email_service::util::redis::RedisClient;
+use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
@@ -11,6 +16,9 @@ use static_file_service_client::StaticFileServiceClient;
use std::sync::Arc;
use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};
+pub(crate) type EmailEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
+type EmailSvc = EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>;
+
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
pub db: sqlx::Pool<sqlx::Postgres>,
@@ -25,7 +33,7 @@ pub(crate) struct ApiContext {
pub jwt_args: JwtValidationArgs,
pub config: Arc<Config>,
pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,
- pub email_service: EmailPreviewState<
- EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,
- >,
+ pub email_service: EmailPreviewState<EmailSvc>,
+ pub entity_access_service: Arc<EmailEntityAccessService>,
+ pub email_thread_state: EmailThreadRouterState<EmailSvc, EmailEntityAccessService>,
}
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/get.rs b/rust/cloud-storage/email_service/src/api/email/threads/get.rs
index 3086b66b8d..8cf5e7d75b 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/get.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/get.rs
@@ -4,16 +4,9 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json, extract};
-use email::domain::ports::EmailService;
-use email::inbound::OptionalEmailLinkExtractor;
-use futures::future::join_all;
use model::response::ErrorResponse;
use model::user::UserContext;
-use models_email::email::service::thread;
use models_email::service::link::Link;
-use models_email::service::message::MessageWithBodyReplyless;
-use models_email::service::thread::APIThread;
-use models_permissions::share_permission::access_level::AccessLevel;
use sqlx::types::Uuid;
use strum_macros::AsRefStr;
use thiserror::Error;
@@ -21,9 +14,6 @@ use utoipa::ToSchema;
#[derive(Debug, Error, AsRefStr)]
pub enum GetThreadError {
- #[error("Thread not found")]
- ThreadNotFound,
-
#[error("Unable to get messages")]
DatabaseError(#[from] anyhow::Error),
@@ -37,29 +27,9 @@ pub enum GetThreadError {
ValidationError(String),
}
-impl GetThreadError {
- /// Returns true if this error should be logged
- fn should_log(&self) -> bool {
- !matches!(
- self,
- GetThreadError::ThreadNotFound
- | GetThreadError::Unauthorized
- | GetThreadError::ValidationError(_)
- )
- }
-
- /// Log the error if appropriate
- fn log_if_needed(&self) {
- if self.should_log() {
- tracing::error!(error = ?self, variant = self.as_ref(), "GetThreadError");
- }
- }
-}
-
impl IntoResponse for GetThreadError {
fn into_response(self) -> Response {
let status_code = match &self {
- GetThreadError::ThreadNotFound => StatusCode::NOT_FOUND,
GetThreadError::Unauthorized => StatusCode::UNAUTHORIZED,
GetThreadError::ValidationError(_) => StatusCode::BAD_REQUEST,
GetThreadError::DatabaseError(_) | GetThreadError::QueryError(_) => {
@@ -79,18 +49,11 @@ impl IntoResponse for GetThreadError {
/// Parameters for getting messages. The number of messages is paginated, returning the latest updated first.
#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
-pub struct GetThreadParams {
+pub struct GetThreadMessagesParams {
pub offset: Option<i64>,
pub limit: Option<i64>,
}
-/// The response returned from the get thread endpoint
-#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
-pub struct GetThreadResponse {
- /// the thread, with messages inside
- pub thread: thread::APIThread,
-}
-
/// Represents pagination parameters with defaults applied
#[derive(Debug, Clone, Copy)]
struct GetThreadPaginationParams {
@@ -108,103 +71,6 @@ const DEFAULT_MESSAGE_LIMIT: i64 = 5;
/// The max number of messages that can be returned in a response
const MESSAGE_MAX: i64 = 100;
-/// Get a thread with a paginated number of messages.
-#[utoipa::path(
- get,
- tag = "Threads",
- path = "/email/threads/{id}",
- operation_id = "get_thread",
- params(
- ("id" = Uuid, Path, description = "Thread ID."),
- ("offset" = i64, Query, description = "Offset for message pagination. Default is 0."),
- ("limit" = i64, Query, description = "Limit for message pagination. Default is 5."),
- ),
-
-
- responses(
- (status = 200, body=GetThreadResponse),
- (status = 400, body=ErrorResponse),
- (status = 401, body=ErrorResponse),
- (status = 404, body=ErrorResponse),
- (status = 500, body=ErrorResponse),
- )
-)]
-#[tracing::instrument(skip(ctx, user_context, link), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
-pub async fn get_thread_handler<U: EmailService>(
- State(ctx): State<ApiContext>,
- user_context: Extension<UserContext>,
- link: OptionalEmailLinkExtractor<U>,
- Path(PathParams { id: thread_id }): Path<PathParams>,
- extract::Query(query_params): extract::Query<GetThreadParams>,
-) -> Result<Response, GetThreadError> {
- get_thread_handler_inner(ctx, user_context, link, thread_id, query_params)
- .await
- .inspect_err(|e| e.log_if_needed())
-}
-
-async fn get_thread_handler_inner<U: EmailService>(
- ctx: ApiContext,
- user_context: Extension<UserContext>,
- link: OptionalEmailLinkExtractor<U>,
- thread_id: Uuid,
- query_params: GetThreadParams,
-) -> Result<Response, GetThreadError> {
- let link = link.0;
- let p = process_get_thread_params(&query_params)?;
-
- let mut thread = email_db_client::threads::get::fetch_thread_with_messages_paginated(
- &ctx.db, thread_id, p.offset, p.limit,
- )
- .await
- .context("Failed to fetch thread with messages")?
- .ok_or(GetThreadError::ThreadNotFound)?;
-
- // Check if user owns the thread via their link
- let is_owner = link
- .as_ref()
- .map(|l| thread.link_id == l.id)
- .unwrap_or(false);
-
- let access_level = if is_owner {
- AccessLevel::Owner
- } else {
- // If user doesn't have email enabled (and thus has no link), use user_context's macro_id
- let macro_id = link
- .as_ref()
- .map(|l| l.macro_id.as_ref())
- .unwrap_or(&user_context.user_id);
-
- let access_level = ctx
- .dss_client
- .get_thread_access_level(macro_id, &thread.db_id.to_string())
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get access level for thread for user");
- GetThreadError::ThreadNotFound
- })?;
- // don't include the owner's drafts if it's a shared thread
- thread.messages.retain(|m| !m.is_draft);
- access_level
- };
-
- let tasks: Vec<_> = thread
- .clone()
- .messages
- .into_iter()
- .map(|message| async move { MessageWithBodyReplyless::from(message) })
- .collect();
-
- let result: Vec<MessageWithBodyReplyless> = join_all(tasks).await;
-
- let api_thread = APIThread::from_thread_with_messages(thread, result, access_level);
-
- Ok((
- StatusCode::OK,
- Json(GetThreadResponse { thread: api_thread }),
- )
- .into_response())
-}
-
// TODO: deduplicate with internal api
#[utoipa::path(
get,
@@ -229,7 +95,7 @@ pub async fn get_thread_messages_handler(
user_context: Extension<UserContext>,
link: Extension<Link>,
Path(PathParams { id }): Path<PathParams>,
- extract::Query(query_params): extract::Query<GetThreadParams>,
+ extract::Query(query_params): extract::Query<GetThreadMessagesParams>,
) -> Result<Response, GetThreadError> {
let p = process_get_thread_params(&query_params)?;
@@ -254,7 +120,7 @@ pub async fn get_thread_messages_handler(
/// Extracts pagination parameters from query params, using defaults when not specified
fn process_get_thread_params(
- params: &GetThreadParams,
+ params: &GetThreadMessagesParams,
) -> Result<GetThreadPaginationParams, GetThreadError> {
if let Some(offset) = params.offset
&& offset < 0
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
index 0b96a0c197..6cd74c8033 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
@@ -44,10 +44,9 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
crate::api::middleware::link::attach_link_context,
));
- // user can still view threads shared with them if they don't have email enabled
- let optional_link_routes = Router::new().route("/:id", get(get::get_thread_handler));
+ let hex_thread_routes = email::inbound::thread_router(state.email_thread_state.clone());
Router::new()
.merge(required_link_routes)
- .merge(optional_link_routes)
+ .merge(hex_thread_routes)
}
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index df2fb99680..da22a074c2 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -19,11 +19,12 @@ use crate::api::email::messages::labels::{UpdateLabelBatchRequest, UpdateLabelBa
use crate::api::email::messages::send::{SendMessageRequest, SendMessageResponse};
use crate::api::email::settings::patch::{PatchSettingsRequest, PatchSettingsResponse};
use crate::api::email::threads::archived::ArchiveThreadRequest;
-use crate::api::email::threads::get::GetThreadResponse;
use crate::api::email::threads::labels::UpdateThreadLabelRequest;
use crate::api::{email, health};
use ::email::inbound;
-use ::email::inbound::{ApiPaginatedThreadCursor, ApiSortMethod, GetPreviewsCursorParams};
+use ::email::inbound::{
+ ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, GetPreviewsCursorParams, GetThreadResponse,
+};
use model::response::EmptyResponse;
use models_email::api::settings::Settings;
use models_email::email::service;
@@ -33,7 +34,7 @@ use models_email::email::service::link::Link;
use models_email::email::service::thread::{PreviewView, PreviewViewStandardLabel};
use models_email::service::label::Label;
use models_email::service::message::{MessageToSend, ParsedMessage};
-use models_email::service::thread::{APIThread, ThreadPreviewCursor};
+use models_email::service::thread::ThreadPreviewCursor;
use utoipa::OpenApi;
#[derive(OpenApi)]
@@ -63,11 +64,11 @@ use utoipa::OpenApi;
email::messages::labels::handler,
email::messages::send::send_handler,
email::threads::seen::seen_handler,
- email::threads::get::get_thread_handler,
email::threads::get::get_thread_messages_handler,
email::threads::archived::archived_handler,
email::threads::labels::handler,
inbound::cursor_handler,
+ inbound::get_thread_handler,
email::links::list::list_links_handler,
email::labels::create::handler,
email::labels::delete::handler,
@@ -106,11 +107,11 @@ use utoipa::OpenApi;
ParsedMessage,
MessageToSend,
// Thread types
- GetThreadResponse,
ArchiveThreadRequest,
UpdateThreadLabelRequest,
- APIThread,
ThreadPreviewCursor,
+ GetThreadResponse,
+ ApiThread,
// Preview types
GetPreviewsCursorParams,
ApiPaginatedThreadCursor,
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index 636424a953..89d6b2372e 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -1,8 +1,13 @@
use crate::api::context::ApiContext;
use anyhow::Context;
use document_storage_service_client::DocumentStorageServiceClient;
-use email::{domain::service::EmailServiceImpl, inbound::EmailPreviewState, outbound::EmailPgRepo};
+use email::{
+ domain::service::EmailServiceImpl,
+ inbound::{EmailPreviewState, EmailThreadRouterState},
+ outbound::EmailPgRepo,
+};
use email_service::config::EmailServiceCloudfrontSignerPrivateKey;
+use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
@@ -120,8 +125,20 @@ async fn main() -> anyhow::Result<()> {
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
.await?;
+ let email_service = EmailPreviewState::new(EmailServiceImpl::new(
+ EmailPgRepo::new(db.clone()),
+ FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
+ ));
+ let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
+ db.clone(),
+ )));
+ let email_thread_state = EmailThreadRouterState {
+ service: email_service.service(),
+ access_service: entity_access_service.clone(),
+ };
+
api::setup_and_serve(ApiContext {
- db: db.clone(),
+ db,
config: Arc::new(config),
auth_service_client: Arc::new(auth_service_client),
redis_client: Arc::new(redis_client),
@@ -133,10 +150,9 @@ async fn main() -> anyhow::Result<()> {
system_properties_service,
jwt_args,
internal_auth_key: LocalOrRemoteSecret::Local(internal_auth_key),
- email_service: EmailPreviewState::new(EmailServiceImpl::new(
- EmailPgRepo::new(db.clone()),
- FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db)),
- )),
+ email_service,
+ entity_access_service,
+ email_thread_state,
})
.await?;
Ok(())
diff --git a/rust/cloud-storage/email_utils/Cargo.toml b/rust/cloud-storage/email_utils/Cargo.toml
index f87982ea18..2833e8195a 100644
--- a/rust/cloud-storage/email_utils/Cargo.toml
+++ b/rust/cloud-storage/email_utils/Cargo.toml
@@ -5,5 +5,7 @@ publish = false
edition = "2024"
[dependencies]
+ego-tree = { workspace = true }
lazy_static = { workspace = true }
-regex = { workspace = true }
\ No newline at end of file
+regex = { workspace = true }
+scraper = { workspace = true }
\ No newline at end of file
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/constants.rs b/rust/cloud-storage/email_utils/src/body_replyless/constants.rs
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/constants.rs
rename to rust/cloud-storage/email_utils/src/body_replyless/constants.rs
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/html_parser.rs b/rust/cloud-storage/email_utils/src/body_replyless/html_parser.rs
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/html_parser.rs
rename to rust/cloud-storage/email_utils/src/body_replyless/html_parser.rs
diff --git a/rust/cloud-storage/email_utils/src/body_replyless/mod.rs b/rust/cloud-storage/email_utils/src/body_replyless/mod.rs
new file mode 100644
index 0000000000..7d7b40a114
--- /dev/null
+++ b/rust/cloud-storage/email_utils/src/body_replyless/mod.rs
@@ -0,0 +1,23 @@
+mod constants;
+mod html_parser;
+mod plaintext_parser;
+#[cfg(test)]
+mod test;
+
+use html_parser::extract_reply_html;
+use plaintext_parser::extract_reply_plaintext;
+
+/// Computes the body of a message with reply/forwarded-thread content stripped.
+///
+/// Returns `None` if the message has neither HTML nor plaintext body content.
+pub fn compute_body_replyless(
+ subject: Option<&str>,
+ body_html_sanitized: Option<&str>,
+ body_text: Option<&str>,
+) -> Option<String> {
+ if let Some(sanitized) = body_html_sanitized {
+ Some(extract_reply_html(subject, sanitized))
+ } else {
+ body_text.map(|body| extract_reply_plaintext(subject, body))
+ }
+}
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/plaintext_parser.rs b/rust/cloud-storage/email_utils/src/body_replyless/plaintext_parser.rs
similarity index 87%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/plaintext_parser.rs
rename to rust/cloud-storage/email_utils/src/body_replyless/plaintext_parser.rs
index 14b6c43c72..9147dedaf6 100644
--- a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/plaintext_parser.rs
+++ b/rust/cloud-storage/email_utils/src/body_replyless/plaintext_parser.rs
@@ -1,4 +1,4 @@
-use crate::service::body_parsing::body_replyless::constants::PLAINTEXT_SPLITTER_RE;
+use super::constants::PLAINTEXT_SPLITTER_RE;
/// Extracts the latest reply from a plaintext email string.
pub fn extract_reply_plaintext(subject: Option<&str>, text_content: &str) -> String {
diff --git a/rust/cloud-storage/email_utils/src/body_replyless/test.rs b/rust/cloud-storage/email_utils/src/body_replyless/test.rs
new file mode 100644
index 0000000000..81b5fa3f31
--- /dev/null
+++ b/rust/cloud-storage/email_utils/src/body_replyless/test.rs
@@ -0,0 +1,75 @@
+use super::compute_body_replyless;
+
+#[test]
+fn test_extract_message_reply_outlook_test_1() {
+ let full_email = include_str!("testdata/outlook-test-1/full.html");
+ let expected_reply = include_str!("testdata/outlook-test-1/body_replyless.html");
+
+ test_email_extraction(full_email, expected_reply, "outlook-test-1");
+}
+
+#[test]
+fn test_extract_message_reply_outlook_test_2() {
+ let full_email = include_str!("testdata/outlook-test-2/full.html");
+ let expected_reply = include_str!("testdata/outlook-test-2/body_replyless.html");
+
+ test_email_extraction(full_email, expected_reply, "outlook-test-2");
+}
+
+#[test]
+fn test_extract_message_reply_test_1() {
+ let full_email = include_str!("testdata/test-1/full.html");
+ let expected_reply = include_str!("testdata/test-1/body_replyless.html");
+
+ test_email_extraction(full_email, expected_reply, "test-1");
+}
+
+#[test]
+fn test_extract_message_reply_test_2() {
+ let full_email = include_str!("testdata/test-2/full.html");
+ let expected_reply = include_str!("testdata/test-2/body_replyless.html");
+
+ test_email_extraction(full_email, expected_reply, "test-2");
+}
+
+#[test]
+fn test_extract_message_reply_test_3() {
+ let full_email = include_str!("testdata/test-3/full.html");
+ let expected_reply = include_str!("testdata/test-3/body_replyless.html");
+
+ test_email_extraction(full_email, expected_reply, "test-3");
+}
+
+/// gmail selectors WITHOUT a gmail_attr div within them should not be split off
+#[test]
+fn test_extract_message_reply_test_4() {
+ let full_email = include_str!("testdata/test-4/full.html");
+ let expected_reply = include_str!("testdata/test-4/body_replyless.html");
+
+ test_email_extraction(full_email, expected_reply, "test-4");
+}
+
+/// the entire email (including style tags before the body) should be used if no splitter
+/// is found on the email
+#[test]
+fn test_extract_message_reply_test_5() {
+ let full_email = include_str!("testdata/test-5/full.html");
+ let expected_reply = include_str!("testdata/test-5/body_replyless.html");
+
+ test_email_extraction(full_email, expected_reply, "test-5");
+}
+
+fn test_email_extraction(full_email: &str, expected_reply: &str, test_name: &str) {
+ let body_replyless = compute_body_replyless(None, Some(full_email), None);
+
+ assert_eq!(
+ body_replyless
+ .unwrap()
+ .replace(" ", "")
+ .replace("\n", "")
+ .trim(),
+ expected_reply.replace(" ", "").replace("\n", "").trim(),
+ "Test '{}' failed: extracted reply doesn't match expected",
+ test_name
+ );
+}
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/outlook-test-1/body_replyless.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/outlook-test-1/body_replyless.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/outlook-test-1/body_replyless.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/outlook-test-1/body_replyless.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/outlook-test-1/full.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/outlook-test-1/full.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/outlook-test-1/full.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/outlook-test-1/full.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/outlook-test-2/body_replyless.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/outlook-test-2/body_replyless.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/outlook-test-2/body_replyless.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/outlook-test-2/body_replyless.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/outlook-test-2/full.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/outlook-test-2/full.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/outlook-test-2/full.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/outlook-test-2/full.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-1/body_replyless.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-1/body_replyless.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-1/body_replyless.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-1/body_replyless.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-1/full.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-1/full.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-1/full.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-1/full.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-2/body_replyless.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-2/body_replyless.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-2/body_replyless.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-2/body_replyless.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-2/full.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-2/full.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-2/full.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-2/full.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-3/body_replyless.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-3/body_replyless.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-3/body_replyless.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-3/body_replyless.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-3/full.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-3/full.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-3/full.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-3/full.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-4/body_replyless.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-4/body_replyless.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-4/body_replyless.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-4/body_replyless.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-4/full.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-4/full.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-4/full.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-4/full.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-5/body_replyless.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-5/body_replyless.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-5/body_replyless.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-5/body_replyless.html
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-5/full.html b/rust/cloud-storage/email_utils/src/body_replyless/testdata/test-5/full.html
similarity index 100%
rename from rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/testdata/test-5/full.html
rename to rust/cloud-storage/email_utils/src/body_replyless/testdata/test-5/full.html
diff --git a/rust/cloud-storage/email_utils/src/generic_email/mod.rs b/rust/cloud-storage/email_utils/src/generic_email/mod.rs
new file mode 100644
index 0000000000..f21240e858
--- /dev/null
+++ b/rust/cloud-storage/email_utils/src/generic_email/mod.rs
@@ -0,0 +1,337 @@
+use lazy_static::lazy_static;
+use regex::Regex;
+
+#[cfg(test)]
+mod test;
+
+lazy_static! {
+ static ref HEX_PATTERN: Regex = Regex::new(r"^[a-f0-9\-]{20,}$").unwrap();
+ static ref UUID_PATTERN: Regex =
+ Regex::new(r"^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$").unwrap();
+}
+
+/// Checks if an email address is likely a generic/automated system email
+///
+/// This function identifies common patterns in email addresses that typically
+/// indicate automated senders rather than individual users.
+pub fn is_generic_email(email: &str) -> bool {
+ let email_lower = email.to_lowercase();
+
+ // Split into local part and domain
+ let (local_part, domain) = match email_lower.split_once('@') {
+ Some(parts) => parts,
+ None => return false, // Invalid email
+ };
+
+ // Check for automated email service domains first (most definitive)
+ if is_automated_domain(domain) {
+ return true;
+ }
+
+ // Check for obvious automated patterns in local part
+ if contains_automated_keyword(local_part) {
+ return true;
+ }
+
+ // Check if local part starts with automated prefix
+ if starts_with_automated_prefix(local_part) {
+ return true;
+ }
+
+ // Check for auto-generated local parts (numbers, UUIDs, hex strings)
+ if is_autogenerated_local_part(local_part) {
+ return true;
+ }
+
+ false
+}
+
+fn is_automated_domain(domain: &str) -> bool {
+ const SYSTEM_DOMAINS: &[&str] = &[
+ // Email service providers
+ "sendgrid.net",
+ "sendgrid.com",
+ "mailchimp.com",
+ "amazonses.com",
+ "email.amazonses.com",
+ "bounce.amazonses.com",
+ "sparkpost.com",
+ "mailgun.org",
+ "mg.mailgun.org",
+ "em.mailgun.org",
+ "mailjet.com",
+ "mandrillapp.com",
+ "postmarkapp.com",
+ "sendinblue.com",
+ "klaviyo.com",
+ "constantcontact.com",
+ // CRM/Marketing platforms
+ "salesforce.com",
+ "salesforceiq.com",
+ "hubspot.com",
+ "marketo.com",
+ "intercom.io",
+ "intercom-mail.com",
+ "campaign-archive.com",
+ // Support platforms
+ "zendesk.com",
+ "freshdesk.com",
+ // Google
+ "notifications.google.com",
+ ];
+
+ SYSTEM_DOMAINS
+ .iter()
+ .any(|d| domain == *d || domain.ends_with(&format!(".{}", d)))
+}
+
+fn contains_automated_keyword(local_part: &str) -> bool {
+ // Keywords that strongly indicate automation when present anywhere
+ const STRONG_KEYWORDS: &[&str] = &[
+ "noreply",
+ "no-reply",
+ "no.reply",
+ "no_reply",
+ "donotreply",
+ "do-not-reply",
+ "do.not.reply",
+ "do_not_reply",
+ "unsubscribe",
+ "unsub",
+ "automated",
+ "mailer-daemon",
+ "postmaster",
+ ];
+
+ STRONG_KEYWORDS.iter().any(|kw| local_part.contains(kw))
+}
+
+fn starts_with_automated_prefix(local_part: &str) -> bool {
+ const AUTOMATED_PREFIXES: &[&str] = &[
+ // Reply/No-reply variants
+ "reply",
+ "noreply",
+ "no-reply",
+ "no.reply",
+ "no_reply",
+ "donotreply",
+ "do-not-reply",
+ "do.not.reply",
+ "do_not_reply",
+ // System/Auto
+ "auto",
+ "automated",
+ "system",
+ "daemon",
+ "cron",
+ "scheduler",
+ "robot",
+ "bot",
+ // Notifications/Alerts
+ "alert",
+ "alerts",
+ "notification",
+ "notifications",
+ "notify",
+ "digest",
+ "bulletin",
+ "announcements",
+ "weekly",
+ "daily",
+ "monthly",
+ // Support/Service
+ "support",
+ "help",
+ "helpdesk",
+ "service",
+ "services",
+ "customercare",
+ "customer-care",
+ "customer.care",
+ "customerservice",
+ "customer-service",
+ "customer.service",
+ // Admin/System
+ "admin",
+ "administrator",
+ "webmaster",
+ "postmaster",
+ "sysadmin",
+ "root",
+ "ops",
+ "devops",
+ "monitor",
+ "monitoring",
+ "status",
+ "logs",
+ "error",
+ "errors",
+ // Accounts/Auth
+ "account",
+ "accounts",
+ "auth",
+ "authentication",
+ "login",
+ "signin",
+ "password",
+ "reset",
+ "otp",
+ "2fa",
+ "mfa",
+ "token",
+ "verify",
+ "verification",
+ "confirm",
+ "confirmation",
+ "security",
+ "secure",
+ // Billing/Transactions
+ "billing",
+ "invoice",
+ "invoices",
+ "payment",
+ "payments",
+ "transaction",
+ "transactions",
+ "refund",
+ "subscription",
+ "subscriptions",
+ "renewal",
+ "receipt",
+ "receipts",
+ "order",
+ "orders",
+ // Shipping/Delivery
+ "shipping",
+ "delivery",
+ "track",
+ "tracking",
+ "booking",
+ "bookings",
+ "reservations",
+ // Marketing/Comms
+ "marketing",
+ "promo",
+ "promotions",
+ "offers",
+ "deals",
+ "news",
+ "newsletter",
+ "updates",
+ "info",
+ "information",
+ "feedback",
+ "survey",
+ // Business departments
+ "sales",
+ "hr",
+ "legal",
+ "finance",
+ "press",
+ "media",
+ "partnerships",
+ "partners",
+ "affiliates",
+ "careers",
+ "jobs",
+ "applications",
+ "events",
+ // Dev/API
+ "dev",
+ "developer",
+ "api",
+ "test",
+ "testing",
+ "mailer",
+ "mail",
+ "bounce",
+ "bounces",
+ // Generic contact
+ "contact",
+ "team",
+ "hello",
+ "hi",
+ "welcome",
+ ];
+
+ // Check if local part starts with prefix followed by a delimiter or end
+ for prefix in AUTOMATED_PREFIXES {
+ if local_part == *prefix {
+ return true;
+ }
+ if let Some(remainder) = local_part.strip_prefix(prefix)
+ && let Some(first_char) = remainder.chars().next()
+ && matches!(first_char, '@' | '-' | '.' | '+' | '=' | '_' | '0'..='9')
+ {
+ // Must be followed by a delimiter, not a letter (to avoid matching "support" in "supportive")
+ return true;
+ }
+ }
+
+ false
+}
+
+fn is_autogenerated_local_part(local_part: &str) -> bool {
+ // Too long - likely autogenerated
+ if local_part.len() > 50 {
+ return true;
+ }
+
+ // UUID pattern
+ if UUID_PATTERN.is_match(local_part) {
+ return true;
+ }
+
+ // Long hex string pattern
+ if HEX_PATTERN.is_match(local_part) {
+ return true;
+ }
+
+ // Purely numeric with delimiters (e.g., "123456", "123-456-789")
+ if !local_part.is_empty()
+ && local_part
+ .chars()
+ .all(|c| c.is_ascii_digit() || c == '.' || c == '-' || c == '_')
+ && local_part.chars().any(|c| c.is_ascii_digit())
+ {
+ return true;
+ }
+
+ // Starts with "id" followed by only numbers (e.g., "id12345")
+ if local_part.starts_with("id")
+ && local_part.len() > 2
+ && local_part[2..].chars().all(|c| c.is_ascii_digit())
+ {
+ return true;
+ }
+
+ // Starts with numbers followed by random-looking characters (e.g., "0000012345abcdef")
+ let digit_prefix_count = local_part
+ .chars()
+ .take_while(|c| c.is_ascii_digit())
+ .count();
+ if digit_prefix_count >= 6 {
+ return true;
+ }
+
+ false
+}
+
+/// Deduplicates a list of email addresses by normalizing them (removing + aliases)
+pub fn dedupe_emails(emails: Vec<String>) -> Vec<String> {
+ emails
+ .into_iter()
+ .map(|mut email| {
+ // Remove everything from + to @ if + exists
+ if let (Some(plus_pos), Some(at_pos)) = (email.find('+'), email.find('@'))
+ && plus_pos < at_pos
+ {
+ email.drain(plus_pos..at_pos);
+ }
+
+ email
+ })
+ .collect::<std::collections::HashSet<_>>()
+ .into_iter()
+ .collect()
+}
diff --git a/rust/cloud-storage/email_utils/src/tests.rs b/rust/cloud-storage/email_utils/src/generic_email/test.rs
similarity index 99%
rename from rust/cloud-storage/email_utils/src/tests.rs
rename to rust/cloud-storage/email_utils/src/generic_email/test.rs
index 83673e81b1..5eeda1ecbe 100644
--- a/rust/cloud-storage/email_utils/src/tests.rs
+++ b/rust/cloud-storage/email_utils/src/generic_email/test.rs
@@ -1,4 +1,4 @@
-use crate::{dedupe_emails, is_generic_email};
+use super::{dedupe_emails, is_generic_email};
#[test]
fn test_is_generic_email() {
diff --git a/rust/cloud-storage/email_utils/src/lib.rs b/rust/cloud-storage/email_utils/src/lib.rs
index 0c7780ee14..ba92074d93 100644
--- a/rust/cloud-storage/email_utils/src/lib.rs
+++ b/rust/cloud-storage/email_utils/src/lib.rs
@@ -1,337 +1,4 @@
-use lazy_static::lazy_static;
-use regex::Regex;
+pub mod body_replyless;
+pub mod generic_email;
-#[cfg(test)]
-mod tests;
-
-lazy_static! {
- static ref HEX_PATTERN: Regex = Regex::new(r"^[a-f0-9\-]{20,}$").unwrap();
- static ref UUID_PATTERN: Regex =
- Regex::new(r"^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$").unwrap();
-}
-
-/// Checks if an email address is likely a generic/automated system email
-///
-/// This function identifies common patterns in email addresses that typically
-/// indicate automated senders rather than individual users.
-pub fn is_generic_email(email: &str) -> bool {
- let email_lower = email.to_lowercase();
-
- // Split into local part and domain
- let (local_part, domain) = match email_lower.split_once('@') {
- Some(parts) => parts,
- None => return false, // Invalid email
- };
-
- // Check for automated email service domains first (most definitive)
- if is_automated_domain(domain) {
- return true;
- }
-
- // Check for obvious automated patterns in local part
- if contains_automated_keyword(local_part) {
- return true;
- }
-
- // Check if local part starts with automated prefix
- if starts_with_automated_prefix(local_part) {
- return true;
- }
-
- // Check for auto-generated local parts (numbers, UUIDs, hex strings)
- if is_autogenerated_local_part(local_part) {
- return true;
- }
-
- false
-}
-
-fn is_automated_domain(domain: &str) -> bool {
- const SYSTEM_DOMAINS: &[&str] = &[
- // Email service providers
- "sendgrid.net",
- "sendgrid.com",
- "mailchimp.com",
- "amazonses.com",
- "email.amazonses.com",
- "bounce.amazonses.com",
- "sparkpost.com",
- "mailgun.org",
- "mg.mailgun.org",
- "em.mailgun.org",
- "mailjet.com",
- "mandrillapp.com",
- "postmarkapp.com",
- "sendinblue.com",
- "klaviyo.com",
- "constantcontact.com",
- // CRM/Marketing platforms
- "salesforce.com",
- "salesforceiq.com",
- "hubspot.com",
- "marketo.com",
- "intercom.io",
- "intercom-mail.com",
- "campaign-archive.com",
- // Support platforms
- "zendesk.com",
- "freshdesk.com",
- // Google
- "notifications.google.com",
- ];
-
- SYSTEM_DOMAINS
- .iter()
- .any(|d| domain == *d || domain.ends_with(&format!(".{}", d)))
-}
-
-fn contains_automated_keyword(local_part: &str) -> bool {
- // Keywords that strongly indicate automation when present anywhere
- const STRONG_KEYWORDS: &[&str] = &[
- "noreply",
- "no-reply",
- "no.reply",
- "no_reply",
- "donotreply",
- "do-not-reply",
- "do.not.reply",
- "do_not_reply",
- "unsubscribe",
- "unsub",
- "automated",
- "mailer-daemon",
- "postmaster",
- ];
-
- STRONG_KEYWORDS.iter().any(|kw| local_part.contains(kw))
-}
-
-fn starts_with_automated_prefix(local_part: &str) -> bool {
- const AUTOMATED_PREFIXES: &[&str] = &[
- // Reply/No-reply variants
- "reply",
- "noreply",
- "no-reply",
- "no.reply",
- "no_reply",
- "donotreply",
- "do-not-reply",
- "do.not.reply",
- "do_not_reply",
- // System/Auto
- "auto",
- "automated",
- "system",
- "daemon",
- "cron",
- "scheduler",
- "robot",
- "bot",
- // Notifications/Alerts
- "alert",
- "alerts",
- "notification",
- "notifications",
- "notify",
- "digest",
- "bulletin",
- "announcements",
- "weekly",
- "daily",
- "monthly",
- // Support/Service
- "support",
- "help",
- "helpdesk",
- "service",
- "services",
- "customercare",
- "customer-care",
- "customer.care",
- "customerservice",
- "customer-service",
- "customer.service",
- // Admin/System
- "admin",
- "administrator",
- "webmaster",
- "postmaster",
- "sysadmin",
- "root",
- "ops",
- "devops",
- "monitor",
- "monitoring",
- "status",
- "logs",
- "error",
- "errors",
- // Accounts/Auth
- "account",
- "accounts",
- "auth",
- "authentication",
- "login",
- "signin",
- "password",
- "reset",
- "otp",
- "2fa",
- "mfa",
- "token",
- "verify",
- "verification",
- "confirm",
- "confirmation",
- "security",
- "secure",
- // Billing/Transactions
- "billing",
- "invoice",
- "invoices",
- "payment",
- "payments",
- "transaction",
- "transactions",
- "refund",
- "subscription",
- "subscriptions",
- "renewal",
- "receipt",
- "receipts",
- "order",
- "orders",
- // Shipping/Delivery
- "shipping",
- "delivery",
- "track",
- "tracking",
- "booking",
- "bookings",
- "reservations",
- // Marketing/Comms
- "marketing",
- "promo",
- "promotions",
- "offers",
- "deals",
- "news",
- "newsletter",
- "updates",
- "info",
- "information",
- "feedback",
- "survey",
- // Business departments
- "sales",
- "hr",
- "legal",
- "finance",
- "press",
- "media",
- "partnerships",
- "partners",
- "affiliates",
- "careers",
- "jobs",
- "applications",
- "events",
- // Dev/API
- "dev",
- "developer",
- "api",
- "test",
- "testing",
- "mailer",
- "mail",
- "bounce",
- "bounces",
- // Generic contact
- "contact",
- "team",
- "hello",
- "hi",
- "welcome",
- ];
-
- // Check if local part starts with prefix followed by a delimiter or end
- for prefix in AUTOMATED_PREFIXES {
- if local_part == *prefix {
- return true;
- }
- if let Some(remainder) = local_part.strip_prefix(prefix)
- && let Some(first_char) = remainder.chars().next()
- && matches!(first_char, '@' | '-' | '.' | '+' | '=' | '_' | '0'..='9')
- {
- // Must be followed by a delimiter, not a letter (to avoid matching "support" in "supportive")
- return true;
- }
- }
-
- false
-}
-
-fn is_autogenerated_local_part(local_part: &str) -> bool {
- // Too long - likely autogenerated
- if local_part.len() > 50 {
- return true;
- }
-
- // UUID pattern
- if UUID_PATTERN.is_match(local_part) {
- return true;
- }
-
- // Long hex string pattern
- if HEX_PATTERN.is_match(local_part) {
- return true;
- }
-
- // Purely numeric with delimiters (e.g., "123456", "123-456-789")
- if !local_part.is_empty()
- && local_part
- .chars()
- .all(|c| c.is_ascii_digit() || c == '.' || c == '-' || c == '_')
- && local_part.chars().any(|c| c.is_ascii_digit())
- {
- return true;
- }
-
- // Starts with "id" followed by only numbers (e.g., "id12345")
- if local_part.starts_with("id")
- && local_part.len() > 2
- && local_part[2..].chars().all(|c| c.is_ascii_digit())
- {
- return true;
- }
-
- // Starts with numbers followed by random-looking characters (e.g., "0000012345abcdef")
- let digit_prefix_count = local_part
- .chars()
- .take_while(|c| c.is_ascii_digit())
- .count();
- if digit_prefix_count >= 6 {
- return true;
- }
-
- false
-}
-
-/// Deduplicates a list of email addresses by normalizing them (removing + aliases)
-pub fn dedupe_emails(emails: Vec<String>) -> Vec<String> {
- emails
- .into_iter()
- .map(|mut email| {
- // Remove everything from + to @ if + exists
- if let (Some(plus_pos), Some(at_pos)) = (email.find('+'), email.find('@'))
- && plus_pos < at_pos
- {
- email.drain(plus_pos..at_pos);
- }
-
- email
- })
- .collect::<std::collections::HashSet<_>>()
- .into_iter()
- .collect()
-}
+pub use generic_email::{dedupe_emails, is_generic_email};
diff --git a/rust/cloud-storage/entity_access/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json b/rust/cloud-storage/entity_access/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
new file mode 100644
index 0000000000..44d3a67e72
--- /dev/null
+++ b/rust/cloud-storage/entity_access/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND l.macro_id = $2\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60"
+}
diff --git a/rust/cloud-storage/entity_access/justfile b/rust/cloud-storage/entity_access/justfile
new file mode 100644
index 0000000000..d5a52bc432
--- /dev/null
+++ b/rust/cloud-storage/entity_access/justfile
@@ -0,0 +1,6 @@
+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"
+
+mod sqlx '../sqlx.just'
+
+prepare_db:
+ just sqlx::prepare_db {{ DATABASE_URL }}
diff --git a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
index ae31de2703..ba3984d5ca 100644
--- a/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
+++ b/rust/cloud-storage/entity_access/src/inbound/axum_extractors/thread.rs
@@ -1,11 +1,12 @@
//! Thread (email thread) access extractor.
+use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;
use axum::{
Extension, RequestPartsExt, async_trait,
- extract::{FromRef, FromRequestParts},
+ extract::{FromRef, FromRequestParts, Path},
http::request::Parts,
};
@@ -16,7 +17,6 @@ use crate::domain::{
},
ports::EntityAccessService,
};
-use model::thread::EmailThreadPermission;
use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Validates that the user has at least the required access level to an email thread.
@@ -24,9 +24,7 @@ use model_user::axum_extractor::OptionalMacroUserExtractor;
/// Type parameter `T` specifies the required access level.
/// Type parameter `Svc` is the entity access service implementation.
///
-/// # Prerequisites
-///
-/// - Thread context must be loaded (EmailThreadPermission in extensions)
+/// Extracts the thread ID from the `thread_id` path parameter.
#[derive(Debug)]
pub struct ThreadAccessLevelExtractor<T: RequiredAccessLevel, Svc> {
/// The entity access receipt
@@ -53,10 +51,17 @@ where
.await
.map_err(|_| ExtractorError::Internal)?;
- let thread_context: Extension<EmailThreadPermission> = parts
+ let Path(path_params): Path<HashMap<String, String>> = parts
.extract()
.await
- .map_err(|_| ExtractorError::Internal)?;
+ .map_err(|_| ExtractorError::BadRequest("missing thread_id path parameter"))?;
+
+ let thread_id = path_params
+ .get("thread_id")
+ .ok_or(ExtractorError::BadRequest(
+ "missing thread_id path parameter",
+ ))?
+ .clone();
let internal_user: Option<Extension<InternalUser>> = if macro_user_id.is_none() {
parts
@@ -71,7 +76,7 @@ where
return Ok(Self {
entity_access_receipt: EntityAccessReceipt {
entity: Entity {
- entity_id: thread_context.thread_id.clone(),
+ entity_id: thread_id,
entity_type: EntityType::EmailThread,
},
auth: EntityAccessAuth::Internal,
@@ -90,18 +95,14 @@ where
Some(macro_user_id) => service
.check_access(
Some(macro_user_id),
- &thread_context.thread_id,
+ &thread_id,
EntityType::EmailThread,
required_level,
)
.await
.map_err(ExtractorError::from)?,
None => service
- .check_public_access(
- &thread_context.thread_id,
- EntityType::EmailThread,
- required_level,
- )
+ .check_public_access(&thread_id, EntityType::EmailThread, required_level)
.await
.map_err(ExtractorError::from)?,
};
@@ -109,7 +110,7 @@ where
Ok(Self {
entity_access_receipt: EntityAccessReceipt {
entity: Entity {
- entity_id: thread_context.thread_id.clone(),
+ entity_id: thread_id,
entity_type: EntityType::EmailThread,
},
auth: macro_user_id
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
index 3faa125425..7ba1ae8414 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
@@ -4,6 +4,7 @@ use crate::domain::models::AccessLevel;
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
use sqlx::PgPool;
use std::str::FromStr;
+use uuid::Uuid;
/// Get the highest access level a user has for an email thread.
///
@@ -16,6 +17,29 @@ pub async fn get_thread_access(
user_id: Option<&MacroUserId<Lowercase<'_>>>,
) -> Result<Option<AccessLevel>, sqlx::Error> {
let user_id = user_id.map(AsRef::as_ref).unwrap_or("");
+
+ let thread_uuid = Uuid::parse_str(thread_id).map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
+
+ let is_owner = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM public.email_threads t
+ JOIN public.email_links l ON l.id = t.link_id
+ WHERE t.id = $1::uuid
+ AND l.macro_id = $2
+ ) AS "exists!"
+ "#,
+ thread_uuid,
+ user_id
+ )
+ .fetch_one(pool)
+ .await?;
+
+ if is_owner {
+ return Ok(Some(AccessLevel::Owner));
+ }
+
let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(
r#"
-- CTE to recursively find all parent projects for the given email thread.
diff --git a/rust/cloud-storage/model/Cargo.toml b/rust/cloud-storage/model/Cargo.toml
index 74f08e8f25..6afd353a92 100644
--- a/rust/cloud-storage/model/Cargo.toml
+++ b/rust/cloud-storage/model/Cargo.toml
@@ -12,14 +12,13 @@ axum = { workspace = true }
base64 = { workspace = true }
chrono = { workspace = true }
document_sub_type = { path = "../document_sub_type" }
-doppleganger = { workspace = true }
+doppleganger = { workspace = true, features = ["chrono", "uuid"] }
macro_user_id = { path = "../macro_user_id" }
model-error-response = { path = "../model-error-response" }
model_file_type = { path = "../model_file_type", features = ["utoipa"] }
model_user = { path = "../model_user", features = ["axum"] }
models_bulk_upload = { path = "../models_bulk_upload" }
models_comms = { path = "../models_comms" }
-models_email = { path = "../models_email" }
models_pagination = { path = "../models_pagination" }
models_permissions = { path = "../models_permissions" }
schemars = { workspace = true }
diff --git a/rust/cloud-storage/models_email/Cargo.toml b/rust/cloud-storage/models_email/Cargo.toml
index 5b3872c8b5..b66284420e 100644
--- a/rust/cloud-storage/models_email/Cargo.toml
+++ b/rust/cloud-storage/models_email/Cargo.toml
@@ -11,6 +11,7 @@ chrono = { workspace = true }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
ego-tree = { workspace = true }
email = { path = "../email" }
+email_utils = { path = "../email_utils" }
html2text = "0.15.1"
lazy_static = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_parsed.rs b/rust/cloud-storage/models_email/src/email/service/body_parsing/body_parsed.rs
index 3f783ce25a..f4e785aec3 100644
--- a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_parsed.rs
+++ b/rust/cloud-storage/models_email/src/email/service/body_parsing/body_parsed.rs
@@ -69,7 +69,6 @@ fn parse_html_to_text(
#[cfg(test)]
mod tests {
use super::*;
- use uuid::Uuid;
fn get_default_config() -> Config<PlainDecorator> {
html2text::config::plain()
@@ -80,8 +79,6 @@ mod tests {
#[test]
fn test_parse_html_to_text_with_simple_html() {
let html = Some("<html><body><p>Hello, world!</p></body></html>".to_string());
- let provider_id = "gmail";
- let link_id = macro_uuid::generate_uuid_v7();
let result = parse_html_to_text(&html, get_default_config());
@@ -91,8 +88,6 @@ mod tests {
#[test]
fn test_parse_html_to_text_with_none() {
let html: Option<String> = None;
- let provider_id = "gmail";
- let link_id = macro_uuid::generate_uuid_v7();
let result = parse_html_to_text(&html, get_default_config());
assert_eq!(result, None);
@@ -101,8 +96,6 @@ mod tests {
#[test]
fn test_parse_html_to_text_with_empty_html() {
let html = Some("".to_string());
- let provider_id = "gmail";
- let link_id = macro_uuid::generate_uuid_v7();
let result = parse_html_to_text(&html, get_default_config());
@@ -112,8 +105,6 @@ mod tests {
#[test]
fn test_parse_html_to_text_with_malformed_html() {
let html = Some("<p>Unclosed paragraph<div>Nested content</p>".to_string());
- let provider_id = "yahoo";
- let link_id = macro_uuid::generate_uuid_v7();
let result = parse_html_to_text(&html, get_default_config());
@@ -146,8 +137,6 @@ mod tests {
"#
.to_string(),
);
- let provider_id = "gmail";
- let link_id = Uuid::new_v4();
let result = parse_html_to_text(&html, get_default_config());
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs b/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs
deleted file mode 100644
index 247881fdf9..0000000000
--- a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs
+++ /dev/null
@@ -1,140 +0,0 @@
-use crate::email::service::message;
-
-mod constants;
-mod html_parser;
-mod plaintext_parser;
-
-use html_parser::extract_reply_html;
-use plaintext_parser::extract_reply_plaintext;
-
-pub fn get_body_replyless_for_message(message: &message::Message) -> Option<String> {
- if let Some(sanitized) = message.body_html_sanitized.as_ref() {
- extract_reply_html(message.subject.as_deref(), sanitized).into()
- } else if let Some(body) = message.body_text.as_ref() {
- extract_reply_plaintext(message.subject.as_deref(), body).into()
- } else {
- None
- }
-}
-
-// Tests are commented out since HTML attribute order is non-deterministic (stored in HashMap).
-// The tags could be in any order, making string comparisons unreliable without complex sorting logic.
-// These test cases remain valuable for manual verification during development.
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::service;
-
- #[test]
- fn test_extract_message_reply_outlook_test_1() {
- // Given an email with Outlook-style formatting and a "From:" separator
- let full_email = include_str!("testdata/outlook-test-1/full.html");
- let expected_reply = include_str!("testdata/outlook-test-1/body_replyless.html");
-
- test_email_extraction(full_email, expected_reply, "outlook-test-1");
- }
-
- #[test]
- fn test_extract_message_reply_outlook_test_2() {
- // Given an email with Outlook-style formatting and a "From:" separator
- let full_email = include_str!("testdata/outlook-test-2/full.html");
- let expected_reply = include_str!("testdata/outlook-test-2/body_replyless.html");
-
- test_email_extraction(full_email, expected_reply, "outlook-test-2");
- }
-
- #[test]
- fn test_extract_message_reply_test_1() {
- let full_email = include_str!("testdata/test-1/full.html");
- let expected_reply = include_str!("testdata/test-1/body_replyless.html");
-
- test_email_extraction(full_email, expected_reply, "test-1");
- }
-
- #[test]
- fn test_extract_message_reply_test_2() {
- let full_email = include_str!("testdata/test-2/full.html");
- let expected_reply = include_str!("testdata/test-2/body_replyless.html");
-
- test_email_extraction(full_email, expected_reply, "test-2");
- }
-
- #[test]
- fn test_extract_message_reply_test_3() {
- let full_email = include_str!("testdata/test-3/full.html");
- let expected_reply = include_str!("testdata/test-3/body_replyless.html");
-
- test_email_extraction(full_email, expected_reply, "test-3");
- }
-
- /// gmail selectors WITHOUT a gmail_attr div within them should not be split off
- #[test]
- fn test_extract_message_reply_test_4() {
- let full_email = include_str!("testdata/test-4/full.html");
- let expected_reply = include_str!("testdata/test-4/body_replyless.html");
-
- test_email_extraction(full_email, expected_reply, "test-4");
- }
-
- /// the entire email (including style tags before the body) should be used if no splitter
- /// is found on the email
- #[test]
- fn test_extract_message_reply_test_5() {
- let full_email = include_str!("testdata/test-5/full.html");
- let expected_reply = include_str!("testdata/test-5/body_replyless.html");
-
- test_email_extraction(full_email, expected_reply, "test-5");
- }
-
- fn test_email_extraction(full_email: &str, expected_reply: &str, test_name: &str) {
- // Create a message with HTML content
- let message = service::message::Message {
- db_id: uuid::Uuid::default(),
- provider_id: None,
- global_id: None,
- thread_db_id: uuid::Uuid::default(),
- provider_thread_id: None,
- replying_to_id: None,
- link_id: Default::default(),
- subject: None,
- snippet: None,
- provider_history_id: None,
- internal_date_ts: None,
- sent_at: None,
- size_estimate: None,
- is_read: false,
- is_starred: false,
- is_sent: false,
- is_draft: false,
- scheduled_send_time: None,
- has_attachments: false,
- from: None,
- to: vec![],
- cc: vec![],
- bcc: vec![],
- body_html_sanitized: Some(full_email.to_string()),
- body_text: None,
- attachments: vec![],
- attachments_draft: vec![],
- attachments_forwarded: vec![],
- headers_json: None,
- created_at: Default::default(),
- labels: vec![],
- body_macro: None,
- updated_at: Default::default(),
- };
-
- let body_replyless = get_body_replyless_for_message(&message);
-
- assert_eq!(
- body_replyless
- .unwrap()
- .replace(" ", "")
- .replace("\n", "")
- .trim(),
- expected_reply.replace(" ", "").replace("\n", "").trim(),
- "Test '{}' failed: extracted reply doesn't match expected",
- test_name
- );
- }
-}
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/mod.rs b/rust/cloud-storage/models_email/src/email/service/body_parsing/mod.rs
index 35e12e9fe5..077ce68427 100644
--- a/rust/cloud-storage/models_email/src/email/service/body_parsing/mod.rs
+++ b/rust/cloud-storage/models_email/src/email/service/body_parsing/mod.rs
@@ -1,2 +1 @@
pub(crate) mod body_parsed;
-pub(crate) mod body_replyless;
diff --git a/rust/cloud-storage/models_email/src/email/service/message.rs b/rust/cloud-storage/models_email/src/email/service/message.rs
index 4958eb5593..f66053d763 100644
--- a/rust/cloud-storage/models_email/src/email/service/message.rs
+++ b/rust/cloud-storage/models_email/src/email/service/message.rs
@@ -6,7 +6,6 @@ use crate::service::attachment::{AttachmentDraft, AttachmentForwarded, Attachmen
use crate::service::body_parsing::body_parsed::{
get_body_parsed_for_message, get_body_parsed_linkless_for_message,
};
-use crate::service::body_parsing::body_replyless::get_body_replyless_for_message;
use crate::service::label::Label;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
@@ -106,7 +105,11 @@ pub struct MessageWithBodyReplyless {
impl From<Message> for MessageWithBodyReplyless {
fn from(message: Message) -> Self {
Self {
- body_replyless: get_body_replyless_for_message(&message),
+ body_replyless: email_utils::body_replyless::compute_body_replyless(
+ message.subject.as_deref(),
+ message.body_html_sanitized.as_deref(),
+ message.body_text.as_deref(),
+ ),
inner: message,
}
}
diff --git a/rust/cloud-storage/models_email/src/email/service/thread.rs b/rust/cloud-storage/models_email/src/email/service/thread.rs
index 5f292235cb..db4bdb0dba 100644
--- a/rust/cloud-storage/models_email/src/email/service/thread.rs
+++ b/rust/cloud-storage/models_email/src/email/service/thread.rs
@@ -1,11 +1,9 @@
use crate::email::service::message::Message;
use crate::service::attachment::Attachment;
use crate::service::contact::Contact;
-use crate::service::message::MessageWithBodyReplyless;
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{Identify, SimpleSortMethod, SortOn};
-use models_permissions::share_permission::access_level::AccessLevel;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_with::{DeserializeFromStr, SerializeDisplay};
@@ -45,49 +43,6 @@ pub struct Thread {
pub messages: Vec<Message>,
}
-/// Thread object exposed to the FE in Get Threads Call
-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
-pub struct APIThread {
- pub db_id: Uuid,
- pub provider_id: Option<String>,
- pub link_id: Uuid,
- pub inbox_visible: bool,
- pub is_read: bool,
- pub access_level: AccessLevel,
- // this field is only set w.r.t incoming messages (see is_inbound), for inbox thread ordering
- pub latest_inbound_message_ts: Option<DateTime<Utc>>,
- // this field is only set w.r.t outgoing messages (see is_outbound), for sent message thread ordering
- pub latest_outbound_message_ts: Option<DateTime<Utc>>,
- // latest message in the thread that isn't marked as spam, for all mail thread ordering
- pub latest_non_spam_message_ts: Option<DateTime<Utc>>,
- pub created_at: DateTime<Utc>,
- pub updated_at: DateTime<Utc>,
- pub messages: Vec<MessageWithBodyReplyless>,
-}
-
-impl APIThread {
- pub fn from_thread_with_messages(
- thread: Thread,
- messages: Vec<MessageWithBodyReplyless>,
- access_level: AccessLevel,
- ) -> Self {
- Self {
- db_id: thread.db_id,
- provider_id: thread.provider_id,
- link_id: thread.link_id,
- inbox_visible: thread.inbox_visible,
- is_read: thread.is_read,
- access_level,
- latest_inbound_message_ts: thread.latest_inbound_message_ts,
- latest_outbound_message_ts: thread.latest_outbound_message_ts,
- latest_non_spam_message_ts: thread.latest_non_spam_message_ts,
- created_at: thread.created_at,
- updated_at: thread.updated_at,
- messages,
- }
- }
-}
-
/// thread summary returned in preview endpoint
#[derive(FromRow, Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ThreadPreview {
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index 52c4823025..f37cb7bd3f 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -91,6 +91,7 @@ serde_json = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
ai = { path = "../ai" }
+entity_access = { path = "../entity_access" }
[[example]]
name = "ai_tools_cli"
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index f082982288..1d71184a78 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -4,6 +4,7 @@ use chrono::Days;
use comms::domain::models::GetChannelsRequest;
use cool_asserts::assert_matches;
use email::domain::models::{EmailErr, EnrichedEmailThreadPreview, PreviewView};
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
use frecency::domain::models::{FrecencyPageRequest, FrecencyPageResponse};
use frecency::domain::ports::MockFrecencyQueryService;
use frecency::domain::services::FrecencyQueryServiceImpl;
@@ -45,6 +46,15 @@ impl EmailService for NoopEmailService {
) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
}
+
+ async fn get_thread_with_messages(
+ &self,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ _offset: i64,
+ _limit: i64,
+ ) -> Result<Option<email::domain::models::Thread>, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
+ }
}
struct NoopCommsService;
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index d667fb8f38..93ae696ab0 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -7,6 +7,7 @@ use email::domain::{
models::{EmailErr, PreviewView, PreviewViewStandardLabel, UserProvider},
ports::EmailService,
};
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
use http_body_util::BodyExt;
use item_filters::EntityFilters;
use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
@@ -89,6 +90,15 @@ impl EmailService for MockEmail {
updated_at: Default::default(),
}))
}
+
+ async fn get_thread_with_messages(
+ &self,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ _offset: i64,
+ _limit: i64,
+ ) -> Result<Option<email::domain::models::Thread>, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
}
fn mock_router() -> Router {
@@ -152,6 +162,15 @@ impl EmailService for MockEmailLinkResult {
) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
(self.get_link_result)()
}
+
+ async fn get_thread_with_messages(
+ &self,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ _offset: i64,
+ _limit: i64,
+ ) -> Result<Option<email::domain::models::Thread>, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
}
#[tokio::test]