@open-workspace/email 0.4.2 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -4
- package/alchemy/index.ts +130 -2
- package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
- package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
- package/drizzle/mailbox/meta/_journal.json +7 -0
- package/drizzle/mailbox/migrations.js +3 -1
- package/migrations/0002_after_0_4_2.sql +35 -0
- package/migrations/meta/0002_snapshot.json +807 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +23 -7
- package/shared/attachment-preview.ts +18 -8
- package/shared/folder-order.ts +31 -6
- package/shared/mail-headers.ts +3 -3
- package/shared/mail-html.ts +25 -0
- package/shared/mail-import.ts +0 -7
- package/shared/mail-received.ts +4 -4
- package/shared/mail-rule-actions.ts +47 -0
- package/shared/mail-sender-intel.ts +5 -1
- package/shared/mail.ts +70 -4
- package/shared/office-preview.ts +0 -4
- package/shared/pdfjs-assets.ts +1 -3
- package/shared/rich-content.ts +35 -0
- package/shared/signature.ts +15 -0
- package/src/admin/address-auto-reply.tsx +52 -0
- package/src/admin/blocked-senders.tsx +86 -66
- package/src/admin/forward-destinations.tsx +140 -0
- package/src/admin/mail-archive.tsx +134 -0
- package/src/admin/team-signature.tsx +90 -0
- package/src/client.tsx +130 -16
- package/src/mail/attachment-preview-dialog.tsx +13 -5
- package/src/mail/auto-reply-banner.tsx +61 -0
- package/src/mail/blocked-senders.tsx +124 -91
- package/src/mail/compose-window-chrome.tsx +20 -8
- package/src/mail/compose-window.tsx +391 -365
- package/src/mail/composer-asset-bookmarks.ts +47 -12
- package/src/mail/composer-attachment-list.tsx +42 -17
- package/src/mail/composer-editor-document.ts +54 -10
- package/src/mail/composer-editor.tsx +44 -44
- package/src/mail/composer-link-text.ts +42 -0
- package/src/mail/composer-recipient-fields.tsx +25 -16
- package/src/mail/composer-recipients.ts +62 -16
- package/src/mail/composer-session.ts +107 -23
- package/src/mail/composer-toolbar.tsx +15 -1
- package/src/mail/composer-upload-client.ts +29 -1
- package/src/mail/composer-upload-progress.ts +2 -2
- package/src/mail/conversation-actions-model.ts +56 -0
- package/src/mail/conversation-list.tsx +263 -128
- package/src/mail/conversation-loading-skeleton.tsx +165 -90
- package/src/mail/conversation-message.tsx +257 -102
- package/src/mail/conversation-order.ts +12 -0
- package/src/mail/conversation-reply.tsx +313 -189
- package/src/mail/conversation-selection-toolbar.tsx +188 -143
- package/src/mail/conversation-view.tsx +315 -85
- package/src/mail/delivery-indicator.tsx +33 -12
- package/src/mail/draft-attachments.ts +194 -0
- package/src/mail/email-html-body.tsx +97 -53
- package/src/mail/folder-cleanup-bar.tsx +193 -0
- package/src/mail/folder-glyph.tsx +5 -0
- package/src/mail/folder-manager.tsx +71 -38
- package/src/mail/mail-app-bar.tsx +15 -3
- package/src/mail/mail-dock.tsx +19 -3
- package/src/mail/mail-focus.ts +48 -0
- package/src/mail/mail-folders.ts +14 -2
- package/src/mail/mail-layout.css +20 -0
- package/src/mail/mail-mailbox-sheet.tsx +22 -69
- package/src/mail/mail-nav-rail.tsx +7 -4
- package/src/mail/mail-nav.tsx +66 -46
- package/src/mail/mail-prefetch.ts +30 -9
- package/src/mail/mail-primitives.tsx +6 -4
- package/src/mail/mail-queries.ts +122 -20
- package/src/mail/mail-query-cache.ts +1085 -173
- package/src/mail/mail-search-params.ts +35 -0
- package/src/mail/mail-shell.tsx +32 -9
- package/src/mail/mailbox-ai-settings.tsx +56 -42
- package/src/mail/mailbox-realtime.tsx +4 -12
- package/src/mail/mailbox-rules.tsx +898 -0
- package/src/mail/message-actions.tsx +38 -26
- package/src/mail/message-attachments.tsx +20 -12
- package/src/mail/message-body.ts +53 -0
- package/src/mail/message-format.ts +8 -2
- package/src/mail/message-header.tsx +3 -1
- package/src/mail/message-translation.tsx +34 -67
- package/src/mail/original-message-sheet.tsx +63 -50
- package/src/mail/original-message.ts +6 -6
- package/src/mail/pane-splitter.tsx +3 -3
- package/src/mail/pdf-preview.tsx +70 -62
- package/src/mail/plain-message-text.tsx +28 -0
- package/src/mail/print-message.ts +31 -36
- package/src/mail/reader-pane.tsx +134 -103
- package/src/mail/recipient-combobox.tsx +52 -29
- package/src/mail/recipient-field-row.tsx +3 -0
- package/src/mail/rich-content.ts +128 -0
- package/src/mail/sanitize-email-html.ts +53 -32
- package/src/mail/sender-actions.tsx +48 -46
- package/src/mail/sender-authentication.tsx +1 -1
- package/src/mail/sender-dialogs.tsx +67 -43
- package/src/mail/sender-security.tsx +12 -11
- package/src/mail/signature.ts +43 -0
- package/src/mail/translation-html.ts +3 -3
- package/src/mail/types.ts +12 -0
- package/src/mail/use-composer-attachment-preflight.ts +23 -60
- package/src/mail/use-composer-core.ts +286 -0
- package/src/mail/use-composer-navigation.ts +120 -0
- package/src/mail/use-composer-submission.ts +154 -19
- package/src/mail/use-conversation-actions.ts +292 -0
- package/src/mail/use-conversation-position.ts +51 -0
- package/src/mail/use-conversation-selection.ts +192 -89
- package/src/mail/use-draft-autosave.ts +394 -0
- package/src/mail/use-drafts.ts +194 -0
- package/src/mail/use-mail-controller.ts +758 -213
- package/src/mail/use-mail-data.ts +210 -100
- package/src/mail/use-mail-safety.ts +19 -38
- package/src/mail/use-mail-send.ts +18 -6
- package/src/mail/use-pdf-translation.ts +1 -1
- package/src/mail/use-reply-cc.ts +61 -0
- package/src/mail/use-visible-message-read.ts +128 -64
- package/src/pwa/push-key.ts +18 -0
- package/src/pwa/push-subscription.ts +88 -26
- package/src/settings/auto-reply-editor.tsx +454 -0
- package/src/settings/auto-reply-page.tsx +59 -0
- package/src/settings/mail-apps-page.tsx +52 -43
- package/src/settings/notifications-page.tsx +82 -67
- package/src/settings/rich-content-editor.tsx +182 -0
- package/src/settings/settings-queries.ts +57 -0
- package/src/settings/signature-editor.tsx +142 -0
- package/src/settings/signature-page.tsx +70 -0
- package/worker/admin/blocked-sender-routes.ts +10 -16
- package/worker/backups/eml.ts +185 -0
- package/worker/backups/file-parts.ts +140 -0
- package/worker/backups/mail-backup.ts +644 -0
- package/worker/backups/settings-backup.ts +866 -0
- package/worker/backups/stream-eml.ts +73 -0
- package/worker/db/schema.ts +89 -5
- package/worker/jmap/attachment-blobs.ts +113 -0
- package/worker/jmap/blobs.ts +162 -0
- package/worker/jmap/draft-content.ts +42 -0
- package/worker/jmap/drafts.ts +70 -0
- package/worker/jmap/email-body.ts +152 -0
- package/worker/jmap/email-methods.ts +1223 -0
- package/worker/jmap/eventsource.ts +9 -8
- package/worker/jmap/import-methods.ts +205 -0
- package/worker/jmap/mailbox-methods.ts +187 -0
- package/worker/jmap/method-core.ts +379 -0
- package/worker/jmap/methods.ts +119 -1816
- package/worker/jmap/push-subscription-methods.ts +373 -0
- package/worker/jmap/push-types.ts +46 -2
- package/worker/jmap/push.ts +24 -31
- package/worker/jmap/routes.ts +144 -153
- package/worker/jmap/submission-methods.ts +395 -0
- package/worker/mail/access.ts +35 -12
- package/worker/mail/ai-classification.ts +2 -2
- package/worker/mail/archive-object.ts +96 -0
- package/worker/mail/archive-routes.ts +35 -0
- package/worker/mail/archive.ts +700 -0
- package/worker/mail/auth-headers.ts +57 -43
- package/worker/mail/auto-reply-routes.ts +260 -0
- package/worker/mail/auto-reply.ts +243 -0
- package/worker/mail/bimi.ts +53 -36
- package/worker/mail/bootstrap.ts +11 -3
- package/worker/mail/capabilities.ts +69 -0
- package/worker/mail/classification-signals.ts +1 -1
- package/worker/mail/confusables-data.ts +9 -0
- package/worker/mail/conversation-cursor.ts +6 -15
- package/worker/mail/delivery-events.ts +9 -7
- package/worker/mail/delivery-facts.ts +1 -1
- package/worker/mail/demo-routes.ts +3 -3
- package/worker/mail/doh.ts +3 -3
- package/worker/mail/download-links.ts +153 -0
- package/worker/mail/downloads.ts +2 -6
- package/worker/mail/draft-routes.ts +473 -0
- package/worker/mail/draft-sender.ts +54 -0
- package/worker/mail/edge-cache.ts +41 -55
- package/worker/mail/email-routing.ts +123 -0
- package/worker/mail/forward-destinations.ts +114 -0
- package/worker/mail/forward-downloads.ts +115 -0
- package/worker/mail/forward-html.ts +85 -0
- package/worker/mail/header-metadata.ts +2 -5
- package/worker/mail/impersonation.ts +102 -101
- package/worker/mail/import-routes.ts +29 -82
- package/worker/mail/import.ts +130 -0
- package/worker/mail/inbound-delivery.ts +6 -5
- package/worker/mail/inbound-threading.ts +15 -2
- package/worker/mail/inbound.ts +58 -28
- package/worker/mail/ip-intel.ts +8 -17
- package/worker/mail/isolate-cache.ts +1 -1
- package/worker/mail/mailbox-deletion.ts +33 -12
- package/worker/mail/mailbox-directory.ts +39 -65
- package/worker/mail/mailing-list.ts +29 -58
- package/worker/mail/message-security.ts +19 -8
- package/worker/mail/message-view.ts +12 -10
- package/worker/mail/office-conversion.ts +3 -5
- package/worker/mail/office-preview-container.ts +3 -8
- package/worker/mail/outbound-content.ts +139 -65
- package/worker/mail/outbound-delivery.ts +20 -17
- package/worker/mail/outbound-service.ts +34 -9
- package/worker/mail/outbound.ts +146 -75
- package/worker/mail/outgoing-context.ts +60 -30
- package/worker/mail/participants.ts +10 -15
- package/worker/mail/plain-body.ts +39 -0
- package/worker/mail/push-endpoint.ts +17 -0
- package/worker/mail/push-notifications.ts +53 -62
- package/worker/mail/quote-parser.ts +36 -24
- package/worker/mail/receive.ts +146 -39
- package/worker/mail/recipients.ts +1 -1
- package/worker/mail/remote-proxy.ts +3 -3
- package/worker/mail/repeat.ts +1 -1
- package/worker/mail/reply-plan.ts +124 -26
- package/worker/mail/rfc.ts +15 -7
- package/worker/mail/rich-content.ts +207 -0
- package/worker/mail/routes.ts +698 -304
- package/worker/mail/routing.ts +274 -0
- package/worker/mail/rules.ts +230 -0
- package/worker/mail/safety-routes.ts +88 -86
- package/worker/mail/schemas.ts +222 -31
- package/worker/mail/search.ts +25 -2
- package/worker/mail/security-settings.ts +4 -10
- package/worker/mail/send-message.ts +238 -0
- package/worker/mail/sender-intel.ts +12 -20
- package/worker/mail/signature-routes.ts +206 -0
- package/worker/mail/signatures.ts +195 -0
- package/worker/mail/spamhaus.ts +28 -16
- package/worker/mail/storage-keys.ts +35 -0
- package/worker/mail/unsubscribe.ts +19 -41
- package/worker/mail/uploads.ts +192 -80
- package/worker/mail/webhook-source.ts +3 -2
- package/worker/mail/workspace-safety.ts +194 -60
- package/worker/mailbox/demo.ts +13 -15
- package/worker/mailbox/email-index.ts +65 -35
- package/worker/mailbox/folder-model.ts +0 -20
- package/worker/mailbox/import-placement.ts +21 -36
- package/worker/mailbox/inbound-decision.ts +114 -0
- package/worker/mailbox/inbox-counts.ts +45 -25
- package/worker/mailbox/index.ts +756 -3201
- package/worker/mailbox/jmap-change-log.ts +195 -0
- package/worker/mailbox/jmap-email-rows.ts +186 -0
- package/worker/mailbox/jmap-mailboxes.ts +116 -0
- package/worker/mailbox/jmap-placement.ts +139 -0
- package/worker/mailbox/jmap-query-filter.ts +231 -0
- package/worker/mailbox/jmap-store.ts +167 -299
- package/worker/mailbox/mailbox-auto-reply.ts +316 -0
- package/worker/mailbox/mailbox-backup.ts +538 -0
- package/worker/mailbox/mailbox-drafts.ts +417 -0
- package/worker/mailbox/mailbox-folders.ts +242 -0
- package/worker/mailbox/mailbox-import.ts +455 -0
- package/worker/mailbox/mailbox-inbound.ts +934 -0
- package/worker/mailbox/mailbox-jmap.ts +294 -0
- package/worker/mailbox/mailbox-outbound.ts +413 -0
- package/worker/mailbox/mailbox-rules.ts +336 -0
- package/worker/mailbox/mailbox-senders.ts +294 -0
- package/worker/mailbox/mailbox-storage.ts +438 -0
- package/worker/mailbox/mailbox-views.ts +891 -0
- package/worker/mailbox/model.ts +1 -0
- package/worker/mailbox/office-preview-jobs.ts +59 -47
- package/worker/mailbox/placement.ts +933 -0
- package/worker/mailbox/restore-thread.ts +52 -0
- package/worker/mailbox/retention.ts +36 -0
- package/worker/mailbox/schema.ts +200 -1
- package/worker/mailbox/senders.ts +216 -178
- package/worker/mailbox/spam-undo-filing.ts +138 -0
- package/worker/mailbox/spam-undo.ts +253 -0
- package/worker/mailbox/support.ts +416 -0
- package/worker/mcp/mail-action-tools.ts +161 -1
- package/worker/mcp/mail-compose-tools.ts +7 -1
- package/worker/mcp/mail-safety-tools.ts +4 -4
- package/worker/module.ts +23 -4
- package/src/mail/use-compose-submission.ts +0 -208
- package/src/mail/use-reply-submission.ts +0 -114
- package/worker/mail/capped-body.ts +0 -36
package/worker/mailbox/index.ts
CHANGED
|
@@ -1,122 +1,50 @@
|
|
|
1
|
-
import {
|
|
2
|
-
aiObjectRunner,
|
|
3
|
-
aiFeatureEnabled,
|
|
4
|
-
aiModel,
|
|
5
|
-
createId,
|
|
6
|
-
normalizeMailboxAddress,
|
|
7
|
-
deferWebhookTask,
|
|
8
|
-
queueWebhookEvent,
|
|
9
|
-
} from "@open-workspace/core/module";
|
|
10
|
-
import type { AiModel } from "@open-workspace/core/module";
|
|
11
|
-
import { required } from "@open-workspace/core/shared";
|
|
1
|
+
import { aiModel, inJsonList } from "@open-workspace/core/module";
|
|
12
2
|
import { DurableObject } from "cloudflare:workers";
|
|
13
|
-
import {
|
|
14
|
-
and,
|
|
15
|
-
asc,
|
|
16
|
-
desc,
|
|
17
|
-
eq,
|
|
18
|
-
inArray,
|
|
19
|
-
isNotNull,
|
|
20
|
-
isNull,
|
|
21
|
-
lt,
|
|
22
|
-
lte,
|
|
23
|
-
ne,
|
|
24
|
-
or,
|
|
25
|
-
sql,
|
|
26
|
-
} from "drizzle-orm";
|
|
3
|
+
import { and, desc, eq, isNotNull, or, min, sql } from "drizzle-orm";
|
|
27
4
|
import { drizzle } from "drizzle-orm/durable-sqlite";
|
|
28
|
-
import type { DrizzleSqliteDODatabase } from "drizzle-orm/durable-sqlite";
|
|
29
5
|
import { migrate } from "drizzle-orm/durable-sqlite/migrator";
|
|
30
|
-
import { z } from "zod";
|
|
31
6
|
|
|
32
7
|
import migrations from "../../drizzle/mailbox/migrations.js";
|
|
33
|
-
import {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
isCompleteFolderOrder,
|
|
37
|
-
sortFolders,
|
|
38
|
-
} from "../../shared/folder-order";
|
|
39
|
-
import {
|
|
40
|
-
MAX_CUSTOM_FOLDER_COUNT,
|
|
41
|
-
mailboxRealtimeUpdate,
|
|
42
|
-
} from "../../shared/mail";
|
|
43
|
-
import type {
|
|
44
|
-
MailboxPushJob,
|
|
45
|
-
MailboxRealtimeClientMessage,
|
|
46
|
-
} from "../../shared/mail";
|
|
8
|
+
import { conversationFolder } from "../../shared/folder-order";
|
|
9
|
+
import { mailboxRealtimeUpdate } from "../../shared/mail";
|
|
10
|
+
import type { MailboxPushJob } from "../../shared/mail";
|
|
47
11
|
import { blockPatternsFor } from "../../shared/mail-feedback";
|
|
48
|
-
import type {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
Unsubscription,
|
|
52
|
-
} from "../../shared/mail-feedback";
|
|
53
|
-
import { headerValues } from "../../shared/mail-headers";
|
|
54
|
-
import { MAX_IMPORTED_TEXT_CHARACTERS } from "../../shared/mail-import";
|
|
55
|
-
import type { ImportPlacement } from "../../shared/mail-import";
|
|
56
|
-
import {
|
|
57
|
-
officePreviewExtension,
|
|
58
|
-
officePreviewKey,
|
|
59
|
-
} from "../../shared/office-preview";
|
|
60
|
-
import {
|
|
61
|
-
EMAIL_RECEIVED_EVENT,
|
|
62
|
-
EMAIL_WEBHOOK_SOURCE,
|
|
63
|
-
emailWebhookEventId,
|
|
64
|
-
} from "../../shared/webhooks";
|
|
65
|
-
import {
|
|
66
|
-
classifyInboundEmail,
|
|
67
|
-
EmailAiClassificationError,
|
|
68
|
-
MAILBOX_AI_MAX_ATTEMPTS,
|
|
69
|
-
} from "../mail/ai-classification";
|
|
70
|
-
import { classificationSignals } from "../mail/classification-signals";
|
|
71
|
-
import type { ClassificationSignals } from "../mail/classification-signals";
|
|
72
|
-
import { deliveryFacts } from "../mail/delivery-facts";
|
|
73
|
-
import {
|
|
74
|
-
inboundMessageId,
|
|
75
|
-
MissingRawMimeError,
|
|
76
|
-
prepareInboundEmail,
|
|
77
|
-
prepareUnprocessableInboundEmail,
|
|
78
|
-
rawHeaderText,
|
|
79
|
-
rawMessageId,
|
|
80
|
-
readInboundRawMime,
|
|
81
|
-
UnprocessableInboundEmailError,
|
|
82
|
-
} from "../mail/inbound";
|
|
12
|
+
import type { Unsubscription } from "../../shared/mail-feedback";
|
|
13
|
+
import type { JmapStateMessage } from "../jmap/push-types";
|
|
14
|
+
import type { DraftSenders } from "../mail/draft-sender";
|
|
83
15
|
import { listActiveMailboxSessions } from "../mail/mailbox-directory";
|
|
84
|
-
import {
|
|
85
|
-
import { emailListKey } from "../mail/message-view";
|
|
86
|
-
import { prepareOutboundDelivery } from "../mail/outbound-delivery";
|
|
16
|
+
import { hasNewRecipients } from "../mail/outbound-threading";
|
|
87
17
|
import { suggestParticipants } from "../mail/participants";
|
|
88
18
|
import type { ParticipantSource } from "../mail/participants";
|
|
89
|
-
import {
|
|
90
|
-
import {
|
|
91
|
-
import
|
|
92
|
-
import {
|
|
19
|
+
import type { RecipientFields } from "../mail/recipients";
|
|
20
|
+
import type { RuleInput } from "../mail/rules";
|
|
21
|
+
import { officePreviewKey } from "../mail/storage-keys";
|
|
22
|
+
import { storeEmail } from "./email-index";
|
|
23
|
+
import type { MailboxState } from "./folder-model";
|
|
93
24
|
import {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
import {
|
|
99
|
-
customFolderPredicate,
|
|
100
|
-
folderAggregateJoinPredicate,
|
|
101
|
-
systemFolderDefinitions,
|
|
102
|
-
systemFolderPredicate,
|
|
103
|
-
} from "./folder-model";
|
|
104
|
-
import type { MailboxState, SystemFolderType } from "./folder-model";
|
|
105
|
-
import { mergedPlacement, requestedPlacement } from "./import-placement";
|
|
106
|
-
import { readInboxCounts, writeInboxCounts } from "./inbox-counts";
|
|
25
|
+
advanceInboxCountsVersion,
|
|
26
|
+
readInboxCounts,
|
|
27
|
+
writeInboxCounts,
|
|
28
|
+
} from "./inbox-counts";
|
|
107
29
|
import type { InboxCounts } from "./inbox-counts";
|
|
108
|
-
import {
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
30
|
+
import { bumpJmapState, currentSeq, jmapState } from "./jmap-change-log";
|
|
31
|
+
import type { jmapChanges as jmapChangeLog } from "./jmap-change-log";
|
|
32
|
+
import { jmapEmails } from "./jmap-email-rows";
|
|
33
|
+
import type { MailboxChange } from "./jmap-placement";
|
|
34
|
+
import type { queryEmails as queryJmapEmails } from "./jmap-store";
|
|
35
|
+
import * as autoReplies from "./mailbox-auto-reply";
|
|
36
|
+
import * as mailboxBackup from "./mailbox-backup";
|
|
37
|
+
import * as mailboxDrafts from "./mailbox-drafts";
|
|
38
|
+
import * as mailboxFolders from "./mailbox-folders";
|
|
39
|
+
import * as mailboxImport from "./mailbox-import";
|
|
40
|
+
import * as mailboxInbound from "./mailbox-inbound";
|
|
41
|
+
import * as mailboxJmap from "./mailbox-jmap";
|
|
42
|
+
import * as mailboxOutbound from "./mailbox-outbound";
|
|
43
|
+
import * as mailboxRules from "./mailbox-rules";
|
|
44
|
+
import * as senderSafety from "./mailbox-senders";
|
|
45
|
+
import * as mailboxStorage from "./mailbox-storage";
|
|
46
|
+
import * as mailboxViews from "./mailbox-views";
|
|
117
47
|
import type {
|
|
118
|
-
EmailAiClassification,
|
|
119
|
-
EmailScreening,
|
|
120
48
|
MailboxAiConfiguration,
|
|
121
49
|
RecipientDeliveryStatus,
|
|
122
50
|
SenderIntel,
|
|
@@ -124,336 +52,76 @@ import type {
|
|
|
124
52
|
import {
|
|
125
53
|
dispatchOfficePreviewJobs,
|
|
126
54
|
hasPendingOfficePreviews,
|
|
127
|
-
insertOfficePreviewJobs,
|
|
128
55
|
nextOfficePreviewAttempt,
|
|
129
56
|
prepareOfficePreviews,
|
|
130
57
|
} from "./office-preview-jobs";
|
|
58
|
+
import {
|
|
59
|
+
blocksForLeavingSpam,
|
|
60
|
+
fileConversations,
|
|
61
|
+
placeConversations,
|
|
62
|
+
} from "./placement";
|
|
63
|
+
import type { RetentionFolder } from "./retention";
|
|
131
64
|
import {
|
|
132
65
|
conversations,
|
|
66
|
+
drafts,
|
|
133
67
|
emailReadStates,
|
|
68
|
+
pendingInbound,
|
|
69
|
+
pendingObjectDeletions,
|
|
134
70
|
emails,
|
|
135
71
|
folders,
|
|
136
72
|
systemFolderOrder,
|
|
137
|
-
|
|
138
|
-
pendingInbound,
|
|
139
|
-
pendingObjectDeletions,
|
|
73
|
+
senderFeedback,
|
|
140
74
|
senders,
|
|
141
75
|
unsubscriptions,
|
|
142
76
|
} from "./schema";
|
|
77
|
+
import type { NewEmail, NewFolder } from "./schema";
|
|
78
|
+
import { setSenderBlocked } from "./senders";
|
|
79
|
+
import {
|
|
80
|
+
withSpamUndo,
|
|
81
|
+
undoSpam,
|
|
82
|
+
nextSpamUndoExpiry,
|
|
83
|
+
expireSpamUndo,
|
|
84
|
+
} from "./spam-undo";
|
|
143
85
|
import type {
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
86
|
+
AutoReplyInput,
|
|
87
|
+
ConversationCursorPosition,
|
|
88
|
+
ConversationPage,
|
|
89
|
+
ConversationUpdate,
|
|
90
|
+
DraftInput,
|
|
91
|
+
ImportMessageInput,
|
|
92
|
+
ImportOriginal,
|
|
93
|
+
InboundDeliveryInput,
|
|
94
|
+
MailboxBackupSettings,
|
|
95
|
+
MailboxDatabase,
|
|
96
|
+
MailboxSocketAttachment,
|
|
97
|
+
SendingDraft,
|
|
98
|
+
TransportUpdate,
|
|
99
|
+
MailboxContext,
|
|
100
|
+
} from "./support";
|
|
150
101
|
import {
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
const schema = {
|
|
164
|
-
conversations,
|
|
165
|
-
emailReadStates,
|
|
166
|
-
emails,
|
|
167
|
-
folders,
|
|
168
|
-
mailboxAiConfiguration,
|
|
169
|
-
pendingInbound,
|
|
170
|
-
pendingObjectDeletions,
|
|
171
|
-
senders,
|
|
172
|
-
unsubscriptions,
|
|
173
|
-
};
|
|
174
|
-
|
|
175
|
-
type MailboxDatabase = DrizzleSqliteDODatabase<typeof schema>;
|
|
176
|
-
|
|
177
|
-
/** The change counter whose inbox counts D1 has (see `syncInboxCounts`). */
|
|
178
|
-
const COUNTS_VERSION_KEY = "inboxCountsVersion";
|
|
179
|
-
const INBOUND_ALARM_BATCH_SIZE = 1;
|
|
180
|
-
const OBJECT_DELETION_ALARM_BATCH_SIZE = 100;
|
|
181
|
-
const MAX_RETRY_DELAY_MS = 60 * 60 * 1000;
|
|
182
|
-
const MAX_INBOUND_RETRY_AGE_MS = 24 * 60 * 60 * 1000;
|
|
183
|
-
|
|
184
|
-
/** Attempts a delivery may end without an outcome (alarm killed) before it is stored unparsed. */
|
|
185
|
-
const MAX_UNFINISHED_INBOUND_ATTEMPTS = 3;
|
|
186
|
-
|
|
187
|
-
const ALARM_WAKE_DELAY_MS = 1000;
|
|
188
|
-
const PRESENCE_TTL_MS = 60_000;
|
|
189
|
-
const AI_CONFIGURATION_ID = "default";
|
|
190
|
-
|
|
191
|
-
/** Set while imported mail has not been announced (counts, realtime, JMAP state). */
|
|
192
|
-
const IMPORT_PENDING_KEY = "import:pending";
|
|
193
|
-
|
|
194
|
-
/** How long imported mail may wait to be announced when the importer does not finish. */
|
|
195
|
-
const IMPORT_ANNOUNCE_DELAY_MS = 15_000;
|
|
196
|
-
|
|
197
|
-
/** Browser sessions, authorized against their session on every update. */
|
|
198
|
-
const SESSION_SOCKET_TAG = "session";
|
|
199
|
-
|
|
200
|
-
/** JMAP EventSource streams held by the Worker; they receive the new state. */
|
|
201
|
-
const JMAP_SOCKET_TAG = "jmap";
|
|
202
|
-
|
|
203
|
-
/** What a browser session sends: whether its tab is visible. */
|
|
204
|
-
const visibilitySchema = z.enum([
|
|
205
|
-
"visible",
|
|
206
|
-
"hidden",
|
|
207
|
-
]) satisfies z.ZodType<MailboxRealtimeClientMessage>;
|
|
208
|
-
|
|
209
|
-
/** Who a session socket belongs to; it survives hibernation with the socket. */
|
|
210
|
-
const socketAttachmentSchema = z.object({
|
|
211
|
-
userId: z.string(),
|
|
212
|
-
sessionId: z.string(),
|
|
213
|
-
sessionTokenHash: z.string(),
|
|
214
|
-
visibility: visibilitySchema,
|
|
215
|
-
presenceUpdatedAt: z.number(),
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
type MailboxSocketAttachment = z.output<typeof socketAttachmentSchema>;
|
|
219
|
-
|
|
220
|
-
/** A session socket's attachment; null for other sockets (JMAP streams carry none). */
|
|
221
|
-
function socketAttachment(socket: WebSocket): MailboxSocketAttachment | null {
|
|
222
|
-
const attachment = socketAttachmentSchema.safeParse(
|
|
223
|
-
socket.deserializeAttachment()
|
|
224
|
-
);
|
|
225
|
-
|
|
226
|
-
return attachment.success ? attachment.data : null;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function errorMessage(cause: unknown) {
|
|
230
|
-
return cause instanceof Error ? cause.message : String(cause);
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
function retryDelay(attempts: number) {
|
|
234
|
-
return Math.min(
|
|
235
|
-
MAX_RETRY_DELAY_MS,
|
|
236
|
-
5000 * 2 ** Math.min(Math.max(attempts - 1, 0), 10)
|
|
237
|
-
);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/**
|
|
241
|
-
* The folder a conversation is listed in, as the app names it: its custom
|
|
242
|
-
* folder or Inbox while active, else Archive, Spam or Trash.
|
|
243
|
-
*/
|
|
244
|
-
function conversationFolder(place: {
|
|
245
|
-
mailboxState: MailboxState;
|
|
246
|
-
folderId: string | null;
|
|
247
|
-
}) {
|
|
248
|
-
if (place.mailboxState !== "active") return place.mailboxState;
|
|
249
|
-
|
|
250
|
-
return place.folderId ?? "inbox";
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/** Whether a delivery has been retried for as long as it may be. */
|
|
254
|
-
function isPastRetryAge(job: PendingInbound, now: number) {
|
|
255
|
-
return now - job.receivedAt.getTime() >= MAX_INBOUND_RETRY_AGE_MS;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
function stringListJson(values: string[]) {
|
|
259
|
-
return JSON.stringify([...new Set(values)]);
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
export type ConversationUpdate = {
|
|
263
|
-
mailboxState?: MailboxState;
|
|
264
|
-
folderId?: string | null;
|
|
265
|
-
};
|
|
266
|
-
|
|
267
|
-
export type ConversationCursorPosition = {
|
|
268
|
-
timelineAt: number;
|
|
269
|
-
emailId: string;
|
|
270
|
-
};
|
|
271
|
-
|
|
272
|
-
export type ConversationListItem = {
|
|
273
|
-
email: Email;
|
|
274
|
-
messageCount: number;
|
|
275
|
-
unreadCount: number;
|
|
276
|
-
hasIncoming: boolean;
|
|
277
|
-
};
|
|
278
|
-
|
|
279
|
-
export type SubmitOutgoingResult = {
|
|
280
|
-
outcome: "inserted" | "existing" | "conflict";
|
|
281
|
-
email: Email;
|
|
282
|
-
};
|
|
283
|
-
|
|
284
|
-
export type InboundDeliveryInput = {
|
|
285
|
-
id: string;
|
|
286
|
-
mailboxId: string;
|
|
287
|
-
rawObjectKey: string;
|
|
288
|
-
envelopeFrom: string;
|
|
289
|
-
envelopeTo: string;
|
|
290
|
-
/** Set when this is a member's copy of mail to a workspace mailing list. */
|
|
291
|
-
listAddress?: string;
|
|
292
|
-
receivedAt: number;
|
|
293
|
-
};
|
|
294
|
-
|
|
295
|
-
export type ImportMessageInput = {
|
|
296
|
-
/** The import's delivery id: the message is stored as `inboundMessageId(importId)`. */
|
|
297
|
-
importId: string;
|
|
298
|
-
/** Where the route stored the raw message. */
|
|
299
|
-
rawObjectKey: string;
|
|
300
|
-
/** The mailbox's own address, which tells sent mail from received. */
|
|
301
|
-
mailboxAddress: string;
|
|
302
|
-
/** When the message was received; the Date header (then now) without one. */
|
|
303
|
-
receivedAt: number | null;
|
|
304
|
-
placement: ImportPlacement;
|
|
305
|
-
/** A custom folder (by name, created when missing) for a message in the Inbox. */
|
|
306
|
-
folderName: string | null;
|
|
307
|
-
/** The people a received message is read for. */
|
|
308
|
-
seenBy: string[];
|
|
309
|
-
/** The conversation the importer's thread key names; null threads by Message-ID headers. */
|
|
310
|
-
conversationId: string | null;
|
|
311
|
-
/** Null decides by the From address. */
|
|
312
|
-
direction: "incoming" | "outgoing" | null;
|
|
313
|
-
};
|
|
314
|
-
|
|
315
|
-
export type ImportMessageResult =
|
|
316
|
-
| {
|
|
317
|
-
status: "imported";
|
|
318
|
-
id: string;
|
|
319
|
-
conversationId: string;
|
|
320
|
-
/** Why the requested folder was not used, if it was not. */
|
|
321
|
-
folderSkipped: "limit" | "invalid" | null;
|
|
322
|
-
}
|
|
323
|
-
| { status: "duplicate"; id: string; conversationId: string }
|
|
324
|
-
| { status: "unprocessable"; reason: string };
|
|
325
|
-
|
|
326
|
-
function clampText(value: string | null | undefined) {
|
|
327
|
-
return value && value.length > MAX_IMPORTED_TEXT_CHARACTERS
|
|
328
|
-
? value.slice(0, MAX_IMPORTED_TEXT_CHARACTERS)
|
|
329
|
-
: (value ?? null);
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
/** The Date header of a raw message, in ms, if it parses. */
|
|
333
|
-
function headerDate(rawMime: ArrayBuffer) {
|
|
334
|
-
const value = headerValues(rawHeaderText(rawMime), "date")[0];
|
|
335
|
-
const time = value ? Date.parse(value) : Number.NaN;
|
|
336
|
-
|
|
337
|
-
return Number.isFinite(time) ? time : null;
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
export type FolderListItem = {
|
|
341
|
-
id: string;
|
|
342
|
-
name: string;
|
|
343
|
-
kind: "system" | "custom";
|
|
344
|
-
systemType: SystemFolderType | null;
|
|
345
|
-
sortOrder: number;
|
|
346
|
-
totalCount: number;
|
|
347
|
-
unreadCount: number;
|
|
348
|
-
};
|
|
349
|
-
|
|
350
|
-
type MailFolder =
|
|
351
|
-
| (FolderRecord & { kind: "custom"; systemType: null })
|
|
352
|
-
| {
|
|
353
|
-
id: string;
|
|
354
|
-
name: string;
|
|
355
|
-
kind: "system";
|
|
356
|
-
systemType: SystemFolderType;
|
|
357
|
-
sortOrder: number;
|
|
358
|
-
};
|
|
359
|
-
|
|
360
|
-
type ConversationRow = {
|
|
361
|
-
email_id: string;
|
|
362
|
-
timeline_at: number;
|
|
363
|
-
message_count: number;
|
|
364
|
-
unread_count: number;
|
|
365
|
-
has_incoming: number;
|
|
366
|
-
};
|
|
367
|
-
|
|
368
|
-
type ConversationSnapshotCountRow = {
|
|
369
|
-
message_count: number;
|
|
370
|
-
unread_count: number;
|
|
371
|
-
};
|
|
372
|
-
|
|
373
|
-
type FolderCountRow = {
|
|
374
|
-
total_count: number;
|
|
375
|
-
unread_count: number;
|
|
376
|
-
};
|
|
377
|
-
|
|
378
|
-
type FolderListRow = {
|
|
379
|
-
id: string;
|
|
380
|
-
name: string;
|
|
381
|
-
kind: "system" | "custom";
|
|
382
|
-
system_type: SystemFolderType | null;
|
|
383
|
-
sort_order: number;
|
|
384
|
-
total_count: number;
|
|
385
|
-
unread_count: number;
|
|
386
|
-
};
|
|
387
|
-
|
|
388
|
-
export type FolderCounts = {
|
|
389
|
-
totalCount: number;
|
|
390
|
-
unreadCount: number;
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
function folderMembership(folder: MailFolder) {
|
|
394
|
-
if (folder.kind === "custom") {
|
|
395
|
-
return {
|
|
396
|
-
predicate: `
|
|
397
|
-
c.folder_id = ?
|
|
398
|
-
and ${customFolderPredicate("c")}
|
|
399
|
-
`,
|
|
400
|
-
bindings: [folder.id],
|
|
401
|
-
};
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
return {
|
|
405
|
-
predicate: systemFolderPredicate(folder.systemType, "c"),
|
|
406
|
-
bindings: [],
|
|
407
|
-
};
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
const FOLDER_AGGREGATE_JOIN_PREDICATE = folderAggregateJoinPredicate(
|
|
411
|
-
"folder",
|
|
412
|
-
"conversation"
|
|
413
|
-
);
|
|
414
|
-
|
|
415
|
-
export type TransportUpdate = {
|
|
416
|
-
state: Email["transportState"];
|
|
417
|
-
messageIdHeader?: string;
|
|
418
|
-
error?: string | null;
|
|
419
|
-
};
|
|
420
|
-
|
|
421
|
-
/** Where an incoming message lands, decided before it is stored. */
|
|
422
|
-
type InboundPlacement = {
|
|
423
|
-
state: "spam" | null;
|
|
424
|
-
folderId: string | null;
|
|
425
|
-
};
|
|
426
|
-
|
|
427
|
-
type InboundScreening = {
|
|
428
|
-
block: SenderBlock | null;
|
|
429
|
-
trusted: boolean;
|
|
430
|
-
};
|
|
431
|
-
|
|
432
|
-
const LIKE_ESCAPE = (value: string) =>
|
|
433
|
-
value.replaceAll(/[\\%_]/gu, (char) => `\\${char}`);
|
|
434
|
-
|
|
435
|
-
/** SQL predicate on a lowercased address expression for a block pattern. */
|
|
436
|
-
function blockPatternPredicate(expression: string, pattern: string) {
|
|
437
|
-
if (!pattern.startsWith("@")) {
|
|
438
|
-
return { sql: `${expression} = ?`, bindings: [pattern] };
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
const domain = LIKE_ESCAPE(pattern.slice(1));
|
|
442
|
-
|
|
443
|
-
return {
|
|
444
|
-
sql: `(${expression} like ? escape '\\' or ${expression} like ? escape '\\')`,
|
|
445
|
-
bindings: [`%@${domain}`, `%.${domain}`],
|
|
446
|
-
};
|
|
447
|
-
}
|
|
102
|
+
ALARM_WAKE_DELAY_MS,
|
|
103
|
+
COUNTS_VERSION_KEY,
|
|
104
|
+
WEB_VERSION_KEY,
|
|
105
|
+
IMPORT_PENDING_KEY,
|
|
106
|
+
JMAP_SOCKET_TAG,
|
|
107
|
+
PRESENCE_TTL_MS,
|
|
108
|
+
SESSION_SOCKET_TAG,
|
|
109
|
+
folderMembership,
|
|
110
|
+
schema,
|
|
111
|
+
socketAttachment,
|
|
112
|
+
visibilitySchema,
|
|
113
|
+
} from "./support";
|
|
448
114
|
|
|
449
115
|
export class MailboxDO extends DurableObject<Env> {
|
|
450
116
|
private readonly db: MailboxDatabase;
|
|
451
117
|
private readonly state: DurableObjectState;
|
|
452
|
-
private readonly
|
|
118
|
+
private readonly context: MailboxContext;
|
|
119
|
+
/** Messages being handed to Email Sending now; one send each at a time. */
|
|
120
|
+
private readonly sending = new Set<string>();
|
|
453
121
|
private recentParticipantSources: ParticipantSource[] | null = null;
|
|
454
122
|
/** The running D1 write of the inbox counts; see `syncInboxCounts`. */
|
|
455
123
|
private countsWrite: Promise<void> | null = null;
|
|
456
|
-
private
|
|
124
|
+
private pendingCounts: "recount" | "version" | null = null;
|
|
457
125
|
/** What the last successful write stored, so the next writes only what changed. */
|
|
458
126
|
private writtenCounts: InboxCounts | null = null;
|
|
459
127
|
/** The D1 bookmark after that write; realtime messages pass it on. */
|
|
@@ -467,8 +135,30 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
467
135
|
constructor(ctx: DurableObjectState, env: Env) {
|
|
468
136
|
super(ctx, env);
|
|
469
137
|
this.state = ctx;
|
|
470
|
-
this.bindings = env;
|
|
471
138
|
this.db = drizzle(ctx.storage, { schema });
|
|
139
|
+
|
|
140
|
+
this.context = {
|
|
141
|
+
db: this.db,
|
|
142
|
+
state: ctx,
|
|
143
|
+
env,
|
|
144
|
+
announce: (options) => this.announce(options),
|
|
145
|
+
scheduleAlarm: (at) => this.scheduleAlarm(at),
|
|
146
|
+
scheduleRetention: () => this.scheduleRetention(),
|
|
147
|
+
getEmail: (id) => this.getEmail(id),
|
|
148
|
+
resolveParent: (inReplyTo, references) =>
|
|
149
|
+
this.resolveParent(inReplyTo, references),
|
|
150
|
+
forgetParticipants: () => {
|
|
151
|
+
this.recentParticipantSources = null;
|
|
152
|
+
},
|
|
153
|
+
getEmailByMessageId: (messageIdHeader) =>
|
|
154
|
+
this.getEmailByMessageId(messageIdHeader),
|
|
155
|
+
classificationModel: () => this.classificationModel(),
|
|
156
|
+
noteAttemptAlarm: (at) => {
|
|
157
|
+
this.attemptAlarmAt = at;
|
|
158
|
+
},
|
|
159
|
+
version: () => this.version(),
|
|
160
|
+
sending: this.sending,
|
|
161
|
+
};
|
|
472
162
|
ctx.blockConcurrencyWhile(async () => {
|
|
473
163
|
await migrate(this.db, migrations);
|
|
474
164
|
|
|
@@ -560,13 +250,16 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
560
250
|
await this.state.storage.deleteAll();
|
|
561
251
|
}
|
|
562
252
|
|
|
563
|
-
async
|
|
253
|
+
async pushDestination(messageId: string, userId: string) {
|
|
564
254
|
const messageState = this.db
|
|
565
255
|
.select({
|
|
566
|
-
|
|
256
|
+
conversationId: conversations.id,
|
|
257
|
+
mailboxState: conversations.mailboxState,
|
|
258
|
+
folderId: conversations.folderId,
|
|
567
259
|
readByUserId: emailReadStates.userId,
|
|
568
260
|
})
|
|
569
261
|
.from(emails)
|
|
262
|
+
.innerJoin(conversations, eq(emails.conversationId, conversations.id))
|
|
570
263
|
.leftJoin(
|
|
571
264
|
emailReadStates,
|
|
572
265
|
and(
|
|
@@ -577,10 +270,20 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
577
270
|
.where(eq(emails.id, messageId))
|
|
578
271
|
.get();
|
|
579
272
|
|
|
580
|
-
if (
|
|
273
|
+
if (messageState?.mailboxState !== "active" || messageState.readByUserId) {
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
|
|
581
277
|
const visibleAfter = Date.now() - PRESENCE_TTL_MS;
|
|
582
278
|
|
|
583
|
-
|
|
279
|
+
if ((await this.authorizedSockets({ userId, visibleAfter })).length) {
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
return {
|
|
284
|
+
conversationId: messageState.conversationId,
|
|
285
|
+
folder: conversationFolder(messageState),
|
|
286
|
+
};
|
|
584
287
|
}
|
|
585
288
|
|
|
586
289
|
private async authorizedSockets(filter?: {
|
|
@@ -627,7 +330,7 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
627
330
|
];
|
|
628
331
|
|
|
629
332
|
const validSessions = await listActiveMailboxSessions(
|
|
630
|
-
this.
|
|
333
|
+
this.env.DB,
|
|
631
334
|
mailboxId,
|
|
632
335
|
sessionIds,
|
|
633
336
|
Date.now()
|
|
@@ -695,10 +398,14 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
695
398
|
/**
|
|
696
399
|
* The change counter that realtime updates carry (`update:<version>`).
|
|
697
400
|
* Reads return it so clients can tell whether their data already has a
|
|
698
|
-
* change they are told about.
|
|
401
|
+
* change they are told about. It moves only with an announcement web
|
|
402
|
+
* clients hear: a change only JMAP sees (a draft's autosave) would make
|
|
403
|
+
* a client's next own change look like someone else's.
|
|
699
404
|
*/
|
|
700
405
|
private version() {
|
|
701
|
-
return
|
|
406
|
+
return (
|
|
407
|
+
this.state.storage.kv.get<number>(WEB_VERSION_KEY) ?? currentSeq(this.db)
|
|
408
|
+
);
|
|
702
409
|
}
|
|
703
410
|
|
|
704
411
|
/**
|
|
@@ -708,8 +415,11 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
708
415
|
* at the latest counts. Settles once D1 has them (failures are logged and
|
|
709
416
|
* retried by the next change or start).
|
|
710
417
|
*/
|
|
711
|
-
private syncInboxCounts()
|
|
712
|
-
|
|
418
|
+
private syncInboxCounts(recount = true) {
|
|
419
|
+
// A version-only announcement must never downgrade a pending recount.
|
|
420
|
+
this.pendingCounts = recount
|
|
421
|
+
? "recount"
|
|
422
|
+
: (this.pendingCounts ?? "version");
|
|
713
423
|
|
|
714
424
|
if (!this.countsWrite) {
|
|
715
425
|
// Started after the assignment, so its `finally` clears this one.
|
|
@@ -724,24 +434,23 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
724
434
|
const mailboxId = this.state.id.name;
|
|
725
435
|
|
|
726
436
|
try {
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
while (
|
|
730
|
-
this.
|
|
437
|
+
if (!mailboxId) return;
|
|
438
|
+
|
|
439
|
+
while (this.pendingCounts) {
|
|
440
|
+
const recount = this.pendingCounts === "recount";
|
|
441
|
+
this.pendingCounts = null;
|
|
731
442
|
const version = this.version();
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
this.countsBookmark = await writeInboxCounts(this.bindings.DB, {
|
|
443
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- commit versions to D1 in order
|
|
444
|
+
this.countsBookmark = await this.writeInboxVersion(
|
|
735
445
|
mailboxId,
|
|
736
446
|
version,
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
});
|
|
740
|
-
this.writtenCounts = counts;
|
|
447
|
+
recount
|
|
448
|
+
);
|
|
741
449
|
this.state.storage.kv.put(COUNTS_VERSION_KEY, version);
|
|
742
450
|
}
|
|
743
451
|
} catch (error) {
|
|
744
452
|
// The stored version stays behind, so the next start writes them again.
|
|
453
|
+
this.pendingCounts = "recount";
|
|
745
454
|
this.writtenCounts = null;
|
|
746
455
|
console.error("Could not write mailbox counts to D1", error);
|
|
747
456
|
} finally {
|
|
@@ -749,27 +458,73 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
749
458
|
}
|
|
750
459
|
}
|
|
751
460
|
|
|
752
|
-
private
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
461
|
+
private async writeInboxVersion(
|
|
462
|
+
mailboxId: string,
|
|
463
|
+
version: number,
|
|
464
|
+
recount: boolean
|
|
465
|
+
) {
|
|
466
|
+
if (!recount) {
|
|
467
|
+
const advanced = await advanceInboxCountsVersion(
|
|
468
|
+
this.env.DB,
|
|
469
|
+
mailboxId,
|
|
470
|
+
version
|
|
471
|
+
);
|
|
472
|
+
|
|
473
|
+
if (advanced) return advanced.bookmark;
|
|
474
|
+
// The row is missing in D1. Rebuild the counts and all per-person rows.
|
|
475
|
+
this.writtenCounts = null;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const counts = readInboxCounts(this.db);
|
|
479
|
+
|
|
480
|
+
const bookmark = await writeInboxCounts(this.env.DB, {
|
|
481
|
+
mailboxId,
|
|
482
|
+
version,
|
|
483
|
+
counts,
|
|
484
|
+
previous: this.writtenCounts,
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
this.writtenCounts = counts;
|
|
488
|
+
|
|
489
|
+
return bookmark;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** See `MailboxContext.announce`. */
|
|
493
|
+
private announce({
|
|
494
|
+
web = true,
|
|
495
|
+
push = true,
|
|
496
|
+
delivered = false,
|
|
497
|
+
inboxChanged = true,
|
|
498
|
+
} = {}) {
|
|
499
|
+
bumpJmapState(this.db);
|
|
500
|
+
let countsWritten = Promise.resolve();
|
|
501
|
+
|
|
502
|
+
if (web) {
|
|
503
|
+
this.state.storage.kv.put(WEB_VERSION_KEY, currentSeq(this.db));
|
|
504
|
+
countsWritten = this.syncInboxCounts(inboxChanged);
|
|
505
|
+
this.state.waitUntil(
|
|
506
|
+
this.broadcastUpdate(countsWritten).catch((error) => {
|
|
507
|
+
console.error("Could not authorize realtime delivery", error);
|
|
508
|
+
})
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
this.announceJmapState(push, delivered);
|
|
513
|
+
|
|
514
|
+
return countsWritten;
|
|
761
515
|
}
|
|
762
516
|
|
|
763
517
|
/** Tells JMAP EventSource streams and (unless `push` is false) push subscribers the new state. */
|
|
764
|
-
private announceJmapState(push
|
|
518
|
+
private announceJmapState(push: boolean, delivered: boolean) {
|
|
765
519
|
const mailboxId = this.state.id.name;
|
|
766
520
|
|
|
767
521
|
if (!mailboxId) return;
|
|
768
|
-
const state = jmapState(this.
|
|
522
|
+
const state = jmapState(this.db);
|
|
523
|
+
const message: JmapStateMessage = { state, delivered };
|
|
769
524
|
|
|
770
525
|
for (const socket of this.state.getWebSockets(JMAP_SOCKET_TAG)) {
|
|
771
526
|
try {
|
|
772
|
-
socket.send(
|
|
527
|
+
socket.send(JSON.stringify(message));
|
|
773
528
|
} catch {
|
|
774
529
|
socket.close(1011, "Could not deliver realtime event");
|
|
775
530
|
}
|
|
@@ -781,534 +536,244 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
781
536
|
type: "jmap-state",
|
|
782
537
|
mailboxId,
|
|
783
538
|
state,
|
|
539
|
+
delivered,
|
|
784
540
|
occurredAt: Date.now(),
|
|
785
541
|
};
|
|
786
542
|
|
|
787
543
|
this.state.waitUntil(
|
|
788
|
-
this.
|
|
544
|
+
this.env.PUSH_NOTIFICATIONS.send(job).catch((error) => {
|
|
789
545
|
console.error("Could not queue JMAP push", error);
|
|
790
546
|
})
|
|
791
547
|
);
|
|
792
548
|
}
|
|
793
549
|
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
550
|
+
listConversations(
|
|
551
|
+
userId: string,
|
|
552
|
+
folderId: string,
|
|
553
|
+
limit: number,
|
|
554
|
+
cursor: ConversationCursorPosition | null,
|
|
555
|
+
search: string | undefined,
|
|
556
|
+
unreadOnly = false,
|
|
557
|
+
draftSenders?: DraftSenders
|
|
558
|
+
) {
|
|
559
|
+
const page: ConversationPage | null = mailboxViews.listConversations(
|
|
560
|
+
this.context,
|
|
561
|
+
userId,
|
|
562
|
+
folderId,
|
|
563
|
+
limit,
|
|
564
|
+
cursor,
|
|
565
|
+
search,
|
|
566
|
+
unreadOnly,
|
|
567
|
+
draftSenders
|
|
568
|
+
);
|
|
807
569
|
|
|
808
|
-
return
|
|
570
|
+
return page;
|
|
809
571
|
}
|
|
810
572
|
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
cause: unknown
|
|
815
|
-
) {
|
|
816
|
-
if (isPastRetryAge(job, now)) {
|
|
817
|
-
this.db.delete(pendingInbound).where(eq(pendingInbound.id, job.id)).run();
|
|
818
|
-
console.error(
|
|
819
|
-
`Stopped retrying notification for inbound delivery ${job.id}`,
|
|
820
|
-
cause
|
|
821
|
-
);
|
|
822
|
-
|
|
823
|
-
return;
|
|
824
|
-
}
|
|
573
|
+
getFolder(id: string) {
|
|
574
|
+
return mailboxFolders.getFolder(this.context, id);
|
|
575
|
+
}
|
|
825
576
|
|
|
826
|
-
|
|
827
|
-
this.
|
|
828
|
-
.update(pendingInbound)
|
|
829
|
-
.set({
|
|
830
|
-
attempts,
|
|
831
|
-
nextAttemptAt: new Date(now + retryDelay(attempts)),
|
|
832
|
-
})
|
|
833
|
-
.where(eq(pendingInbound.id, job.id))
|
|
834
|
-
.run();
|
|
835
|
-
console.error(
|
|
836
|
-
`Could not queue notification for inbound delivery ${job.id}`,
|
|
837
|
-
cause
|
|
838
|
-
);
|
|
577
|
+
createFolder(id: string, name: string) {
|
|
578
|
+
return mailboxFolders.createFolder(this.context, id, name);
|
|
839
579
|
}
|
|
840
580
|
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
now: number,
|
|
845
|
-
announce: boolean
|
|
846
|
-
) {
|
|
847
|
-
try {
|
|
848
|
-
const mailboxId = this.state.id.name ?? "unknown-mailbox";
|
|
849
|
-
deferWebhookTask(
|
|
850
|
-
(task) => this.state.waitUntil(task),
|
|
851
|
-
() =>
|
|
852
|
-
queueWebhookEvent(this.bindings, {
|
|
853
|
-
eventId: emailWebhookEventId(
|
|
854
|
-
EMAIL_RECEIVED_EVENT,
|
|
855
|
-
mailboxId,
|
|
856
|
-
email.id
|
|
857
|
-
),
|
|
858
|
-
eventType: EMAIL_RECEIVED_EVENT,
|
|
859
|
-
occurredAt: email.timelineAt.getTime(),
|
|
860
|
-
source: {
|
|
861
|
-
kind: EMAIL_WEBHOOK_SOURCE,
|
|
862
|
-
mailboxId,
|
|
863
|
-
messageId: email.id,
|
|
864
|
-
},
|
|
865
|
-
})
|
|
866
|
-
);
|
|
581
|
+
renameFolder(id: string, name: string) {
|
|
582
|
+
return mailboxFolders.renameFolder(this.context, id, name);
|
|
583
|
+
}
|
|
867
584
|
|
|
868
|
-
|
|
585
|
+
deleteFolder(id: string) {
|
|
586
|
+
return mailboxFolders.deleteFolder(this.context, id);
|
|
587
|
+
}
|
|
869
588
|
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
.where(eq(conversations.id, email.conversationId))
|
|
874
|
-
.all()[0];
|
|
589
|
+
reorderFolders(folderIds: string[]) {
|
|
590
|
+
return mailboxFolders.reorderFolders(this.context, folderIds);
|
|
591
|
+
}
|
|
875
592
|
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
593
|
+
listRules() {
|
|
594
|
+
return mailboxRules.listRules(this.context);
|
|
595
|
+
}
|
|
879
596
|
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
this.retryStoredInboundNotification(job, now, error);
|
|
883
|
-
}
|
|
597
|
+
createRule(input: RuleInput) {
|
|
598
|
+
return mailboxRules.createRule(this.context, input);
|
|
884
599
|
}
|
|
885
600
|
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
limit: number,
|
|
890
|
-
cursor: ConversationCursorPosition | null,
|
|
891
|
-
search: string | undefined,
|
|
892
|
-
unreadOnly = false
|
|
893
|
-
) {
|
|
894
|
-
const folder = this.getFolder(folderId);
|
|
601
|
+
setRuleEnabled(id: string, enabled: boolean) {
|
|
602
|
+
return mailboxRules.setRuleEnabled(this.context, id, enabled);
|
|
603
|
+
}
|
|
895
604
|
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
605
|
+
updateRule(id: string, input: Omit<RuleInput, "enabled">) {
|
|
606
|
+
return mailboxRules.updateRule(this.context, id, input);
|
|
607
|
+
}
|
|
899
608
|
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
609
|
+
deleteRule(id: string) {
|
|
610
|
+
return mailboxRules.deleteRule(this.context, id);
|
|
611
|
+
}
|
|
903
612
|
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
if (unreadOnly) {
|
|
908
|
-
predicates.push(`exists (
|
|
909
|
-
select 1
|
|
910
|
-
from emails unread_message
|
|
911
|
-
where unread_message.conversation_id = c.id
|
|
912
|
-
and unread_message.direction = 'incoming'
|
|
913
|
-
and not exists (
|
|
914
|
-
select 1
|
|
915
|
-
from email_read_states unread_state
|
|
916
|
-
where unread_state.user_id = ?
|
|
917
|
-
and unread_state.email_id = unread_message.id
|
|
918
|
-
)
|
|
919
|
-
)`);
|
|
920
|
-
bindings.push(userId);
|
|
921
|
-
}
|
|
613
|
+
reorderRules(ruleIds: string[]) {
|
|
614
|
+
return mailboxRules.reorderRules(this.context, ruleIds);
|
|
615
|
+
}
|
|
922
616
|
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
predicates.push(`c.id in (
|
|
927
|
-
select conversation_id
|
|
928
|
-
from email_search
|
|
929
|
-
where email_search match ?
|
|
930
|
-
)`);
|
|
931
|
-
bindings.push(searchQuery);
|
|
932
|
-
}
|
|
617
|
+
testRule(rule: Pick<RuleInput, "match" | "conditions">) {
|
|
618
|
+
return mailboxRules.testRule(this.context, rule);
|
|
619
|
+
}
|
|
933
620
|
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
);
|
|
938
|
-
bindings.push(cursor.timelineAt, cursor.timelineAt, cursor.emailId);
|
|
939
|
-
}
|
|
621
|
+
getMailboxAiSettings() {
|
|
622
|
+
return mailboxRules.getMailboxAiSettings(this.context);
|
|
623
|
+
}
|
|
940
624
|
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
.exec<ConversationRow>(
|
|
945
|
-
`
|
|
946
|
-
select
|
|
947
|
-
c.latest_email_id as email_id,
|
|
948
|
-
c.timeline_at,
|
|
949
|
-
c.has_incoming,
|
|
950
|
-
(
|
|
951
|
-
select count(*)
|
|
952
|
-
from emails message
|
|
953
|
-
where message.conversation_id = c.id
|
|
954
|
-
) as message_count,
|
|
955
|
-
(
|
|
956
|
-
select count(*)
|
|
957
|
-
from emails message
|
|
958
|
-
where message.conversation_id = c.id
|
|
959
|
-
and message.direction = 'incoming'
|
|
960
|
-
and not exists (
|
|
961
|
-
select 1
|
|
962
|
-
from email_read_states read_state
|
|
963
|
-
where read_state.user_id = ?
|
|
964
|
-
and read_state.email_id = message.id
|
|
965
|
-
)
|
|
966
|
-
) as unread_count
|
|
967
|
-
from conversations c
|
|
968
|
-
where ${predicates.join(" and ")}
|
|
969
|
-
order by c.timeline_at desc, c.latest_email_id desc
|
|
970
|
-
limit ?
|
|
971
|
-
`,
|
|
972
|
-
userId,
|
|
973
|
-
...bindings
|
|
974
|
-
)
|
|
975
|
-
.toArray();
|
|
976
|
-
|
|
977
|
-
const pageRows = rows.slice(0, limit);
|
|
978
|
-
const emailIds = pageRows.map((row) => row.email_id);
|
|
979
|
-
|
|
980
|
-
const emailRows = emailIds.length
|
|
981
|
-
? this.db.select().from(emails).where(inArray(emails.id, emailIds)).all()
|
|
982
|
-
: [];
|
|
983
|
-
|
|
984
|
-
const emailsById = new Map(emailRows.map((email) => [email.id, email]));
|
|
985
|
-
|
|
986
|
-
const items = pageRows.flatMap((row): ConversationListItem[] => {
|
|
987
|
-
const email = emailsById.get(row.email_id);
|
|
988
|
-
|
|
989
|
-
return email
|
|
990
|
-
? [
|
|
991
|
-
{
|
|
992
|
-
email,
|
|
993
|
-
messageCount: Number(row.message_count),
|
|
994
|
-
unreadCount: Number(row.unread_count),
|
|
995
|
-
hasIncoming: Boolean(row.has_incoming),
|
|
996
|
-
},
|
|
997
|
-
]
|
|
998
|
-
: [];
|
|
999
|
-
});
|
|
625
|
+
setMailboxAiConfiguration(configuration: MailboxAiConfiguration) {
|
|
626
|
+
return mailboxRules.setMailboxAiConfiguration(this.context, configuration);
|
|
627
|
+
}
|
|
1000
628
|
|
|
1001
|
-
|
|
629
|
+
listDrafts(userId: string) {
|
|
630
|
+
return mailboxDrafts.listDrafts(this.context, userId);
|
|
631
|
+
}
|
|
1002
632
|
|
|
633
|
+
/** The person's drafts with the mailbox version they reflect, for clients that refresh by it. */
|
|
634
|
+
versionedDrafts(userId: string) {
|
|
1003
635
|
return {
|
|
1004
|
-
|
|
1005
|
-
next:
|
|
1006
|
-
rows.length > limit && last
|
|
1007
|
-
? { timelineAt: Number(last.timeline_at), emailId: last.email_id }
|
|
1008
|
-
: null,
|
|
636
|
+
drafts: mailboxDrafts.listDrafts(this.context, userId),
|
|
1009
637
|
version: this.version(),
|
|
1010
638
|
};
|
|
1011
639
|
}
|
|
1012
640
|
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
const stored = new Map(
|
|
1016
|
-
this.db
|
|
1017
|
-
.select()
|
|
1018
|
-
.from(systemFolderOrder)
|
|
1019
|
-
.all()
|
|
1020
|
-
.map((row) => [row.folderId, row.sortOrder])
|
|
1021
|
-
);
|
|
1022
|
-
|
|
1023
|
-
return systemFolderDefinitions.map((folder) => ({
|
|
1024
|
-
...folder,
|
|
1025
|
-
sortOrder:
|
|
1026
|
-
folder.id === "inbox" ? 0 : (stored.get(folder.id) ?? folder.sortOrder),
|
|
1027
|
-
}));
|
|
641
|
+
getDraft(userId: string, id: string) {
|
|
642
|
+
return mailboxDrafts.getDraft(this.context, userId, id);
|
|
1028
643
|
}
|
|
1029
644
|
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
if (system) {
|
|
1034
|
-
return {
|
|
1035
|
-
...system,
|
|
1036
|
-
kind: "system",
|
|
1037
|
-
};
|
|
1038
|
-
}
|
|
1039
|
-
|
|
1040
|
-
const custom = this.db
|
|
1041
|
-
.select()
|
|
1042
|
-
.from(folders)
|
|
1043
|
-
.where(eq(folders.id, id))
|
|
1044
|
-
.all()[0];
|
|
1045
|
-
|
|
1046
|
-
return custom ? { ...custom, kind: "custom", systemType: null } : null;
|
|
645
|
+
draftForEditor(userId: string, id: string) {
|
|
646
|
+
return mailboxDrafts.draftForEditor(this.context, userId, id);
|
|
1047
647
|
}
|
|
1048
648
|
|
|
1049
|
-
|
|
1050
|
-
const normalized = name.toLocaleLowerCase("en-US");
|
|
1051
|
-
|
|
649
|
+
getDraftAttachments(userId: string, id: string) {
|
|
1052
650
|
return (
|
|
1053
|
-
systemFolderDefinitions.some(
|
|
1054
|
-
(folder) => folder.name.toLocaleLowerCase("en-US") === normalized
|
|
1055
|
-
) ||
|
|
1056
651
|
this.db
|
|
1057
|
-
.select({
|
|
1058
|
-
.from(
|
|
1059
|
-
.
|
|
1060
|
-
.
|
|
1061
|
-
(folder) =>
|
|
1062
|
-
folder.id !== excludingId &&
|
|
1063
|
-
folder.name.toLocaleLowerCase("en-US") === normalized
|
|
1064
|
-
)
|
|
652
|
+
.select({ files: drafts.attachments })
|
|
653
|
+
.from(drafts)
|
|
654
|
+
.where(and(eq(drafts.userId, userId), eq(drafts.id, id)))
|
|
655
|
+
.get()?.files ?? []
|
|
1065
656
|
);
|
|
1066
657
|
}
|
|
1067
658
|
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
659
|
+
saveDraft(
|
|
660
|
+
userId: string,
|
|
661
|
+
input: DraftInput,
|
|
662
|
+
expectedVersion: number,
|
|
663
|
+
copiedKeys: string[] = []
|
|
664
|
+
) {
|
|
665
|
+
return mailboxDrafts.saveDraft(
|
|
666
|
+
this.context,
|
|
667
|
+
userId,
|
|
668
|
+
input,
|
|
669
|
+
expectedVersion,
|
|
670
|
+
copiedKeys
|
|
671
|
+
);
|
|
1074
672
|
}
|
|
1075
673
|
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
if (!normalizedName || normalizedName.length > 80) {
|
|
1080
|
-
return { status: "invalid" as const };
|
|
1081
|
-
}
|
|
1082
|
-
|
|
1083
|
-
const existing = this.db
|
|
1084
|
-
.select({ id: folders.id, sortOrder: folders.sortOrder })
|
|
1085
|
-
.from(folders)
|
|
1086
|
-
.all();
|
|
1087
|
-
|
|
1088
|
-
if (existing.length >= MAX_CUSTOM_FOLDER_COUNT) {
|
|
1089
|
-
return { status: "limit" as const };
|
|
1090
|
-
}
|
|
1091
|
-
|
|
1092
|
-
if (this.folderNameTaken(normalizedName)) {
|
|
1093
|
-
return { status: "conflict" as const };
|
|
1094
|
-
}
|
|
674
|
+
discardDrafts(userId: string, selected: { id: string; version: number }[]) {
|
|
675
|
+
return mailboxDrafts.discardDrafts(this.context, userId, selected);
|
|
676
|
+
}
|
|
1095
677
|
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
...this.systemFolders().map((item) => item.sortOrder)
|
|
1100
|
-
);
|
|
678
|
+
deleteDraft(userId: string, id: string, version?: number) {
|
|
679
|
+
return mailboxDrafts.deleteDraft(this.context, userId, id, version);
|
|
680
|
+
}
|
|
1101
681
|
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
.
|
|
1105
|
-
.
|
|
682
|
+
holdsDraftFile(userId: string, key: string) {
|
|
683
|
+
return !!this.db
|
|
684
|
+
.select({ id: drafts.id })
|
|
685
|
+
.from(drafts)
|
|
686
|
+
.where(
|
|
687
|
+
and(
|
|
688
|
+
eq(drafts.userId, userId),
|
|
689
|
+
sql`exists (
|
|
690
|
+
select 1 from json_each(${drafts.attachments}) where value ->> 'r2Key' = ${key}
|
|
691
|
+
)`
|
|
692
|
+
)
|
|
693
|
+
)
|
|
694
|
+
.limit(1)
|
|
1106
695
|
.get();
|
|
696
|
+
}
|
|
1107
697
|
|
|
1108
|
-
|
|
698
|
+
forgetDraftFiles(objectKeys: string[]) {
|
|
699
|
+
return mailboxDrafts.forgetDraftFiles(this.context, objectKeys);
|
|
1109
700
|
}
|
|
1110
701
|
|
|
1111
|
-
|
|
1112
|
-
|
|
702
|
+
jmapState() {
|
|
703
|
+
return mailboxJmap.jmapState(this.context);
|
|
704
|
+
}
|
|
1113
705
|
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
706
|
+
jmapChanges(input: Parameters<typeof jmapChangeLog>[1]) {
|
|
707
|
+
return mailboxJmap.jmapChanges(this.context, input);
|
|
708
|
+
}
|
|
1117
709
|
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
) {
|
|
1122
|
-
return { status: "not_found" as const };
|
|
1123
|
-
}
|
|
710
|
+
jmapMailboxes(userId: string, withCounts = true) {
|
|
711
|
+
return mailboxJmap.jmapMailboxes(this.context, userId, withCounts);
|
|
712
|
+
}
|
|
1124
713
|
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
714
|
+
jmapQueryEmails(input: Parameters<typeof queryJmapEmails>[1]) {
|
|
715
|
+
return mailboxJmap.jmapQueryEmails(this.context, input);
|
|
716
|
+
}
|
|
1128
717
|
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
.where(eq(folders.id, id))
|
|
1133
|
-
.returning()
|
|
1134
|
-
.all();
|
|
718
|
+
jmapQueryChanges(input: Parameters<typeof mailboxJmap.jmapQueryChanges>[1]) {
|
|
719
|
+
return mailboxJmap.jmapQueryChanges(this.context, input);
|
|
720
|
+
}
|
|
1135
721
|
|
|
1136
|
-
|
|
1137
|
-
this.
|
|
722
|
+
jmapEmails(userId: string, ids: string[], properties?: string[] | null) {
|
|
723
|
+
return jmapEmails(this.context, userId, ids, properties);
|
|
724
|
+
}
|
|
1138
725
|
|
|
1139
|
-
|
|
726
|
+
jmapThreads(ids: string[], userId: string) {
|
|
727
|
+
return mailboxJmap.jmapThreads(this.context, ids, userId);
|
|
1140
728
|
}
|
|
1141
729
|
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
730
|
+
jmapChangeMailboxes(
|
|
731
|
+
changes: { emailId: string; change: MailboxChange }[],
|
|
732
|
+
by: { userId: string; trustSenders: boolean }
|
|
733
|
+
) {
|
|
734
|
+
return mailboxJmap.jmapChangeMailboxes(this.context, changes, by);
|
|
735
|
+
}
|
|
1148
736
|
|
|
1149
|
-
|
|
1150
|
-
|
|
737
|
+
listBackupEmails(afterId: string | null, limit: number, newLimit: number) {
|
|
738
|
+
return mailboxBackup.listBackupEmails(
|
|
739
|
+
this.context,
|
|
740
|
+
afterId,
|
|
741
|
+
limit,
|
|
742
|
+
newLimit
|
|
743
|
+
);
|
|
744
|
+
}
|
|
1151
745
|
|
|
1152
|
-
|
|
746
|
+
listBackupDrafts(after: mailboxBackup.BackupDraftKey | null) {
|
|
747
|
+
return mailboxBackup.listBackupDrafts(this.context, after);
|
|
1153
748
|
}
|
|
1154
749
|
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
*/
|
|
1159
|
-
reorderFolders(folderIds: string[]) {
|
|
1160
|
-
const customIds = this.db
|
|
1161
|
-
.select({ id: folders.id })
|
|
1162
|
-
.from(folders)
|
|
1163
|
-
.all()
|
|
1164
|
-
.map((folder) => folder.id);
|
|
1165
|
-
|
|
1166
|
-
if (!isCompleteFolderOrder(folderIds, customIds)) {
|
|
1167
|
-
return { status: "conflict" as const };
|
|
1168
|
-
}
|
|
750
|
+
backupSettings() {
|
|
751
|
+
return mailboxBackup.backupSettings(this.context);
|
|
752
|
+
}
|
|
1169
753
|
|
|
1170
|
-
|
|
1171
|
-
this.
|
|
1172
|
-
|
|
1173
|
-
if (custom.has(id)) {
|
|
1174
|
-
tx.update(folders).set({ sortOrder }).where(eq(folders.id, id)).run();
|
|
1175
|
-
} else {
|
|
1176
|
-
tx.insert(systemFolderOrder)
|
|
1177
|
-
.values({ folderId: id, sortOrder })
|
|
1178
|
-
.onConflictDoUpdate({
|
|
1179
|
-
target: systemFolderOrder.folderId,
|
|
1180
|
-
set: { sortOrder },
|
|
1181
|
-
})
|
|
1182
|
-
.run();
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
});
|
|
1186
|
-
this.publishUpdate();
|
|
754
|
+
restoreSettings(settings: MailboxBackupSettings) {
|
|
755
|
+
return mailboxBackup.restoreSettings(this.context, settings);
|
|
756
|
+
}
|
|
1187
757
|
|
|
1188
|
-
|
|
758
|
+
restoreDraft(
|
|
759
|
+
userId: string,
|
|
760
|
+
input: DraftInput,
|
|
761
|
+
restoredSource: Parameters<typeof mailboxBackup.restoreDraft>[3]
|
|
762
|
+
) {
|
|
763
|
+
return mailboxBackup.restoreDraft(
|
|
764
|
+
this.context,
|
|
765
|
+
userId,
|
|
766
|
+
input,
|
|
767
|
+
restoredSource
|
|
768
|
+
);
|
|
1189
769
|
}
|
|
1190
770
|
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
.from(mailboxAiConfiguration)
|
|
1195
|
-
.where(eq(mailboxAiConfiguration.id, AI_CONFIGURATION_ID))
|
|
1196
|
-
.all()[0];
|
|
771
|
+
clearBackupHashes() {
|
|
772
|
+
return mailboxBackup.clearBackupHashes(this.context);
|
|
773
|
+
}
|
|
1197
774
|
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
instructions: stored.instructions,
|
|
1201
|
-
confidenceThreshold: stored.confidenceThreshold,
|
|
1202
|
-
}
|
|
1203
|
-
: {
|
|
1204
|
-
instructions: "",
|
|
1205
|
-
confidenceThreshold: 75,
|
|
1206
|
-
};
|
|
1207
|
-
}
|
|
1208
|
-
|
|
1209
|
-
getMailboxAiSettings() {
|
|
1210
|
-
return {
|
|
1211
|
-
configuration: this.aiConfiguration(),
|
|
1212
|
-
globalEnabled: aiFeatureEnabled("classification"),
|
|
1213
|
-
};
|
|
1214
|
-
}
|
|
1215
|
-
|
|
1216
|
-
setMailboxAiConfiguration(configuration: MailboxAiConfiguration) {
|
|
1217
|
-
if (
|
|
1218
|
-
configuration.confidenceThreshold < 50 ||
|
|
1219
|
-
configuration.confidenceThreshold > 100 ||
|
|
1220
|
-
configuration.instructions.length > 4000
|
|
1221
|
-
) {
|
|
1222
|
-
throw new Error("Invalid mailbox AI configuration");
|
|
1223
|
-
}
|
|
1224
|
-
|
|
1225
|
-
this.db
|
|
1226
|
-
.insert(mailboxAiConfiguration)
|
|
1227
|
-
.values({
|
|
1228
|
-
id: AI_CONFIGURATION_ID,
|
|
1229
|
-
instructions: configuration.instructions.trim(),
|
|
1230
|
-
confidenceThreshold: configuration.confidenceThreshold,
|
|
1231
|
-
updatedAt: new Date(),
|
|
1232
|
-
})
|
|
1233
|
-
.onConflictDoUpdate({
|
|
1234
|
-
target: mailboxAiConfiguration.id,
|
|
1235
|
-
set: {
|
|
1236
|
-
instructions: configuration.instructions.trim(),
|
|
1237
|
-
confidenceThreshold: configuration.confidenceThreshold,
|
|
1238
|
-
updatedAt: new Date(),
|
|
1239
|
-
},
|
|
1240
|
-
})
|
|
1241
|
-
.run();
|
|
1242
|
-
|
|
1243
|
-
return this.getMailboxAiSettings();
|
|
1244
|
-
}
|
|
1245
|
-
|
|
1246
|
-
jmapState() {
|
|
1247
|
-
return jmapState(this.state.storage);
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
jmapMailboxes(userId: string) {
|
|
1251
|
-
return {
|
|
1252
|
-
state: jmapState(this.state.storage),
|
|
1253
|
-
mailboxes: jmapMailboxRows(this.state.storage.sql, userId),
|
|
1254
|
-
};
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
jmapQueryEmails(input: Parameters<typeof queryJmapEmails>[1]) {
|
|
1258
|
-
return {
|
|
1259
|
-
state: jmapState(this.state.storage),
|
|
1260
|
-
...queryJmapEmails(this.state.storage.sql, input),
|
|
1261
|
-
};
|
|
1262
|
-
}
|
|
1263
|
-
|
|
1264
|
-
/** Emails with their JMAP Mailbox and this user's $seen keyword; unknown ids are left out. */
|
|
1265
|
-
jmapEmails(userId: string, ids: string[]) {
|
|
1266
|
-
const placement = jmapEmailPlacement(this.state.storage.sql, userId, ids);
|
|
1267
|
-
|
|
1268
|
-
return {
|
|
1269
|
-
state: jmapState(this.state.storage),
|
|
1270
|
-
emails: ids.flatMap((id) => {
|
|
1271
|
-
const email = this.getEmail(id);
|
|
1272
|
-
const place = placement.get(id);
|
|
1273
|
-
|
|
1274
|
-
return email && place ? [{ email, ...place }] : [];
|
|
1275
|
-
}),
|
|
1276
|
-
};
|
|
1277
|
-
}
|
|
1278
|
-
|
|
1279
|
-
jmapThreads(ids: string[]) {
|
|
1280
|
-
return {
|
|
1281
|
-
state: jmapState(this.state.storage),
|
|
1282
|
-
threads: [...jmapThreadEmails(this.state.storage.sql, ids)].map(
|
|
1283
|
-
([id, emailIds]) => ({ id, emailIds })
|
|
1284
|
-
),
|
|
1285
|
-
};
|
|
1286
|
-
}
|
|
1287
|
-
|
|
1288
|
-
jmapMoveEmails(emailIds: string[], target: string) {
|
|
1289
|
-
const moved = this.db.transaction(() => {
|
|
1290
|
-
const known = jmapMoveEmails(this.state.storage.sql, emailIds, target);
|
|
1291
|
-
|
|
1292
|
-
if (known) {
|
|
1293
|
-
// Mail kept out of a conversation as spam rejoins it once moved out of Junk.
|
|
1294
|
-
this.rejoinSplitConversations(
|
|
1295
|
-
this.db
|
|
1296
|
-
.selectDistinct({ id: emails.conversationId })
|
|
1297
|
-
.from(emails)
|
|
1298
|
-
.where(
|
|
1299
|
-
sql`${emails.id} in (select cast(value as text) from json_each(${stringListJson(emailIds)}))`
|
|
1300
|
-
)
|
|
1301
|
-
.all()
|
|
1302
|
-
.map((row) => row.id)
|
|
1303
|
-
);
|
|
1304
|
-
}
|
|
1305
|
-
|
|
1306
|
-
return known;
|
|
1307
|
-
});
|
|
1308
|
-
|
|
1309
|
-
if (moved) this.publishUpdate();
|
|
1310
|
-
|
|
1311
|
-
return moved;
|
|
775
|
+
setBackupHashes(hashes: mailboxBackup.BackupHash[]) {
|
|
776
|
+
return mailboxBackup.setBackupHashes(this.context, hashes);
|
|
1312
777
|
}
|
|
1313
778
|
|
|
1314
779
|
getEmail(id: string) {
|
|
@@ -1328,43 +793,32 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1328
793
|
);
|
|
1329
794
|
}
|
|
1330
795
|
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
796
|
+
hasNewConversationRecipients(
|
|
797
|
+
conversationId: string,
|
|
798
|
+
ownAddress: string,
|
|
799
|
+
recipients: RecipientFields
|
|
800
|
+
) {
|
|
801
|
+
const history = this.db
|
|
802
|
+
.select({
|
|
803
|
+
fromJson: emails.fromJson,
|
|
804
|
+
toJson: emails.toJson,
|
|
805
|
+
ccJson: emails.ccJson,
|
|
806
|
+
bccJson: emails.bccJson,
|
|
807
|
+
listPostAddress: emails.listPostAddress,
|
|
808
|
+
})
|
|
1334
809
|
.from(emails)
|
|
1335
810
|
.where(eq(emails.conversationId, conversationId))
|
|
1336
|
-
.orderBy(asc(emails.timelineAt), asc(emails.id))
|
|
1337
811
|
.all();
|
|
1338
|
-
}
|
|
1339
812
|
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
.select({
|
|
1343
|
-
mailboxState: conversations.mailboxState,
|
|
1344
|
-
folderId: conversations.folderId,
|
|
1345
|
-
})
|
|
1346
|
-
.from(conversations)
|
|
1347
|
-
.where(eq(conversations.id, conversationId))
|
|
1348
|
-
.all()[0];
|
|
813
|
+
return hasNewRecipients({ ownAddress, history, ...recipients });
|
|
814
|
+
}
|
|
1349
815
|
|
|
1350
|
-
|
|
816
|
+
getConversation(conversationId: string) {
|
|
817
|
+
return mailboxViews.getConversation(this.context, conversationId);
|
|
818
|
+
}
|
|
1351
819
|
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
folderId: conversation.folderId,
|
|
1355
|
-
messages: this.getConversation(conversationId),
|
|
1356
|
-
readStates: this.db
|
|
1357
|
-
.select({
|
|
1358
|
-
emailId: emailReadStates.emailId,
|
|
1359
|
-
userId: emailReadStates.userId,
|
|
1360
|
-
readAt: emailReadStates.readAt,
|
|
1361
|
-
})
|
|
1362
|
-
.from(emailReadStates)
|
|
1363
|
-
.innerJoin(emails, eq(emailReadStates.emailId, emails.id))
|
|
1364
|
-
.where(eq(emails.conversationId, conversationId))
|
|
1365
|
-
.orderBy(asc(emailReadStates.readAt))
|
|
1366
|
-
.all(),
|
|
1367
|
-
};
|
|
820
|
+
getConversationSnapshot(conversationId: string) {
|
|
821
|
+
return mailboxViews.getConversationSnapshot(this.context, conversationId);
|
|
1368
822
|
}
|
|
1369
823
|
|
|
1370
824
|
getConversationPageSnapshot(
|
|
@@ -1373,165 +827,49 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1373
827
|
limit: number,
|
|
1374
828
|
cursor: ConversationCursorPosition | null
|
|
1375
829
|
) {
|
|
1376
|
-
|
|
1377
|
-
.
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
.from(conversations)
|
|
1384
|
-
.where(eq(conversations.id, conversationId))
|
|
1385
|
-
.all()[0];
|
|
1386
|
-
|
|
1387
|
-
if (!conversation) return null;
|
|
1388
|
-
|
|
1389
|
-
const pageLimit = Math.max(1, Math.min(limit, 25));
|
|
1390
|
-
const cursorDate = cursor ? new Date(cursor.timelineAt) : null;
|
|
1391
|
-
|
|
1392
|
-
const predicate =
|
|
1393
|
-
cursor && cursorDate
|
|
1394
|
-
? and(
|
|
1395
|
-
eq(emails.conversationId, conversationId),
|
|
1396
|
-
or(
|
|
1397
|
-
lt(emails.timelineAt, cursorDate),
|
|
1398
|
-
and(
|
|
1399
|
-
eq(emails.timelineAt, cursorDate),
|
|
1400
|
-
lt(emails.id, cursor.emailId)
|
|
1401
|
-
)
|
|
1402
|
-
)
|
|
1403
|
-
)
|
|
1404
|
-
: eq(emails.conversationId, conversationId);
|
|
1405
|
-
|
|
1406
|
-
const descending = this.db
|
|
1407
|
-
.select()
|
|
1408
|
-
.from(emails)
|
|
1409
|
-
.where(predicate)
|
|
1410
|
-
.orderBy(desc(emails.timelineAt), desc(emails.id))
|
|
1411
|
-
.limit(pageLimit + 1)
|
|
1412
|
-
.all();
|
|
1413
|
-
|
|
1414
|
-
const page = descending.slice(0, pageLimit);
|
|
1415
|
-
const oldest = page.at(-1);
|
|
1416
|
-
const messageIds = page.map((email) => email.id);
|
|
1417
|
-
|
|
1418
|
-
const counts = this.state.storage.sql
|
|
1419
|
-
.exec<ConversationSnapshotCountRow>(
|
|
1420
|
-
`
|
|
1421
|
-
select
|
|
1422
|
-
count(*) as message_count,
|
|
1423
|
-
coalesce(sum(
|
|
1424
|
-
case
|
|
1425
|
-
when message.direction = 'incoming' and not exists (
|
|
1426
|
-
select 1
|
|
1427
|
-
from email_read_states read_state
|
|
1428
|
-
where read_state.user_id = ?
|
|
1429
|
-
and read_state.email_id = message.id
|
|
1430
|
-
) then 1
|
|
1431
|
-
else 0
|
|
1432
|
-
end
|
|
1433
|
-
), 0) as unread_count
|
|
1434
|
-
from emails message
|
|
1435
|
-
where message.conversation_id = ?
|
|
1436
|
-
`,
|
|
1437
|
-
userId,
|
|
1438
|
-
conversationId
|
|
1439
|
-
)
|
|
1440
|
-
.one();
|
|
1441
|
-
|
|
1442
|
-
return {
|
|
1443
|
-
mailboxState: conversation.mailboxState,
|
|
1444
|
-
folderId: conversation.folderId,
|
|
1445
|
-
hasIncoming: conversation.hasIncoming,
|
|
1446
|
-
hasOutgoing: conversation.hasOutgoing,
|
|
1447
|
-
messageCount: Number(counts.message_count),
|
|
1448
|
-
unreadCount: Number(counts.unread_count),
|
|
1449
|
-
messages: page.reverse(),
|
|
1450
|
-
next:
|
|
1451
|
-
descending.length > pageLimit && oldest
|
|
1452
|
-
? { timelineAt: oldest.timelineAt.getTime(), emailId: oldest.id }
|
|
1453
|
-
: null,
|
|
1454
|
-
readStates: messageIds.length
|
|
1455
|
-
? this.db
|
|
1456
|
-
.select({
|
|
1457
|
-
emailId: emailReadStates.emailId,
|
|
1458
|
-
userId: emailReadStates.userId,
|
|
1459
|
-
readAt: emailReadStates.readAt,
|
|
1460
|
-
})
|
|
1461
|
-
.from(emailReadStates)
|
|
1462
|
-
.where(inArray(emailReadStates.emailId, messageIds))
|
|
1463
|
-
.orderBy(asc(emailReadStates.readAt))
|
|
1464
|
-
.all()
|
|
1465
|
-
: [],
|
|
1466
|
-
};
|
|
830
|
+
return mailboxViews.getConversationPageSnapshot(
|
|
831
|
+
this.context,
|
|
832
|
+
conversationId,
|
|
833
|
+
userId,
|
|
834
|
+
limit,
|
|
835
|
+
cursor
|
|
836
|
+
);
|
|
1467
837
|
}
|
|
1468
838
|
|
|
1469
|
-
/**
|
|
1470
|
-
* Everything the reader needs from this mailbox in one call: a page of the
|
|
1471
|
-
* conversation with read states, plus sender history and block, trust and
|
|
1472
|
-
* unsubscribe state for its incoming senders.
|
|
1473
|
-
*/
|
|
1474
839
|
getConversationView(
|
|
1475
840
|
conversationId: string,
|
|
1476
841
|
userId: string,
|
|
1477
842
|
limit: number,
|
|
1478
|
-
cursor: ConversationCursorPosition | null
|
|
843
|
+
cursor: ConversationCursorPosition | null,
|
|
844
|
+
includeReplyDraft: boolean,
|
|
845
|
+
matchId?: string
|
|
1479
846
|
) {
|
|
1480
|
-
|
|
847
|
+
return mailboxViews.getConversationView(
|
|
848
|
+
this.context,
|
|
1481
849
|
conversationId,
|
|
1482
850
|
userId,
|
|
1483
851
|
limit,
|
|
1484
|
-
cursor
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
if (!snapshot) return null;
|
|
1488
|
-
|
|
1489
|
-
const incoming = snapshot.messages.filter(
|
|
1490
|
-
(message) => message.direction === "incoming"
|
|
852
|
+
cursor,
|
|
853
|
+
includeReplyDraft,
|
|
854
|
+
matchId
|
|
1491
855
|
);
|
|
1492
|
-
|
|
1493
|
-
const senderAddresses = incoming.flatMap((message) =>
|
|
1494
|
-
message.fromJson[0] ? [message.fromJson[0].address] : []
|
|
1495
|
-
);
|
|
1496
|
-
|
|
1497
|
-
return {
|
|
1498
|
-
...snapshot,
|
|
1499
|
-
history: this.getSenderHistory(senderAddresses),
|
|
1500
|
-
safety: this.getMessageSafetyContext(
|
|
1501
|
-
senderAddresses,
|
|
1502
|
-
incoming.flatMap((message) => emailListKey(message) ?? [])
|
|
1503
|
-
),
|
|
1504
|
-
version: this.version(),
|
|
1505
|
-
};
|
|
1506
856
|
}
|
|
1507
857
|
|
|
1508
|
-
/** One message with its sender's history and safety state, for re-deriving its security summary. */
|
|
1509
858
|
getMessageSenderView(emailId: string) {
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
if (!email) return null;
|
|
1513
|
-
|
|
1514
|
-
const sender =
|
|
1515
|
-
email.direction === "incoming" ? email.fromJson[0]?.address : undefined;
|
|
1516
|
-
|
|
1517
|
-
const senderAddresses = sender ? [sender] : [];
|
|
1518
|
-
const listKey = emailListKey(email);
|
|
1519
|
-
|
|
1520
|
-
return {
|
|
1521
|
-
email,
|
|
1522
|
-
history: this.getSenderHistory(senderAddresses),
|
|
1523
|
-
safety: this.getMessageSafetyContext(
|
|
1524
|
-
senderAddresses,
|
|
1525
|
-
listKey ? [listKey] : []
|
|
1526
|
-
),
|
|
1527
|
-
};
|
|
859
|
+
return mailboxViews.getMessageSenderView(this.context, emailId);
|
|
1528
860
|
}
|
|
1529
861
|
|
|
1530
862
|
getAttachment(emailId: string, attachmentId: string) {
|
|
1531
|
-
|
|
863
|
+
return mailboxViews.getAttachment(this.context, emailId, attachmentId);
|
|
864
|
+
}
|
|
1532
865
|
|
|
866
|
+
getRawMimeKey(emailId: string) {
|
|
1533
867
|
return (
|
|
1534
|
-
|
|
868
|
+
this.db
|
|
869
|
+
.select({ key: emails.rawMimeR2Key })
|
|
870
|
+
.from(emails)
|
|
871
|
+
.where(eq(emails.id, emailId))
|
|
872
|
+
.get()?.key ?? null
|
|
1535
873
|
);
|
|
1536
874
|
}
|
|
1537
875
|
|
|
@@ -1541,26 +879,20 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1541
879
|
sourceKey: string,
|
|
1542
880
|
status: "ready" | "failed"
|
|
1543
881
|
) {
|
|
1544
|
-
const
|
|
882
|
+
const attachments = mailboxViews.emailAttachments(this.context, emailId);
|
|
1545
883
|
|
|
1546
|
-
const file =
|
|
884
|
+
const file = attachments.find(
|
|
1547
885
|
(attachment) =>
|
|
1548
886
|
attachment.id === attachmentId && attachment.r2Key === sourceKey
|
|
1549
887
|
);
|
|
1550
888
|
|
|
1551
|
-
if (!
|
|
1552
|
-
// Conversion may finish after permanent deletion already removed its
|
|
1553
|
-
//
|
|
1554
|
-
|
|
1555
|
-
await
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
.values({
|
|
1559
|
-
objectKey: officePreviewKey(sourceKey),
|
|
1560
|
-
nextAttemptAt: cleanupAt,
|
|
1561
|
-
})
|
|
1562
|
-
.onConflictDoNothing()
|
|
1563
|
-
.run();
|
|
889
|
+
if (!file) {
|
|
890
|
+
// Conversion may finish after permanent deletion already removed its
|
|
891
|
+
// objects: queue the PDF before the queue acknowledges, so an R2
|
|
892
|
+
// outage can't orphan it.
|
|
893
|
+
await mailboxStorage.forgetObjects(this.context, [
|
|
894
|
+
officePreviewKey(sourceKey),
|
|
895
|
+
]);
|
|
1564
896
|
|
|
1565
897
|
return false;
|
|
1566
898
|
}
|
|
@@ -1569,7 +901,7 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1569
901
|
this.db
|
|
1570
902
|
.update(emails)
|
|
1571
903
|
.set({
|
|
1572
|
-
attachmentsJson:
|
|
904
|
+
attachmentsJson: attachments.map((attachment) =>
|
|
1573
905
|
attachment.id === attachmentId
|
|
1574
906
|
? { ...attachment, pdfPreviewStatus: status }
|
|
1575
907
|
: attachment
|
|
@@ -1577,7 +909,7 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1577
909
|
})
|
|
1578
910
|
.where(eq(emails.id, emailId))
|
|
1579
911
|
.run();
|
|
1580
|
-
this.
|
|
912
|
+
void this.announce({ inboxChanged: false });
|
|
1581
913
|
|
|
1582
914
|
return true;
|
|
1583
915
|
}
|
|
@@ -1595,195 +927,75 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1595
927
|
.limit(500)
|
|
1596
928
|
.all();
|
|
1597
929
|
|
|
1598
|
-
const
|
|
1599
|
-
.exec<{ address: string }>(
|
|
1600
|
-
"select address from senders where blocked_at is not null or reported_at is not null"
|
|
1601
|
-
)
|
|
1602
|
-
.toArray()
|
|
1603
|
-
.map((row) => row.address);
|
|
1604
|
-
|
|
1605
|
-
const excluded = new Set(flagged);
|
|
1606
|
-
|
|
1607
|
-
return suggestParticipants(
|
|
930
|
+
const candidates = suggestParticipants(
|
|
1608
931
|
this.recentParticipantSources,
|
|
1609
932
|
ownAddress,
|
|
1610
|
-
query
|
|
1611
|
-
limit,
|
|
1612
|
-
(address) =>
|
|
1613
|
-
blockPatternsFor(address).some((pattern) => excluded.has(pattern))
|
|
933
|
+
query
|
|
1614
934
|
);
|
|
1615
|
-
}
|
|
1616
935
|
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
union all
|
|
1630
|
-
select id, name, 'custom', null, sort_order
|
|
1631
|
-
from folders
|
|
1632
|
-
),
|
|
1633
|
-
conversation_unread as (
|
|
1634
|
-
select
|
|
1635
|
-
c.id,
|
|
1636
|
-
c.mailbox_state,
|
|
1637
|
-
c.folder_id,
|
|
1638
|
-
c.has_incoming,
|
|
1639
|
-
c.has_outgoing,
|
|
1640
|
-
coalesce(sum(case
|
|
1641
|
-
when message.id is not null and read_state.email_id is null then 1
|
|
1642
|
-
else 0
|
|
1643
|
-
end), 0) as unread_count
|
|
1644
|
-
from conversations c
|
|
1645
|
-
left join emails message
|
|
1646
|
-
on message.conversation_id = c.id
|
|
1647
|
-
and message.direction = 'incoming'
|
|
1648
|
-
left join email_read_states read_state
|
|
1649
|
-
on read_state.user_id = ?
|
|
1650
|
-
and read_state.email_id = message.id
|
|
1651
|
-
group by
|
|
1652
|
-
c.id,
|
|
1653
|
-
c.mailbox_state,
|
|
1654
|
-
c.folder_id,
|
|
1655
|
-
c.has_incoming,
|
|
1656
|
-
c.has_outgoing
|
|
936
|
+
if (!candidates.length) return [];
|
|
937
|
+
|
|
938
|
+
const patterns = candidates.flatMap((row) => blockPatternsFor(row.address));
|
|
939
|
+
|
|
940
|
+
const flagged = this.db
|
|
941
|
+
.select({ address: senders.address })
|
|
942
|
+
.from(senders)
|
|
943
|
+
.where(
|
|
944
|
+
and(
|
|
945
|
+
inJsonList(senders.address, patterns),
|
|
946
|
+
or(isNotNull(senders.blockedAt), isNotNull(senders.reportedAt))
|
|
947
|
+
)
|
|
1657
948
|
)
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
${FOLDER_AGGREGATE_JOIN_PREDICATE}
|
|
1669
|
-
group by
|
|
1670
|
-
folder.id,
|
|
1671
|
-
folder.name,
|
|
1672
|
-
folder.kind,
|
|
1673
|
-
folder.system_type,
|
|
1674
|
-
folder.sort_order
|
|
1675
|
-
`,
|
|
1676
|
-
JSON.stringify(this.systemFolders()),
|
|
1677
|
-
userId
|
|
949
|
+
.all();
|
|
950
|
+
|
|
951
|
+
const excluded = new Set(flagged.map((row) => row.address));
|
|
952
|
+
|
|
953
|
+
return candidates
|
|
954
|
+
.filter(
|
|
955
|
+
(row) =>
|
|
956
|
+
!blockPatternsFor(row.address).some((pattern) =>
|
|
957
|
+
excluded.has(pattern)
|
|
958
|
+
)
|
|
1678
959
|
)
|
|
1679
|
-
.
|
|
1680
|
-
|
|
1681
|
-
return sortFolders(
|
|
1682
|
-
rows.map((row): FolderListItem => ({
|
|
1683
|
-
id: row.id,
|
|
1684
|
-
name: row.name,
|
|
1685
|
-
kind: row.kind,
|
|
1686
|
-
systemType: row.system_type,
|
|
1687
|
-
sortOrder: Number(row.sort_order),
|
|
1688
|
-
totalCount: Number(row.total_count),
|
|
1689
|
-
unreadCount: Number(row.unread_count),
|
|
1690
|
-
}))
|
|
1691
|
-
);
|
|
960
|
+
.slice(0, limit);
|
|
1692
961
|
}
|
|
1693
962
|
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
startupView(
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
963
|
+
listFolders(userId: string) {
|
|
964
|
+
return mailboxViews.listFolders(this.context, userId);
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
startupView(
|
|
968
|
+
userId: string,
|
|
969
|
+
folderId: string,
|
|
970
|
+
limit: number,
|
|
971
|
+
draftSenders?: DraftSenders
|
|
972
|
+
) {
|
|
973
|
+
return mailboxViews.startupView(
|
|
974
|
+
this.context,
|
|
975
|
+
userId,
|
|
976
|
+
folderId,
|
|
977
|
+
limit,
|
|
978
|
+
draftSenders
|
|
979
|
+
);
|
|
1709
980
|
}
|
|
1710
981
|
|
|
1711
|
-
/** `listFolders` with the change counter it reflects. */
|
|
1712
982
|
folderView(userId: string) {
|
|
1713
|
-
return
|
|
1714
|
-
}
|
|
1715
|
-
|
|
1716
|
-
getFolderCounts(userId: string, folderId: string): FolderCounts | null {
|
|
1717
|
-
const folder = this.getFolder(folderId);
|
|
1718
|
-
|
|
1719
|
-
return folder ? this.countFolder(userId, folder) : null;
|
|
1720
|
-
}
|
|
1721
|
-
|
|
1722
|
-
private countFolder(userId: string, folder: MailFolder): FolderCounts {
|
|
1723
|
-
const membership = folderMembership(folder);
|
|
1724
|
-
|
|
1725
|
-
const counts = this.state.storage.sql
|
|
1726
|
-
.exec<FolderCountRow>(
|
|
1727
|
-
`
|
|
1728
|
-
select
|
|
1729
|
-
count(*) as total_count,
|
|
1730
|
-
coalesce(sum((
|
|
1731
|
-
select count(*)
|
|
1732
|
-
from emails message
|
|
1733
|
-
where message.conversation_id = c.id
|
|
1734
|
-
and message.direction = 'incoming'
|
|
1735
|
-
and not exists (
|
|
1736
|
-
select 1
|
|
1737
|
-
from email_read_states read_state
|
|
1738
|
-
where read_state.user_id = ?
|
|
1739
|
-
and read_state.email_id = message.id
|
|
1740
|
-
)
|
|
1741
|
-
)), 0) as unread_count
|
|
1742
|
-
from conversations c
|
|
1743
|
-
where ${membership.predicate}
|
|
1744
|
-
`,
|
|
1745
|
-
userId,
|
|
1746
|
-
...membership.bindings
|
|
1747
|
-
)
|
|
1748
|
-
.one();
|
|
983
|
+
return mailboxViews.folderView(this.context, userId);
|
|
984
|
+
}
|
|
1749
985
|
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
unreadCount: Number(counts.unread_count),
|
|
1753
|
-
};
|
|
986
|
+
getFolderCounts(userId: string, folderId: string) {
|
|
987
|
+
return mailboxViews.getFolderCounts(this.context, userId, folderId);
|
|
1754
988
|
}
|
|
1755
989
|
|
|
1756
|
-
/** Sets one person's read state; the change counter after it, or false for no such message. */
|
|
1757
990
|
setMessageRead(userId: string, emailId: string, isRead: boolean) {
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
if (!email) return false;
|
|
1761
|
-
|
|
1762
|
-
if (isRead) {
|
|
1763
|
-
const readAt = new Date();
|
|
1764
|
-
this.db
|
|
1765
|
-
.insert(emailReadStates)
|
|
1766
|
-
.values({ userId, emailId, readAt })
|
|
1767
|
-
.onConflictDoUpdate({
|
|
1768
|
-
target: [emailReadStates.userId, emailReadStates.emailId],
|
|
1769
|
-
set: { readAt },
|
|
1770
|
-
})
|
|
1771
|
-
.run();
|
|
1772
|
-
} else {
|
|
1773
|
-
this.db
|
|
1774
|
-
.delete(emailReadStates)
|
|
1775
|
-
.where(
|
|
1776
|
-
and(
|
|
1777
|
-
eq(emailReadStates.userId, userId),
|
|
1778
|
-
eq(emailReadStates.emailId, emailId)
|
|
1779
|
-
)
|
|
1780
|
-
)
|
|
1781
|
-
.run();
|
|
1782
|
-
}
|
|
1783
|
-
|
|
1784
|
-
this.publishUpdate();
|
|
991
|
+
return mailboxViews.setMessageRead(this.context, userId, emailId, isRead);
|
|
992
|
+
}
|
|
1785
993
|
|
|
1786
|
-
|
|
994
|
+
setReadStates(
|
|
995
|
+
userId: string,
|
|
996
|
+
changes: { emailId: string; isRead: boolean }[]
|
|
997
|
+
) {
|
|
998
|
+
return mailboxViews.setReadStates(this.context, userId, changes);
|
|
1787
999
|
}
|
|
1788
1000
|
|
|
1789
1001
|
bulkSetConversationRead(
|
|
@@ -1791,121 +1003,16 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1791
1003
|
conversationIds: string[],
|
|
1792
1004
|
isRead: boolean
|
|
1793
1005
|
) {
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
.select({ id: conversations.id })
|
|
1801
|
-
.from(conversations)
|
|
1802
|
-
.where(
|
|
1803
|
-
and(
|
|
1804
|
-
sql`${conversations.id} in (
|
|
1805
|
-
select cast(value as text) from json_each(${candidatesJson})
|
|
1806
|
-
)`,
|
|
1807
|
-
eq(conversations.hasIncoming, true)
|
|
1808
|
-
)
|
|
1809
|
-
)
|
|
1810
|
-
.all()
|
|
1811
|
-
.map((conversation) => conversation.id);
|
|
1812
|
-
|
|
1813
|
-
if (!existingIds.length) return 0;
|
|
1814
|
-
const existingIdsJson = stringListJson(existingIds);
|
|
1815
|
-
|
|
1816
|
-
if (isRead) {
|
|
1817
|
-
this.db.run(sql`
|
|
1818
|
-
insert into email_read_states (user_id, email_id, read_at)
|
|
1819
|
-
select ${userId}, id, ${Date.now()}
|
|
1820
|
-
from emails
|
|
1821
|
-
where conversation_id in (
|
|
1822
|
-
select cast(value as text) from json_each(${existingIdsJson})
|
|
1823
|
-
) and direction = 'incoming'
|
|
1824
|
-
on conflict (user_id, email_id) do update set read_at = excluded.read_at
|
|
1825
|
-
`);
|
|
1826
|
-
} else {
|
|
1827
|
-
this.db.run(sql`
|
|
1828
|
-
delete from email_read_states
|
|
1829
|
-
where user_id = ${userId}
|
|
1830
|
-
and email_id in (
|
|
1831
|
-
select message.id
|
|
1832
|
-
from emails message
|
|
1833
|
-
where message.conversation_id in (
|
|
1834
|
-
select cast(value as text) from json_each(${existingIdsJson})
|
|
1835
|
-
)
|
|
1836
|
-
and message.direction = 'incoming'
|
|
1837
|
-
and not exists (
|
|
1838
|
-
select 1
|
|
1839
|
-
from emails newer
|
|
1840
|
-
where newer.conversation_id = message.conversation_id
|
|
1841
|
-
and newer.direction = 'incoming'
|
|
1842
|
-
and (
|
|
1843
|
-
newer.timeline_at > message.timeline_at
|
|
1844
|
-
or (
|
|
1845
|
-
newer.timeline_at = message.timeline_at
|
|
1846
|
-
and newer.id > message.id
|
|
1847
|
-
)
|
|
1848
|
-
)
|
|
1849
|
-
)
|
|
1850
|
-
)
|
|
1851
|
-
`);
|
|
1852
|
-
}
|
|
1853
|
-
|
|
1854
|
-
this.publishUpdate();
|
|
1855
|
-
|
|
1856
|
-
return existingIds.length;
|
|
1006
|
+
return mailboxViews.bulkSetConversationRead(
|
|
1007
|
+
this.context,
|
|
1008
|
+
userId,
|
|
1009
|
+
conversationIds,
|
|
1010
|
+
isRead
|
|
1011
|
+
);
|
|
1857
1012
|
}
|
|
1858
1013
|
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
if (Number.isNaN(receivedAt.getTime())) {
|
|
1863
|
-
throw new Error("Inbound delivery has an invalid receipt time");
|
|
1864
|
-
}
|
|
1865
|
-
|
|
1866
|
-
if (this.state.id.name && this.state.id.name !== input.mailboxId) {
|
|
1867
|
-
throw new Error("Inbound delivery targeted the wrong mailbox object");
|
|
1868
|
-
}
|
|
1869
|
-
|
|
1870
|
-
const queuedAt = new Date();
|
|
1871
|
-
// Keep the alarm just ahead of the due time. Scheduling it for "now" can
|
|
1872
|
-
// wake it on the setAlarm await before the synchronous insert below runs.
|
|
1873
|
-
const alarmAt = queuedAt.getTime() + ALARM_WAKE_DELAY_MS;
|
|
1874
|
-
await this.scheduleAlarm(alarmAt);
|
|
1875
|
-
const messageId = inboundMessageId(input.id);
|
|
1876
|
-
|
|
1877
|
-
const queued = this.db.transaction((tx) => {
|
|
1878
|
-
const existing = tx
|
|
1879
|
-
.select({ id: emails.id })
|
|
1880
|
-
.from(emails)
|
|
1881
|
-
.where(eq(emails.id, messageId))
|
|
1882
|
-
.all()[0];
|
|
1883
|
-
|
|
1884
|
-
if (existing) return false;
|
|
1885
|
-
|
|
1886
|
-
const result = tx
|
|
1887
|
-
.insert(pendingInbound)
|
|
1888
|
-
.values({
|
|
1889
|
-
id: input.id,
|
|
1890
|
-
rawObjectKey: input.rawObjectKey,
|
|
1891
|
-
envelopeFrom: input.envelopeFrom,
|
|
1892
|
-
envelopeTo: input.envelopeTo,
|
|
1893
|
-
listAddress: input.listAddress ?? null,
|
|
1894
|
-
receivedAt,
|
|
1895
|
-
nextAttemptAt: queuedAt,
|
|
1896
|
-
})
|
|
1897
|
-
.onConflictDoNothing()
|
|
1898
|
-
.returning({ id: pendingInbound.id })
|
|
1899
|
-
.all();
|
|
1900
|
-
|
|
1901
|
-
return result.length > 0;
|
|
1902
|
-
});
|
|
1903
|
-
|
|
1904
|
-
// An alarm finishing meanwhile may have dropped its own wake (see
|
|
1905
|
-
// `scheduleRemainingWork`) before it could see this row.
|
|
1906
|
-
if (queued) await this.scheduleAlarm(alarmAt);
|
|
1907
|
-
|
|
1908
|
-
return { messageId, queued };
|
|
1014
|
+
enqueueInbound(input: InboundDeliveryInput) {
|
|
1015
|
+
return mailboxInbound.enqueueInbound(this.context, input);
|
|
1909
1016
|
}
|
|
1910
1017
|
|
|
1911
1018
|
async insertEmail(input: NewEmail) {
|
|
@@ -1916,18 +1023,7 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1916
1023
|
}
|
|
1917
1024
|
|
|
1918
1025
|
this.db.transaction((tx) => {
|
|
1919
|
-
|
|
1920
|
-
.insert(emails)
|
|
1921
|
-
.values(email)
|
|
1922
|
-
.onConflictDoNothing()
|
|
1923
|
-
.returning({ id: emails.id })
|
|
1924
|
-
.all();
|
|
1925
|
-
|
|
1926
|
-
if (inserted.length) {
|
|
1927
|
-
indexInsertedEmail(this.state.storage.sql, email.id);
|
|
1928
|
-
insertOfficePreviewJobs(this.state.storage.sql, email);
|
|
1929
|
-
recordCorrespondents(this.state.storage.sql, email);
|
|
1930
|
-
}
|
|
1026
|
+
storeEmail(tx, this.state.storage.sql, email);
|
|
1931
1027
|
});
|
|
1932
1028
|
this.recentParticipantSources = null;
|
|
1933
1029
|
void this.syncInboxCounts();
|
|
@@ -1935,1100 +1031,106 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1935
1031
|
return this.getEmail(email.id);
|
|
1936
1032
|
}
|
|
1937
1033
|
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1034
|
+
findImported(
|
|
1035
|
+
emailId: string,
|
|
1036
|
+
original: Pick<ImportOriginal, "emailId" | "conversationId"> | null,
|
|
1037
|
+
conversationId: string | null,
|
|
1038
|
+
copy?: mailboxImport.ImportCopyKey | null
|
|
1039
|
+
) {
|
|
1040
|
+
return mailboxImport.findImported(
|
|
1041
|
+
this.context,
|
|
1042
|
+
emailId,
|
|
1043
|
+
original,
|
|
1044
|
+
conversationId,
|
|
1045
|
+
copy
|
|
1046
|
+
);
|
|
1950
1047
|
}
|
|
1951
1048
|
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
* AI, sender checks, webhooks or push: imported mail is history. The
|
|
1956
|
-
* conversation and search index are kept as for any message; counts,
|
|
1957
|
-
* realtime and JMAP state are announced once for the batch
|
|
1958
|
-
* (`finishImport`, or the alarm when the importer never says it finished).
|
|
1959
|
-
* Idempotent by `importId` and by Message-ID.
|
|
1960
|
-
*/
|
|
1961
|
-
async importMessage(input: ImportMessageInput): Promise<ImportMessageResult> {
|
|
1962
|
-
const id = inboundMessageId(input.importId);
|
|
1963
|
-
const known = this.getEmail(id);
|
|
1964
|
-
|
|
1965
|
-
if (known) {
|
|
1966
|
-
return { status: "duplicate", id, conversationId: known.conversationId };
|
|
1967
|
-
}
|
|
1968
|
-
|
|
1969
|
-
const object = await this.bindings.MAIL_STORAGE.get(input.rawObjectKey);
|
|
1970
|
-
|
|
1971
|
-
if (!object) throw new MissingRawMimeError();
|
|
1972
|
-
const rawMime = await object.arrayBuffer();
|
|
1973
|
-
const messageIdHeader = rawMessageId(rawMime);
|
|
1974
|
-
|
|
1975
|
-
const copy = messageIdHeader
|
|
1976
|
-
? this.getEmailByMessageId(messageIdHeader)
|
|
1977
|
-
: null;
|
|
1049
|
+
importMessage(input: ImportMessageInput) {
|
|
1050
|
+
return mailboxImport.importMessage(this.context, input);
|
|
1051
|
+
}
|
|
1978
1052
|
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1053
|
+
finishImport() {
|
|
1054
|
+
return mailboxImport.finishImport(this.context);
|
|
1055
|
+
}
|
|
1982
1056
|
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
};
|
|
1988
|
-
}
|
|
1057
|
+
/** The model from openworkspace.json; tests substitute one on the instance. */
|
|
1058
|
+
protected classificationModel() {
|
|
1059
|
+
return aiModel(this.env, "classification");
|
|
1060
|
+
}
|
|
1989
1061
|
|
|
1990
|
-
|
|
1991
|
-
|
|
1062
|
+
setEmailSenderIntel(
|
|
1063
|
+
emailId: string,
|
|
1064
|
+
intel: SenderIntel,
|
|
1065
|
+
replacesCheckedAt: number | null = null
|
|
1066
|
+
) {
|
|
1067
|
+
return senderSafety.setEmailSenderIntel(
|
|
1068
|
+
this.context,
|
|
1069
|
+
emailId,
|
|
1070
|
+
intel,
|
|
1071
|
+
replacesCheckedAt
|
|
1992
1072
|
);
|
|
1073
|
+
}
|
|
1993
1074
|
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
parsed = (
|
|
1998
|
-
await prepareInboundEmail({
|
|
1999
|
-
env: this.bindings,
|
|
2000
|
-
mailboxId: this.state.id.name ?? "unknown-mailbox",
|
|
2001
|
-
job: {
|
|
2002
|
-
id: input.importId,
|
|
2003
|
-
rawObjectKey: input.rawObjectKey,
|
|
2004
|
-
envelopeFrom: "",
|
|
2005
|
-
envelopeTo: input.mailboxAddress,
|
|
2006
|
-
listAddress: null,
|
|
2007
|
-
receivedAt,
|
|
2008
|
-
},
|
|
2009
|
-
rawMime,
|
|
2010
|
-
resolveParent: (inReplyTo, references) =>
|
|
2011
|
-
this.resolveParent(inReplyTo, references),
|
|
2012
|
-
})
|
|
2013
|
-
).email;
|
|
2014
|
-
} catch (error) {
|
|
2015
|
-
if (!(error instanceof UnprocessableInboundEmailError)) throw error;
|
|
2016
|
-
await this.bindings.MAIL_STORAGE.delete(input.rawObjectKey);
|
|
1075
|
+
getSenderHistory(addresses: string[]) {
|
|
1076
|
+
return senderSafety.getSenderHistory(this.context, addresses);
|
|
1077
|
+
}
|
|
2017
1078
|
|
|
2018
|
-
|
|
2019
|
-
|
|
1079
|
+
getMessageSafetyContext(addresses: string[], listKeys: string[]) {
|
|
1080
|
+
return senderSafety.getMessageSafetyContext(
|
|
1081
|
+
this.context,
|
|
1082
|
+
addresses,
|
|
1083
|
+
listKeys
|
|
1084
|
+
);
|
|
1085
|
+
}
|
|
2020
1086
|
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
conversationId: input.conversationId ?? parsed.conversationId,
|
|
2033
|
-
direction,
|
|
2034
|
-
bodyText: clampText(parsed.bodyText),
|
|
2035
|
-
quotedText: clampText(parsed.quotedText),
|
|
2036
|
-
// Not an SMTP delivery to this workspace.
|
|
2037
|
-
envelopeFrom: null,
|
|
2038
|
-
envelopeTo: null,
|
|
2039
|
-
};
|
|
1087
|
+
recordUnsubscription(input: {
|
|
1088
|
+
listKey: string;
|
|
1089
|
+
emailId: string;
|
|
1090
|
+
method: Unsubscription["method"];
|
|
1091
|
+
status: Unsubscription["status"];
|
|
1092
|
+
target: string | null;
|
|
1093
|
+
detail: string | null;
|
|
1094
|
+
userId: string;
|
|
1095
|
+
}) {
|
|
1096
|
+
return senderSafety.recordUnsubscription(this.context, input);
|
|
1097
|
+
}
|
|
2040
1098
|
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
imported.authenticationResultsJson = null;
|
|
2045
|
-
imported.listUnsubscribeJson = null;
|
|
2046
|
-
}
|
|
1099
|
+
blockSender(pattern: string, moveExisting: boolean) {
|
|
1100
|
+
return senderSafety.blockSender(this.context, pattern, moveExisting);
|
|
1101
|
+
}
|
|
2047
1102
|
|
|
2048
|
-
|
|
1103
|
+
moveSenderToSpam(pattern: string) {
|
|
1104
|
+
return senderSafety.moveSenderToSpam(this.context, pattern);
|
|
1105
|
+
}
|
|
2049
1106
|
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
.select({
|
|
2054
|
-
mailboxState: conversations.mailboxState,
|
|
2055
|
-
folderId: conversations.folderId,
|
|
2056
|
-
})
|
|
2057
|
-
.from(conversations)
|
|
2058
|
-
.where(eq(conversations.id, email.conversationId))
|
|
2059
|
-
.all()[0] ?? null;
|
|
1107
|
+
unblockSender(pattern: string) {
|
|
1108
|
+
return senderSafety.unblockSender(this.context, pattern);
|
|
1109
|
+
}
|
|
2060
1110
|
|
|
2061
|
-
|
|
2062
|
-
|
|
1111
|
+
listBlockedSenders() {
|
|
1112
|
+
return senderSafety.listBlockedSenders(this.context);
|
|
1113
|
+
}
|
|
2063
1114
|
|
|
2064
|
-
|
|
2065
|
-
|
|
1115
|
+
setSenderTrusted(address: string, trusted: boolean) {
|
|
1116
|
+
return senderSafety.setSenderTrusted(this.context, address, trusted);
|
|
1117
|
+
}
|
|
2066
1118
|
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
1119
|
+
reportSpam(input: Parameters<typeof senderSafety.reportSpam>[1]) {
|
|
1120
|
+
return senderSafety.reportSpam(this.context, input);
|
|
1121
|
+
}
|
|
2070
1122
|
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
.onConflictDoNothing()
|
|
2075
|
-
.returning({ id: emails.id })
|
|
2076
|
-
.all();
|
|
2077
|
-
|
|
2078
|
-
if (!inserted.length) return null;
|
|
2079
|
-
indexInsertedEmail(this.state.storage.sql, email.id);
|
|
2080
|
-
insertOfficePreviewJobs(this.state.storage.sql, email);
|
|
2081
|
-
recordCorrespondents(this.state.storage.sql, email);
|
|
2082
|
-
|
|
2083
|
-
const placement = mergedPlacement(
|
|
2084
|
-
before,
|
|
2085
|
-
requestedPlacement(input.placement, folderId)
|
|
2086
|
-
);
|
|
1123
|
+
markNotSpam(input: Parameters<typeof senderSafety.markNotSpam>[1]) {
|
|
1124
|
+
return senderSafety.markNotSpam(this.context, input);
|
|
1125
|
+
}
|
|
2087
1126
|
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
.where(eq(conversations.id, email.conversationId))
|
|
2092
|
-
.run();
|
|
2093
|
-
}
|
|
1127
|
+
submitOutgoing(input: NewEmail, userId: string, draft?: SendingDraft) {
|
|
1128
|
+
return mailboxOutbound.submitOutgoing(this.context, input, userId, draft);
|
|
1129
|
+
}
|
|
2094
1130
|
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
.values({ userId, emailId: email.id, readAt: receivedAt })
|
|
2099
|
-
.onConflictDoNothing()
|
|
2100
|
-
.run();
|
|
2101
|
-
}
|
|
2102
|
-
}
|
|
2103
|
-
|
|
2104
|
-
return { folderSkipped };
|
|
2105
|
-
});
|
|
2106
|
-
|
|
2107
|
-
if (!stored) {
|
|
2108
|
-
const existing = this.getEmail(id);
|
|
2109
|
-
|
|
2110
|
-
return {
|
|
2111
|
-
status: "duplicate",
|
|
2112
|
-
id,
|
|
2113
|
-
conversationId: existing?.conversationId ?? email.conversationId,
|
|
2114
|
-
};
|
|
2115
|
-
}
|
|
2116
|
-
|
|
2117
|
-
this.recentParticipantSources = null;
|
|
2118
|
-
this.state.storage.kv.put(IMPORT_PENDING_KEY, true);
|
|
2119
|
-
await this.scheduleAlarm(
|
|
2120
|
-
Date.now() +
|
|
2121
|
-
(hasPendingOfficePreviews(email)
|
|
2122
|
-
? ALARM_WAKE_DELAY_MS
|
|
2123
|
-
: IMPORT_ANNOUNCE_DELAY_MS)
|
|
2124
|
-
);
|
|
2125
|
-
|
|
2126
|
-
return {
|
|
2127
|
-
status: "imported",
|
|
2128
|
-
id,
|
|
2129
|
-
conversationId: email.conversationId,
|
|
2130
|
-
folderSkipped: stored.folderSkipped,
|
|
2131
|
-
};
|
|
2132
|
-
}
|
|
2133
|
-
|
|
2134
|
-
/** The custom folder with this name (any case), created when missing; why not, when it cannot be. */
|
|
2135
|
-
private importFolder(
|
|
2136
|
-
name: string
|
|
2137
|
-
): { id: string } | { skipped: "limit" | "invalid" } {
|
|
2138
|
-
const normalized = name.trim().toLocaleLowerCase("en-US");
|
|
2139
|
-
|
|
2140
|
-
const existing = this.db
|
|
2141
|
-
.select({ id: folders.id, name: folders.name })
|
|
2142
|
-
.from(folders)
|
|
2143
|
-
.all()
|
|
2144
|
-
.find((folder) => folder.name.toLocaleLowerCase("en-US") === normalized);
|
|
2145
|
-
|
|
2146
|
-
if (existing) return { id: existing.id };
|
|
2147
|
-
const created = this.insertFolder(createId("fld"), name);
|
|
2148
|
-
|
|
2149
|
-
if (created.status === "ok") return { id: created.folder.id };
|
|
2150
|
-
|
|
2151
|
-
// A system folder's name ("Sent", "Archive") is no custom folder.
|
|
2152
|
-
return { skipped: created.status === "limit" ? "limit" : "invalid" };
|
|
2153
|
-
}
|
|
2154
|
-
|
|
2155
|
-
/**
|
|
2156
|
-
* Announces what imports stored since the last time: writes the inbox
|
|
2157
|
-
* counts to D1 once, bumps the JMAP state, and tells open apps to refresh.
|
|
2158
|
-
* Push subscribers are not told; imported mail is not new mail.
|
|
2159
|
-
*/
|
|
2160
|
-
async finishImport() {
|
|
2161
|
-
if (this.state.storage.kv.get<boolean>(IMPORT_PENDING_KEY)) {
|
|
2162
|
-
this.state.storage.kv.delete(IMPORT_PENDING_KEY);
|
|
2163
|
-
bumpJmapState(this.state.storage);
|
|
2164
|
-
const countsWritten = this.syncInboxCounts();
|
|
2165
|
-
this.state.waitUntil(
|
|
2166
|
-
this.broadcastUpdate(countsWritten).catch((error) => {
|
|
2167
|
-
console.error("Could not authorize realtime delivery", error);
|
|
2168
|
-
})
|
|
2169
|
-
);
|
|
2170
|
-
this.announceJmapState(false);
|
|
2171
|
-
await countsWritten;
|
|
2172
|
-
}
|
|
2173
|
-
|
|
2174
|
-
return { version: this.version() };
|
|
2175
|
-
}
|
|
2176
|
-
|
|
2177
|
-
/**
|
|
2178
|
-
* DNS intelligence and receiver signals for a parsed delivery, gathered
|
|
2179
|
-
* before AI classification so the model can use them. Fails open.
|
|
2180
|
-
*/
|
|
2181
|
-
private async inboundSenderSignals(email: NewEmail, links: string[]) {
|
|
2182
|
-
let identity: WorkspaceIdentity = { domains: [], names: new Map() };
|
|
2183
|
-
let dqsKey: string | null = null;
|
|
2184
|
-
let workspaceBlocks = new Map<string, number>();
|
|
2185
|
-
|
|
2186
|
-
try {
|
|
2187
|
-
[identity, dqsKey, workspaceBlocks] = await Promise.all([
|
|
2188
|
-
workspaceIdentity(this.bindings.DB),
|
|
2189
|
-
spamhausDqsKey(this.bindings),
|
|
2190
|
-
workspaceBlockPatterns(this.bindings.DB),
|
|
2191
|
-
]);
|
|
2192
|
-
} catch (error) {
|
|
2193
|
-
console.error(
|
|
2194
|
-
"Could not read workspace identity for sender checks",
|
|
2195
|
-
error
|
|
2196
|
-
);
|
|
2197
|
-
}
|
|
2198
|
-
|
|
2199
|
-
const stored = email.authenticationResultsJson;
|
|
2200
|
-
const authentication = stored ?? null;
|
|
2201
|
-
const from = email.fromJson[0] ?? { address: "", name: null };
|
|
2202
|
-
const storage = this.state.storage.sql;
|
|
2203
|
-
|
|
2204
|
-
const status = from.address
|
|
2205
|
-
? senderStatuses(storage, [from.address]).get(
|
|
2206
|
-
from.address.toLocaleLowerCase()
|
|
2207
|
-
)
|
|
2208
|
-
: undefined;
|
|
2209
|
-
|
|
2210
|
-
const block =
|
|
2211
|
-
workspaceBlockFor(from.address, workspaceBlocks) ?? status?.block ?? null;
|
|
2212
|
-
|
|
2213
|
-
const trusted = Boolean(status?.trustedAt) && !block;
|
|
2214
|
-
let intel: SenderIntel | null = null;
|
|
2215
|
-
|
|
2216
|
-
try {
|
|
2217
|
-
intel = await collectSenderIntel({
|
|
2218
|
-
authentication,
|
|
2219
|
-
fromAddress: from.address,
|
|
2220
|
-
linkDomains: links,
|
|
2221
|
-
workspaceDomains: identity.domains,
|
|
2222
|
-
dqsKey,
|
|
2223
|
-
bucket: this.bindings.MAIL_STORAGE,
|
|
2224
|
-
});
|
|
2225
|
-
} catch (error) {
|
|
2226
|
-
console.error(
|
|
2227
|
-
`Could not collect sender intelligence for ${email.id}`,
|
|
2228
|
-
error
|
|
2229
|
-
);
|
|
2230
|
-
}
|
|
2231
|
-
|
|
2232
|
-
const history = senderHistory(storage, [from.address]).get(
|
|
2233
|
-
from.address.toLocaleLowerCase()
|
|
2234
|
-
);
|
|
2235
|
-
|
|
2236
|
-
const delivery = deliveryFacts({
|
|
2237
|
-
authentication,
|
|
2238
|
-
deliveredTo: email.envelopeTo ?? null,
|
|
2239
|
-
to: (email.toJson ?? []).map((item) => item.address),
|
|
2240
|
-
cc: (email.ccJson ?? []).map((item) => item.address),
|
|
2241
|
-
listId: email.listId ?? null,
|
|
2242
|
-
workspaceDomains: identity.domains,
|
|
2243
|
-
isKnownAddressee: (address) => this.isKnownAddressee(address),
|
|
2244
|
-
});
|
|
2245
|
-
|
|
2246
|
-
const security = messageSecurity({
|
|
2247
|
-
fromAddress: from.address,
|
|
2248
|
-
fromName: from.name,
|
|
2249
|
-
authentication,
|
|
2250
|
-
listUnsubscribe: null,
|
|
2251
|
-
workspaceDomains: identity.domains,
|
|
2252
|
-
internalNames: identity.names,
|
|
2253
|
-
intel,
|
|
2254
|
-
// Counted as if this message were already stored.
|
|
2255
|
-
history: {
|
|
2256
|
-
inboundCount: (history?.inboundCount ?? 0) + 1,
|
|
2257
|
-
outboundCount: history?.outboundCount ?? 0,
|
|
2258
|
-
},
|
|
2259
|
-
replyTo: (email.replyToJson ?? []).map((item) => item.address),
|
|
2260
|
-
listId: email.listId ?? null,
|
|
2261
|
-
delivery,
|
|
2262
|
-
trusted,
|
|
2263
|
-
});
|
|
2264
|
-
|
|
2265
|
-
const screening: InboundScreening = { block, trusted };
|
|
2266
|
-
|
|
2267
|
-
let workspaceFeedback: Awaited<
|
|
2268
|
-
ReturnType<typeof workspaceFeedbackSummary>
|
|
2269
|
-
> | null = null;
|
|
2270
|
-
|
|
2271
|
-
const mailboxId = this.state.id.name;
|
|
2272
|
-
|
|
2273
|
-
if (from.address && mailboxId && !block) {
|
|
2274
|
-
try {
|
|
2275
|
-
workspaceFeedback = await workspaceFeedbackSummary(
|
|
2276
|
-
this.bindings.DB,
|
|
2277
|
-
mailboxId,
|
|
2278
|
-
from.address
|
|
2279
|
-
);
|
|
2280
|
-
} catch (error) {
|
|
2281
|
-
console.error(
|
|
2282
|
-
`Could not read workspace feedback for ${email.id}`,
|
|
2283
|
-
error
|
|
2284
|
-
);
|
|
2285
|
-
}
|
|
2286
|
-
}
|
|
2287
|
-
|
|
2288
|
-
return {
|
|
2289
|
-
intel,
|
|
2290
|
-
delivery,
|
|
2291
|
-
screening,
|
|
2292
|
-
signals: classificationSignals({
|
|
2293
|
-
authentication,
|
|
2294
|
-
intel,
|
|
2295
|
-
firstTimeSender: security.firstTimeSender,
|
|
2296
|
-
warnings: security.warnings,
|
|
2297
|
-
feedback: from.address
|
|
2298
|
-
? senderFeedbackSummary(storage, from.address)
|
|
2299
|
-
: null,
|
|
2300
|
-
workspaceFeedback,
|
|
2301
|
-
delivery,
|
|
2302
|
-
}),
|
|
2303
|
-
};
|
|
2304
|
-
}
|
|
2305
|
-
|
|
2306
|
-
/** Mail written to this address already reached the mailbox from at least two senders. */
|
|
2307
|
-
private isKnownAddressee(address: string) {
|
|
2308
|
-
const [row] = this.state.storage.sql
|
|
2309
|
-
.exec<{ senders: number }>(
|
|
2310
|
-
`
|
|
2311
|
-
select count(distinct lower(json_extract(message.from_json, '$[0].address'))) as senders
|
|
2312
|
-
from emails message
|
|
2313
|
-
where message.direction = 'incoming'
|
|
2314
|
-
and exists (
|
|
2315
|
-
select 1 from json_each(message.to_json) recipient
|
|
2316
|
-
where lower(json_extract(recipient.value, '$.address')) = ?1
|
|
2317
|
-
union all
|
|
2318
|
-
select 1 from json_each(message.cc_json) recipient
|
|
2319
|
-
where lower(json_extract(recipient.value, '$.address')) = ?1
|
|
2320
|
-
)
|
|
2321
|
-
`,
|
|
2322
|
-
address.toLocaleLowerCase()
|
|
2323
|
-
)
|
|
2324
|
-
.toArray();
|
|
2325
|
-
|
|
2326
|
-
return Number(row?.senders ?? 0) >= 2;
|
|
2327
|
-
}
|
|
2328
|
-
|
|
2329
|
-
/** Blocks win over AI; trusted senders override an AI spam verdict. */
|
|
2330
|
-
private inboundPlacement(
|
|
2331
|
-
screening: InboundScreening,
|
|
2332
|
-
classification: EmailAiClassification | null
|
|
2333
|
-
): InboundPlacement {
|
|
2334
|
-
if (screening.block) return { state: "spam", folderId: null };
|
|
2335
|
-
|
|
2336
|
-
if (classification?.spam && !screening.trusted) {
|
|
2337
|
-
return { state: "spam", folderId: null };
|
|
2338
|
-
}
|
|
2339
|
-
|
|
2340
|
-
return { state: null, folderId: classification?.folderId ?? null };
|
|
2341
|
-
}
|
|
2342
|
-
|
|
2343
|
-
/** The model from openworkspace.json; tests substitute one on the instance. */
|
|
2344
|
-
protected classificationModel(): Promise<AiModel | null> {
|
|
2345
|
-
return aiModel(this.bindings, "classification");
|
|
2346
|
-
}
|
|
2347
|
-
|
|
2348
|
-
private async classifyInbound(
|
|
2349
|
-
rawMime: ArrayBuffer,
|
|
2350
|
-
signals: ClassificationSignals | null
|
|
2351
|
-
) {
|
|
2352
|
-
let ai: AiModel | null;
|
|
2353
|
-
|
|
2354
|
-
try {
|
|
2355
|
-
ai = await this.classificationModel();
|
|
2356
|
-
} catch (error) {
|
|
2357
|
-
throw new EmailAiClassificationError(
|
|
2358
|
-
"The classification model is misconfigured",
|
|
2359
|
-
{ cause: error }
|
|
2360
|
-
);
|
|
2361
|
-
}
|
|
2362
|
-
|
|
2363
|
-
if (!ai) return null;
|
|
2364
|
-
const configuration = this.aiConfiguration();
|
|
2365
|
-
|
|
2366
|
-
const customFolders = this.db
|
|
2367
|
-
.select({ id: folders.id, name: folders.name })
|
|
2368
|
-
.from(folders)
|
|
2369
|
-
.orderBy(asc(folders.sortOrder), asc(folders.name))
|
|
2370
|
-
.all();
|
|
2371
|
-
|
|
2372
|
-
return classifyInboundEmail({
|
|
2373
|
-
rawMime,
|
|
2374
|
-
folders: customFolders,
|
|
2375
|
-
configuration,
|
|
2376
|
-
signals,
|
|
2377
|
-
model: ai.id,
|
|
2378
|
-
run: aiObjectRunner(ai),
|
|
2379
|
-
});
|
|
2380
|
-
}
|
|
2381
|
-
|
|
2382
|
-
private insertClassifiedInboundEmail(
|
|
2383
|
-
input: NewEmail,
|
|
2384
|
-
classification: EmailAiClassification | null,
|
|
2385
|
-
placement: InboundPlacement
|
|
2386
|
-
) {
|
|
2387
|
-
const prepared = prepareOfficePreviews(input);
|
|
2388
|
-
|
|
2389
|
-
const stored = this.db.transaction((tx) => {
|
|
2390
|
-
// Threading trusts the sender's In-Reply-To and References, so spam
|
|
2391
|
-
// that names a message here starts its own conversation instead of
|
|
2392
|
-
// moving (or reviving) one with other mail. Spam may join spam.
|
|
2393
|
-
const joined = placement.state
|
|
2394
|
-
? tx
|
|
2395
|
-
.select({ mailboxState: conversations.mailboxState })
|
|
2396
|
-
.from(conversations)
|
|
2397
|
-
.where(eq(conversations.id, prepared.conversationId))
|
|
2398
|
-
.all()[0]
|
|
2399
|
-
: undefined;
|
|
2400
|
-
|
|
2401
|
-
// The conversation it named is recorded, so the message rejoins it
|
|
2402
|
-
// when it leaves Spam (rejoinSplitConversations).
|
|
2403
|
-
const email =
|
|
2404
|
-
joined && joined.mailboxState !== placement.state
|
|
2405
|
-
? {
|
|
2406
|
-
...prepared,
|
|
2407
|
-
conversationId: createId("conv"),
|
|
2408
|
-
splitFromConversationId: prepared.conversationId,
|
|
2409
|
-
}
|
|
2410
|
-
: prepared;
|
|
2411
|
-
|
|
2412
|
-
const trustedFolder = placement.folderId
|
|
2413
|
-
? tx
|
|
2414
|
-
.select({ id: folders.id })
|
|
2415
|
-
.from(folders)
|
|
2416
|
-
.where(eq(folders.id, placement.folderId))
|
|
2417
|
-
.all()[0]
|
|
2418
|
-
: null;
|
|
2419
|
-
|
|
2420
|
-
const normalizedClassification =
|
|
2421
|
-
classification?.folderId &&
|
|
2422
|
-
!tx
|
|
2423
|
-
.select({ id: folders.id })
|
|
2424
|
-
.from(folders)
|
|
2425
|
-
.where(eq(folders.id, classification.folderId))
|
|
2426
|
-
.all()[0]
|
|
2427
|
-
? { ...classification, folderId: null }
|
|
2428
|
-
: classification;
|
|
2429
|
-
|
|
2430
|
-
const inserted = tx
|
|
2431
|
-
.insert(emails)
|
|
2432
|
-
.values({
|
|
2433
|
-
...email,
|
|
2434
|
-
aiClassificationJson: normalizedClassification,
|
|
2435
|
-
})
|
|
2436
|
-
.onConflictDoNothing()
|
|
2437
|
-
.returning()
|
|
2438
|
-
.all()[0];
|
|
2439
|
-
|
|
2440
|
-
if (!inserted) return null;
|
|
2441
|
-
indexInsertedEmail(this.state.storage.sql, inserted.id);
|
|
2442
|
-
insertOfficePreviewJobs(this.state.storage.sql, email);
|
|
2443
|
-
recordCorrespondents(this.state.storage.sql, email);
|
|
2444
|
-
|
|
2445
|
-
const activeConversation = and(
|
|
2446
|
-
eq(conversations.id, email.conversationId),
|
|
2447
|
-
eq(conversations.mailboxState, "active")
|
|
2448
|
-
);
|
|
2449
|
-
|
|
2450
|
-
// AI sorting files only the first incoming message of a conversation:
|
|
2451
|
-
// a reply to received mail (whose threading headers the sender chose)
|
|
2452
|
-
// leaves the thread where it is. Replies to a thread this mailbox
|
|
2453
|
-
// started are filed like new mail.
|
|
2454
|
-
const startsConversation = !tx
|
|
2455
|
-
.select({ id: emails.id })
|
|
2456
|
-
.from(emails)
|
|
2457
|
-
.where(
|
|
2458
|
-
and(
|
|
2459
|
-
eq(emails.conversationId, email.conversationId),
|
|
2460
|
-
eq(emails.direction, "incoming"),
|
|
2461
|
-
ne(emails.id, inserted.id)
|
|
2462
|
-
)
|
|
2463
|
-
)
|
|
2464
|
-
.limit(1)
|
|
2465
|
-
.all()[0];
|
|
2466
|
-
|
|
2467
|
-
if (placement.state) {
|
|
2468
|
-
tx.update(conversations)
|
|
2469
|
-
.set({ mailboxState: placement.state, folderId: null })
|
|
2470
|
-
.where(activeConversation)
|
|
2471
|
-
.run();
|
|
2472
|
-
} else if (trustedFolder && startsConversation) {
|
|
2473
|
-
tx.update(conversations)
|
|
2474
|
-
.set({ folderId: trustedFolder.id })
|
|
2475
|
-
.where(and(activeConversation, isNull(conversations.folderId)))
|
|
2476
|
-
.run();
|
|
2477
|
-
}
|
|
2478
|
-
|
|
2479
|
-
return (
|
|
2480
|
-
tx.select().from(emails).where(eq(emails.id, inserted.id)).all()[0] ??
|
|
2481
|
-
null
|
|
2482
|
-
);
|
|
2483
|
-
});
|
|
2484
|
-
|
|
2485
|
-
this.recentParticipantSources = null;
|
|
2486
|
-
|
|
2487
|
-
return stored;
|
|
2488
|
-
}
|
|
2489
|
-
|
|
2490
|
-
/**
|
|
2491
|
-
* Fills sender intelligence in on view: for a message without any, or
|
|
2492
|
-
* replacing the failed result checked at `replacesCheckedAt`.
|
|
2493
|
-
*/
|
|
2494
|
-
setEmailSenderIntel(
|
|
2495
|
-
emailId: string,
|
|
2496
|
-
intel: SenderIntel,
|
|
2497
|
-
replacesCheckedAt: number | null = null
|
|
2498
|
-
) {
|
|
2499
|
-
const current =
|
|
2500
|
-
replacesCheckedAt === null
|
|
2501
|
-
? isNull(emails.senderIntelJson)
|
|
2502
|
-
: sql`json_extract(${emails.senderIntelJson}, '$.checkedAt') = ${replacesCheckedAt}`;
|
|
2503
|
-
|
|
2504
|
-
return (
|
|
2505
|
-
this.db
|
|
2506
|
-
.update(emails)
|
|
2507
|
-
.set({ senderIntelJson: intel })
|
|
2508
|
-
.where(
|
|
2509
|
-
and(eq(emails.id, emailId), eq(emails.direction, "incoming"), current)
|
|
2510
|
-
)
|
|
2511
|
-
.returning({ id: emails.id })
|
|
2512
|
-
.all().length > 0
|
|
2513
|
-
);
|
|
2514
|
-
}
|
|
2515
|
-
|
|
2516
|
-
/** Inbound/outbound counters for the given addresses (lowercased keys). */
|
|
2517
|
-
getSenderHistory(addresses: string[]) {
|
|
2518
|
-
return Object.fromEntries(senderHistory(this.state.storage.sql, addresses));
|
|
2519
|
-
}
|
|
2520
|
-
|
|
2521
|
-
/** Block, trust and report state for senders, and unsubscribe records for lists. */
|
|
2522
|
-
getMessageSafetyContext(addresses: string[], listKeys: string[]) {
|
|
2523
|
-
const keys = [...new Set(listKeys)].slice(0, 100);
|
|
2524
|
-
|
|
2525
|
-
const rows = keys.length
|
|
2526
|
-
? this.db
|
|
2527
|
-
.select()
|
|
2528
|
-
.from(unsubscriptions)
|
|
2529
|
-
.where(inArray(unsubscriptions.listKey, keys))
|
|
2530
|
-
.all()
|
|
2531
|
-
: [];
|
|
2532
|
-
|
|
2533
|
-
return {
|
|
2534
|
-
senders: Object.fromEntries(
|
|
2535
|
-
senderStatuses(this.state.storage.sql, addresses)
|
|
2536
|
-
),
|
|
2537
|
-
unsubscriptions: Object.fromEntries(
|
|
2538
|
-
rows.map((row): [string, Unsubscription] => [
|
|
2539
|
-
row.listKey,
|
|
2540
|
-
{
|
|
2541
|
-
listKey: row.listKey,
|
|
2542
|
-
method: row.method,
|
|
2543
|
-
status: row.status,
|
|
2544
|
-
target: row.target,
|
|
2545
|
-
at: row.createdAt.getTime(),
|
|
2546
|
-
},
|
|
2547
|
-
])
|
|
2548
|
-
),
|
|
2549
|
-
};
|
|
2550
|
-
}
|
|
2551
|
-
|
|
2552
|
-
recordUnsubscription(input: {
|
|
2553
|
-
listKey: string;
|
|
2554
|
-
emailId: string;
|
|
2555
|
-
method: Unsubscription["method"];
|
|
2556
|
-
status: Unsubscription["status"];
|
|
2557
|
-
target: string | null;
|
|
2558
|
-
detail: string | null;
|
|
2559
|
-
userId: string;
|
|
2560
|
-
}): Unsubscription {
|
|
2561
|
-
const createdAt = new Date();
|
|
2562
|
-
const values = { ...input, createdAt };
|
|
2563
|
-
this.db
|
|
2564
|
-
.insert(unsubscriptions)
|
|
2565
|
-
.values(values)
|
|
2566
|
-
.onConflictDoUpdate({ target: unsubscriptions.listKey, set: values })
|
|
2567
|
-
.run();
|
|
2568
|
-
this.publishUpdate();
|
|
2569
|
-
|
|
2570
|
-
return {
|
|
2571
|
-
listKey: input.listKey,
|
|
2572
|
-
method: input.method,
|
|
2573
|
-
status: input.status,
|
|
2574
|
-
target: input.target,
|
|
2575
|
-
at: createdAt.getTime(),
|
|
2576
|
-
};
|
|
2577
|
-
}
|
|
2578
|
-
|
|
2579
|
-
/** Moves every Inbox or Archive conversation with mail from the pattern to Spam. */
|
|
2580
|
-
private moveSenderConversationsToSpam(pattern: string) {
|
|
2581
|
-
const predicate = blockPatternPredicate(
|
|
2582
|
-
"lower(json_extract(message.from_json, '$[0].address'))",
|
|
2583
|
-
pattern
|
|
2584
|
-
);
|
|
2585
|
-
|
|
2586
|
-
return this.state.storage.sql
|
|
2587
|
-
.exec<{ id: string }>(
|
|
2588
|
-
`
|
|
2589
|
-
update conversations
|
|
2590
|
-
set mailbox_state = 'spam', folder_id = null
|
|
2591
|
-
where mailbox_state in ('active', 'archive')
|
|
2592
|
-
and id in (
|
|
2593
|
-
select message.conversation_id from emails message
|
|
2594
|
-
where message.direction = 'incoming' and ${predicate.sql}
|
|
2595
|
-
)
|
|
2596
|
-
returning id
|
|
2597
|
-
`,
|
|
2598
|
-
...predicate.bindings
|
|
2599
|
-
)
|
|
2600
|
-
.toArray().length;
|
|
2601
|
-
}
|
|
2602
|
-
|
|
2603
|
-
blockSender(pattern: string, moveExisting: boolean) {
|
|
2604
|
-
const moved = this.db.transaction(() => {
|
|
2605
|
-
setSenderBlocked(this.state.storage.sql, pattern, true, Date.now());
|
|
2606
|
-
|
|
2607
|
-
return moveExisting ? this.moveSenderConversationsToSpam(pattern) : 0;
|
|
2608
|
-
});
|
|
2609
|
-
|
|
2610
|
-
this.recentParticipantSources = null;
|
|
2611
|
-
this.publishUpdate();
|
|
2612
|
-
|
|
2613
|
-
return { block: blockFromPattern(pattern, Date.now(), false), moved };
|
|
2614
|
-
}
|
|
2615
|
-
|
|
2616
|
-
/** For a workspace-wide block: existing mail goes to Spam; the block itself lives in D1. */
|
|
2617
|
-
moveSenderToSpam(pattern: string) {
|
|
2618
|
-
const moved = this.moveSenderConversationsToSpam(pattern);
|
|
2619
|
-
|
|
2620
|
-
if (moved) {
|
|
2621
|
-
this.recentParticipantSources = null;
|
|
2622
|
-
this.publishUpdate();
|
|
2623
|
-
}
|
|
2624
|
-
|
|
2625
|
-
return moved;
|
|
2626
|
-
}
|
|
2627
|
-
|
|
2628
|
-
unblockSender(pattern: string) {
|
|
2629
|
-
const existed =
|
|
2630
|
-
this.state.storage.sql
|
|
2631
|
-
.exec(
|
|
2632
|
-
"select 1 from senders where address = ? and blocked_at is not null",
|
|
2633
|
-
pattern
|
|
2634
|
-
)
|
|
2635
|
-
.toArray().length > 0;
|
|
2636
|
-
|
|
2637
|
-
setSenderBlocked(this.state.storage.sql, pattern, false, Date.now());
|
|
2638
|
-
this.recentParticipantSources = null;
|
|
2639
|
-
this.publishUpdate();
|
|
2640
|
-
|
|
2641
|
-
return existed;
|
|
2642
|
-
}
|
|
2643
|
-
|
|
2644
|
-
listBlockedSenders() {
|
|
2645
|
-
return listBlockedSenders(this.state.storage.sql);
|
|
2646
|
-
}
|
|
2647
|
-
|
|
2648
|
-
setSenderTrusted(address: string, trusted: boolean) {
|
|
2649
|
-
setSenderTrusted(this.state.storage.sql, address, trusted, Date.now());
|
|
2650
|
-
this.publishUpdate();
|
|
2651
|
-
|
|
2652
|
-
return true;
|
|
2653
|
-
}
|
|
2654
|
-
|
|
2655
|
-
/** The newest incoming message of each conversation, for actions that need a sender. */
|
|
2656
|
-
latestIncomingEmails(conversationIds: string[]) {
|
|
2657
|
-
const ids = [...new Set(conversationIds)].slice(0, 100);
|
|
2658
|
-
|
|
2659
|
-
if (!ids.length) return [];
|
|
2660
|
-
|
|
2661
|
-
const rows = this.state.storage.sql
|
|
2662
|
-
.exec<{ id: string }>(
|
|
2663
|
-
`
|
|
2664
|
-
select (
|
|
2665
|
-
select message.id from emails message
|
|
2666
|
-
where message.conversation_id = requested.value and message.direction = 'incoming'
|
|
2667
|
-
order by message.timeline_at desc, message.id desc limit 1
|
|
2668
|
-
) as id
|
|
2669
|
-
from json_each(?) requested
|
|
2670
|
-
`,
|
|
2671
|
-
stringListJson(ids)
|
|
2672
|
-
)
|
|
2673
|
-
.toArray()
|
|
2674
|
-
.flatMap((row) => (row.id ? [row.id] : []));
|
|
2675
|
-
|
|
2676
|
-
return rows.length
|
|
2677
|
-
? this.db.select().from(emails).where(inArray(emails.id, rows)).all()
|
|
2678
|
-
: [];
|
|
2679
|
-
}
|
|
2680
|
-
|
|
2681
|
-
/**
|
|
2682
|
-
* Report spam: labels the message, records feedback for the classifier,
|
|
2683
|
-
* and moves its conversation to Spam. Never contacts the sender.
|
|
2684
|
-
*/
|
|
2685
|
-
reportMessage(input: { emailId: string; userId: string }) {
|
|
2686
|
-
const email = this.getEmail(input.emailId);
|
|
2687
|
-
|
|
2688
|
-
if (!email || email.direction !== "incoming") return null;
|
|
2689
|
-
const address = email.fromJson[0]?.address ?? "";
|
|
2690
|
-
|
|
2691
|
-
const moved = this.db.transaction((tx) => {
|
|
2692
|
-
tx.update(emails)
|
|
2693
|
-
.set({ reportLabel: "spam" })
|
|
2694
|
-
.where(eq(emails.id, email.id))
|
|
2695
|
-
.run();
|
|
2696
|
-
|
|
2697
|
-
if (address.includes("@")) {
|
|
2698
|
-
recordSenderFeedback(this.state.storage.sql, {
|
|
2699
|
-
id: createId("fbk"),
|
|
2700
|
-
address,
|
|
2701
|
-
emailId: email.id,
|
|
2702
|
-
label: "spam",
|
|
2703
|
-
userId: input.userId,
|
|
2704
|
-
now: Date.now(),
|
|
2705
|
-
});
|
|
2706
|
-
}
|
|
2707
|
-
|
|
2708
|
-
return (
|
|
2709
|
-
tx
|
|
2710
|
-
.update(conversations)
|
|
2711
|
-
.set({ mailboxState: "spam", folderId: null })
|
|
2712
|
-
.where(
|
|
2713
|
-
and(
|
|
2714
|
-
eq(conversations.id, email.conversationId),
|
|
2715
|
-
inArray(conversations.mailboxState, ["active", "archive"])
|
|
2716
|
-
)
|
|
2717
|
-
)
|
|
2718
|
-
.returning({ id: conversations.id })
|
|
2719
|
-
.all().length > 0
|
|
2720
|
-
);
|
|
2721
|
-
});
|
|
2722
|
-
|
|
2723
|
-
this.recentParticipantSources = null;
|
|
2724
|
-
this.publishUpdate();
|
|
2725
|
-
|
|
2726
|
-
return {
|
|
2727
|
-
email: required(this.getEmail(email.id), "The reported email exists"),
|
|
2728
|
-
moved,
|
|
2729
|
-
};
|
|
2730
|
-
}
|
|
2731
|
-
|
|
2732
|
-
/** "Not spam": back to Inbox, the sender becomes trusted, and the feedback is recorded. */
|
|
2733
|
-
markNotSpam(input: { emailId: string; userId: string }) {
|
|
2734
|
-
const email = this.getEmail(input.emailId);
|
|
2735
|
-
|
|
2736
|
-
if (!email || email.direction !== "incoming") return null;
|
|
2737
|
-
const address = email.fromJson[0]?.address ?? "";
|
|
2738
|
-
const label: FeedbackLabel = "not_spam";
|
|
2739
|
-
|
|
2740
|
-
const outcome = this.db.transaction((tx) => {
|
|
2741
|
-
tx.update(emails)
|
|
2742
|
-
.set({ reportLabel: null })
|
|
2743
|
-
.where(eq(emails.conversationId, email.conversationId))
|
|
2744
|
-
.run();
|
|
2745
|
-
|
|
2746
|
-
if (address.includes("@")) {
|
|
2747
|
-
recordSenderFeedback(this.state.storage.sql, {
|
|
2748
|
-
id: createId("fbk"),
|
|
2749
|
-
address,
|
|
2750
|
-
emailId: email.id,
|
|
2751
|
-
label,
|
|
2752
|
-
userId: input.userId,
|
|
2753
|
-
now: Date.now(),
|
|
2754
|
-
});
|
|
2755
|
-
setSenderTrusted(this.state.storage.sql, address, true, Date.now());
|
|
2756
|
-
}
|
|
2757
|
-
|
|
2758
|
-
const back =
|
|
2759
|
-
tx
|
|
2760
|
-
.update(conversations)
|
|
2761
|
-
.set({ mailboxState: "active" })
|
|
2762
|
-
.where(
|
|
2763
|
-
and(
|
|
2764
|
-
eq(conversations.id, email.conversationId),
|
|
2765
|
-
eq(conversations.mailboxState, "spam")
|
|
2766
|
-
)
|
|
2767
|
-
)
|
|
2768
|
-
.returning({ id: conversations.id })
|
|
2769
|
-
.all().length > 0;
|
|
2770
|
-
|
|
2771
|
-
// Spam that named a conversation here was kept out of it; once it is
|
|
2772
|
-
// not spam, it rejoins that conversation.
|
|
2773
|
-
const conversationId = back
|
|
2774
|
-
? (this.rejoinSplitConversations([email.conversationId]).get(
|
|
2775
|
-
email.conversationId
|
|
2776
|
-
) ?? email.conversationId)
|
|
2777
|
-
: email.conversationId;
|
|
2778
|
-
|
|
2779
|
-
const place = tx
|
|
2780
|
-
.select({
|
|
2781
|
-
mailboxState: conversations.mailboxState,
|
|
2782
|
-
folderId: conversations.folderId,
|
|
2783
|
-
})
|
|
2784
|
-
.from(conversations)
|
|
2785
|
-
.where(eq(conversations.id, conversationId))
|
|
2786
|
-
.all()[0];
|
|
2787
|
-
|
|
2788
|
-
return {
|
|
2789
|
-
restored: back,
|
|
2790
|
-
conversationId,
|
|
2791
|
-
folder: place ? conversationFolder(place) : "inbox",
|
|
2792
|
-
};
|
|
2793
|
-
});
|
|
2794
|
-
|
|
2795
|
-
this.recentParticipantSources = null;
|
|
2796
|
-
this.publishUpdate();
|
|
2797
|
-
|
|
2798
|
-
return {
|
|
2799
|
-
restored: outcome.restored,
|
|
2800
|
-
conversationId: outcome.conversationId,
|
|
2801
|
-
rejoined: outcome.conversationId !== email.conversationId,
|
|
2802
|
-
folder: outcome.folder,
|
|
2803
|
-
address: address.includes("@") ? address : null,
|
|
2804
|
-
};
|
|
2805
|
-
}
|
|
2806
|
-
|
|
2807
|
-
/**
|
|
2808
|
-
* Puts mail kept out of a conversation as spam (#25) back into it, once
|
|
2809
|
-
* its own conversation has left Spam: by Not spam, a move in the app or
|
|
2810
|
-
* over JMAP, or a reply sent from here. Call it inside the transaction
|
|
2811
|
-
* that moved `conversationIds`; only those now in Inbox or Archive that
|
|
2812
|
-
* hold a message marked with `split_from_conversation_id` are touched, so
|
|
2813
|
-
* conversations threaded elsewhere (an import's, say) are never merged.
|
|
2814
|
-
*
|
|
2815
|
-
* The marked message names the conversation it was kept out of. When that
|
|
2816
|
-
* conversation is gone, the message's own threading headers are resolved
|
|
2817
|
-
* again. The conversation rejoins its target when the target is in Inbox
|
|
2818
|
-
* or Archive; a target in Trash or Spam is not brought back by it, and the
|
|
2819
|
-
* conversation stays where it was moved. Either way the decision is final
|
|
2820
|
-
* and the mark is cleared.
|
|
2821
|
-
*
|
|
2822
|
-
* The rescued message is placed as a legitimate reply would be: moved to
|
|
2823
|
-
* Inbox (or a custom folder), the target becomes active and takes that
|
|
2824
|
-
* folder (else keeps its own). Moved to Archive, the target stays where it
|
|
2825
|
-
* is. Returns, for each merged conversation, the one its messages are in.
|
|
2826
|
-
*/
|
|
2827
|
-
private rejoinSplitConversations(conversationIds: string[]) {
|
|
2828
|
-
const merged = new Map<string, string>();
|
|
2829
|
-
|
|
2830
|
-
if (!conversationIds.length) return merged;
|
|
2831
|
-
|
|
2832
|
-
const marked = this.db
|
|
2833
|
-
.select({
|
|
2834
|
-
emailId: emails.id,
|
|
2835
|
-
conversationId: conversations.id,
|
|
2836
|
-
mailboxState: conversations.mailboxState,
|
|
2837
|
-
folderId: conversations.folderId,
|
|
2838
|
-
splitFrom: emails.splitFromConversationId,
|
|
2839
|
-
inReplyTo: emails.inReplyToJson,
|
|
2840
|
-
references: emails.referencesJson,
|
|
2841
|
-
})
|
|
2842
|
-
.from(emails)
|
|
2843
|
-
.innerJoin(conversations, eq(conversations.id, emails.conversationId))
|
|
2844
|
-
.where(
|
|
2845
|
-
and(
|
|
2846
|
-
sql`${conversations.id} in (select cast(value as text) from json_each(${stringListJson(conversationIds)}))`,
|
|
2847
|
-
inArray(conversations.mailboxState, ["active", "archive"]),
|
|
2848
|
-
isNotNull(emails.splitFromConversationId)
|
|
2849
|
-
)
|
|
2850
|
-
)
|
|
2851
|
-
.all();
|
|
2852
|
-
|
|
2853
|
-
const groups = new Map<string, typeof marked>();
|
|
2854
|
-
|
|
2855
|
-
for (const row of marked) {
|
|
2856
|
-
groups.set(row.conversationId, [
|
|
2857
|
-
...(groups.get(row.conversationId) ?? []),
|
|
2858
|
-
row,
|
|
2859
|
-
]);
|
|
2860
|
-
}
|
|
2861
|
-
|
|
2862
|
-
for (const [conversationId, rows] of groups) {
|
|
2863
|
-
const targets = new Set(
|
|
2864
|
-
rows.map((row) => this.splitTarget(conversationId, row))
|
|
2865
|
-
);
|
|
2866
|
-
|
|
2867
|
-
const [target, ...others] = targets;
|
|
2868
|
-
|
|
2869
|
-
this.db
|
|
2870
|
-
.update(emails)
|
|
2871
|
-
.set({ splitFromConversationId: null })
|
|
2872
|
-
.where(
|
|
2873
|
-
and(
|
|
2874
|
-
eq(emails.conversationId, conversationId),
|
|
2875
|
-
isNotNull(emails.splitFromConversationId)
|
|
2876
|
-
)
|
|
2877
|
-
)
|
|
2878
|
-
.run();
|
|
2879
|
-
|
|
2880
|
-
if (!target || others.length) continue;
|
|
2881
|
-
const [moved] = rows;
|
|
2882
|
-
|
|
2883
|
-
if (!moved) continue;
|
|
2884
|
-
mergeConversation(this.state.storage.sql, conversationId, target);
|
|
2885
|
-
|
|
2886
|
-
if (moved.mailboxState === "active") {
|
|
2887
|
-
this.db
|
|
2888
|
-
.update(conversations)
|
|
2889
|
-
.set({
|
|
2890
|
-
mailboxState: "active",
|
|
2891
|
-
folderId: moved.folderId ?? sql`${conversations.folderId}`,
|
|
2892
|
-
})
|
|
2893
|
-
.where(eq(conversations.id, target))
|
|
2894
|
-
.run();
|
|
2895
|
-
}
|
|
2896
|
-
|
|
2897
|
-
merged.set(conversationId, target);
|
|
2898
|
-
}
|
|
2899
|
-
|
|
2900
|
-
return merged;
|
|
2901
|
-
}
|
|
2902
|
-
|
|
2903
|
-
/**
|
|
2904
|
-
* The conversation a marked message rejoins, or null: the one it was kept
|
|
2905
|
-
* out of, else (when that one is gone) its parent's, while that
|
|
2906
|
-
* conversation is in Inbox or Archive.
|
|
2907
|
-
*/
|
|
2908
|
-
private splitTarget(
|
|
2909
|
-
conversationId: string,
|
|
2910
|
-
row: { splitFrom: string | null; inReplyTo: string[]; references: string[] }
|
|
2911
|
-
) {
|
|
2912
|
-
const placeOf = (id: string) =>
|
|
2913
|
-
this.db
|
|
2914
|
-
.select({ mailboxState: conversations.mailboxState })
|
|
2915
|
-
.from(conversations)
|
|
2916
|
-
.where(eq(conversations.id, id))
|
|
2917
|
-
.all()[0];
|
|
2918
|
-
|
|
2919
|
-
let targetId = row.splitFrom;
|
|
2920
|
-
let target = targetId ? placeOf(targetId) : undefined;
|
|
2921
|
-
|
|
2922
|
-
if (!target) {
|
|
2923
|
-
const parent = this.resolveParent(row.inReplyTo, row.references);
|
|
2924
|
-
targetId = parent?.conversationId ?? null;
|
|
2925
|
-
target = targetId ? placeOf(targetId) : undefined;
|
|
2926
|
-
}
|
|
2927
|
-
|
|
2928
|
-
return targetId &&
|
|
2929
|
-
targetId !== conversationId &&
|
|
2930
|
-
(target?.mailboxState === "active" || target?.mailboxState === "archive")
|
|
2931
|
-
? targetId
|
|
2932
|
-
: null;
|
|
2933
|
-
}
|
|
2934
|
-
|
|
2935
|
-
submitOutgoing(input: NewEmail) {
|
|
2936
|
-
return this.state.blockConcurrencyWhile(async () => {
|
|
2937
|
-
if (
|
|
2938
|
-
input.direction !== "outgoing" ||
|
|
2939
|
-
input.transportState !== "unconfirmed"
|
|
2940
|
-
) {
|
|
2941
|
-
throw new Error("Only unconfirmed outgoing messages can be submitted");
|
|
2942
|
-
}
|
|
2943
|
-
|
|
2944
|
-
if (!input.requestFingerprint) {
|
|
2945
|
-
throw new Error("An outgoing request fingerprint is required");
|
|
2946
|
-
}
|
|
2947
|
-
|
|
2948
|
-
const email = prepareOfficePreviews(input);
|
|
2949
|
-
|
|
2950
|
-
if (hasPendingOfficePreviews(email)) {
|
|
2951
|
-
await this.scheduleAlarm(Date.now() + ALARM_WAKE_DELAY_MS);
|
|
2952
|
-
}
|
|
2953
|
-
|
|
2954
|
-
const submission = this.db.transaction((tx): SubmitOutgoingResult => {
|
|
2955
|
-
const existing = tx
|
|
2956
|
-
.select()
|
|
2957
|
-
.from(emails)
|
|
2958
|
-
.where(eq(emails.id, email.id))
|
|
2959
|
-
.all()[0];
|
|
2960
|
-
|
|
2961
|
-
if (existing) {
|
|
2962
|
-
const sameRequest =
|
|
2963
|
-
existing.direction === "outgoing" &&
|
|
2964
|
-
existing.requestFingerprint === email.requestFingerprint;
|
|
2965
|
-
|
|
2966
|
-
return {
|
|
2967
|
-
outcome: sameRequest ? "existing" : "conflict",
|
|
2968
|
-
email: existing,
|
|
2969
|
-
};
|
|
2970
|
-
}
|
|
2971
|
-
|
|
2972
|
-
tx.insert(emails).values(email).run();
|
|
2973
|
-
indexInsertedEmail(this.state.storage.sql, email.id);
|
|
2974
|
-
insertOfficePreviewJobs(this.state.storage.sql, email);
|
|
2975
|
-
recordCorrespondents(this.state.storage.sql, email);
|
|
2976
|
-
// A reply sent from here brings its conversation out of Spam, and
|
|
2977
|
-
// mail kept out of a conversation as spam rejoins it.
|
|
2978
|
-
this.rejoinSplitConversations([email.conversationId]);
|
|
2979
|
-
|
|
2980
|
-
const inserted = tx
|
|
2981
|
-
.select()
|
|
2982
|
-
.from(emails)
|
|
2983
|
-
.where(eq(emails.id, email.id))
|
|
2984
|
-
.all()[0];
|
|
2985
|
-
|
|
2986
|
-
if (!inserted) throw new Error("Outgoing message was not persisted");
|
|
2987
|
-
|
|
2988
|
-
return { outcome: "inserted", email: inserted };
|
|
2989
|
-
});
|
|
2990
|
-
|
|
2991
|
-
if (submission.outcome !== "inserted") return submission;
|
|
2992
|
-
this.recentParticipantSources = null;
|
|
2993
|
-
|
|
2994
|
-
const result = {
|
|
2995
|
-
...submission,
|
|
2996
|
-
email: await this.deliverOutgoing(submission.email.id),
|
|
2997
|
-
};
|
|
2998
|
-
|
|
2999
|
-
this.publishUpdate();
|
|
3000
|
-
|
|
3001
|
-
return result;
|
|
3002
|
-
});
|
|
3003
|
-
}
|
|
3004
|
-
|
|
3005
|
-
resendOutgoing(id: string) {
|
|
3006
|
-
return this.state.blockConcurrencyWhile(async () => {
|
|
3007
|
-
const result = this.db
|
|
3008
|
-
.update(emails)
|
|
3009
|
-
.set({
|
|
3010
|
-
transportState: "unconfirmed",
|
|
3011
|
-
messageIdHeader: null,
|
|
3012
|
-
transportError: null,
|
|
3013
|
-
deliveryStatusJson: [],
|
|
3014
|
-
})
|
|
3015
|
-
.where(
|
|
3016
|
-
and(
|
|
3017
|
-
eq(emails.id, id),
|
|
3018
|
-
eq(emails.direction, "outgoing"),
|
|
3019
|
-
inArray(emails.transportState, ["failed", "unconfirmed"])
|
|
3020
|
-
)
|
|
3021
|
-
)
|
|
3022
|
-
.returning({ id: emails.id })
|
|
3023
|
-
.all();
|
|
3024
|
-
|
|
3025
|
-
if (!result.length) return null;
|
|
3026
|
-
const email = await this.deliverOutgoing(id);
|
|
3027
|
-
this.publishUpdate();
|
|
3028
|
-
|
|
3029
|
-
return email;
|
|
3030
|
-
});
|
|
3031
|
-
}
|
|
1131
|
+
resendOutgoing(id: string, origin: string) {
|
|
1132
|
+
return mailboxOutbound.resendOutgoing(this.context, id, origin);
|
|
1133
|
+
}
|
|
3032
1134
|
|
|
3033
1135
|
async seedMailbox(
|
|
3034
1136
|
folderValues: NewFolder[],
|
|
@@ -3061,30 +1163,24 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
3061
1163
|
}
|
|
3062
1164
|
|
|
3063
1165
|
for (const email of emailValues) {
|
|
3064
|
-
|
|
3065
|
-
.insert(emails)
|
|
3066
|
-
.values(email)
|
|
3067
|
-
.onConflictDoNothing()
|
|
3068
|
-
.returning({ id: emails.id })
|
|
3069
|
-
.all();
|
|
3070
|
-
|
|
3071
|
-
if (!inserted.length) continue;
|
|
3072
|
-
indexInsertedEmail(this.state.storage.sql, email.id);
|
|
3073
|
-
recordCorrespondents(this.state.storage.sql, email);
|
|
1166
|
+
storeEmail(tx, this.state.storage.sql, email);
|
|
3074
1167
|
}
|
|
3075
1168
|
|
|
3076
1169
|
for (const conversation of conversationValues) {
|
|
3077
|
-
|
|
3078
|
-
.
|
|
1170
|
+
fileConversations(
|
|
1171
|
+
this.state.storage.sql,
|
|
1172
|
+
[conversation.id],
|
|
1173
|
+
{
|
|
3079
1174
|
mailboxState: conversation.mailboxState,
|
|
3080
1175
|
folderId: conversation.folderId,
|
|
3081
|
-
}
|
|
3082
|
-
|
|
3083
|
-
|
|
1176
|
+
},
|
|
1177
|
+
{ stored: true }
|
|
1178
|
+
);
|
|
3084
1179
|
}
|
|
3085
1180
|
});
|
|
3086
1181
|
this.recentParticipantSources = null;
|
|
3087
1182
|
await this.syncInboxCounts();
|
|
1183
|
+
this.scheduleRetention();
|
|
3088
1184
|
|
|
3089
1185
|
return { folders: folderValues.length, emails: emailValues.length };
|
|
3090
1186
|
}
|
|
@@ -3097,738 +1193,217 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
3097
1193
|
emailIds: string[];
|
|
3098
1194
|
blockedPatterns: { pattern: string; at: number }[];
|
|
3099
1195
|
}) {
|
|
3100
|
-
const storage = this.state.storage.sql;
|
|
3101
1196
|
this.db.transaction(() => {
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
1197
|
+
this.db
|
|
1198
|
+
.update(emails)
|
|
1199
|
+
.set({ reportLabel: null })
|
|
1200
|
+
.where(inJsonList(emails.id, input.emailIds))
|
|
1201
|
+
.run();
|
|
1202
|
+
this.db.delete(unsubscriptions).run();
|
|
1203
|
+
this.db.delete(senderFeedback).run();
|
|
1204
|
+
this.db
|
|
1205
|
+
.update(senders)
|
|
1206
|
+
.set({ trustedAt: null, reportedAt: null, blockedAt: null })
|
|
1207
|
+
.run();
|
|
3111
1208
|
|
|
3112
1209
|
for (const block of input.blockedPatterns) {
|
|
3113
|
-
setSenderBlocked(
|
|
1210
|
+
setSenderBlocked(this.db, block.pattern, block.at);
|
|
3114
1211
|
}
|
|
3115
1212
|
});
|
|
3116
1213
|
this.recentParticipantSources = null;
|
|
3117
1214
|
}
|
|
3118
1215
|
|
|
3119
|
-
|
|
1216
|
+
/**
|
|
1217
|
+
* Moves conversations still in `sourceFolderId` (a stale selection can't
|
|
1218
|
+
* overwrite a teammate's newer move), as `by.userId` asks, trusting the
|
|
1219
|
+
* senders it takes out of Spam only with `by.trustSenders`: see
|
|
1220
|
+
* `placeConversations` (no `by.userId`, no verdict: an Undo). Null when
|
|
1221
|
+
* a folder is missing.
|
|
1222
|
+
*/
|
|
1223
|
+
async bulkUpdateConversations(
|
|
3120
1224
|
conversationIds: string[],
|
|
3121
1225
|
sourceFolderId: string,
|
|
3122
|
-
update: ConversationUpdate
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
if (update.folderId) {
|
|
3129
|
-
const targetFolder = this.getFolder(update.folderId);
|
|
3130
|
-
|
|
3131
|
-
if (!targetFolder || targetFolder.kind !== "custom") return null;
|
|
1226
|
+
update: ConversationUpdate,
|
|
1227
|
+
by: {
|
|
1228
|
+
userId: string | null;
|
|
1229
|
+
trustSenders: boolean;
|
|
1230
|
+
undo?: boolean;
|
|
1231
|
+
offerUndo?: boolean;
|
|
3132
1232
|
}
|
|
3133
|
-
|
|
3134
|
-
const candidates = [...new Set(conversationIds)];
|
|
3135
|
-
|
|
3136
|
-
if (!candidates.length) return 0;
|
|
3137
|
-
const assignments: string[] = [];
|
|
3138
|
-
const values: (string | null)[] = [];
|
|
3139
|
-
|
|
1233
|
+
) {
|
|
3140
1234
|
// A custom folder is a classification inside the active Inbox
|
|
3141
1235
|
// distribution, so assigning one also restores the conversation.
|
|
3142
|
-
const mailboxState =
|
|
3143
|
-
?
|
|
3144
|
-
: update.mailboxState;
|
|
3145
|
-
|
|
3146
|
-
if (mailboxState !== undefined) {
|
|
3147
|
-
assignments.push("mailbox_state = ?");
|
|
3148
|
-
values.push(mailboxState);
|
|
3149
|
-
}
|
|
1236
|
+
const mailboxState =
|
|
1237
|
+
update.mailboxState ?? (update.folderId ? "active" : undefined);
|
|
3150
1238
|
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
}
|
|
3155
|
-
|
|
3156
|
-
if (!assignments.length) return 0;
|
|
3157
|
-
const membership = folderMembership(sourceFolder);
|
|
3158
|
-
const candidatesJson = stringListJson(candidates);
|
|
3159
|
-
|
|
3160
|
-
// Setting folderId means placing the conversation in the Inbox
|
|
3161
|
-
// distribution. Outgoing-only conversations must stay in Sent.
|
|
3162
|
-
const targetPredicate =
|
|
3163
|
-
update.folderId === undefined ? "" : "and c.has_incoming = 1";
|
|
3164
|
-
|
|
3165
|
-
const result = this.db.transaction(() => {
|
|
3166
|
-
// Keep the source-folder guard in the update itself so a stale shared
|
|
3167
|
-
// selection cannot overwrite a teammate's newer move.
|
|
3168
|
-
const moved = this.state.storage.sql
|
|
3169
|
-
.exec<{ id: string }>(
|
|
3170
|
-
`
|
|
3171
|
-
update conversations as c
|
|
3172
|
-
set ${assignments.join(", ")}
|
|
3173
|
-
where c.id in (
|
|
3174
|
-
select cast(value as text) from json_each(?)
|
|
3175
|
-
)
|
|
3176
|
-
and ${membership.predicate}
|
|
3177
|
-
${targetPredicate}
|
|
3178
|
-
returning id
|
|
3179
|
-
`,
|
|
3180
|
-
...values,
|
|
3181
|
-
candidatesJson,
|
|
3182
|
-
...membership.bindings
|
|
3183
|
-
)
|
|
3184
|
-
.toArray();
|
|
1239
|
+
const workspaceBlocks = await blocksForLeavingSpam(this.context, [
|
|
1240
|
+
{ conversationIds, mailboxState },
|
|
1241
|
+
]);
|
|
3185
1242
|
|
|
3186
|
-
|
|
3187
|
-
this.rejoinSplitConversations(moved.map((row) => row.id));
|
|
1243
|
+
const sourceFolder = mailboxFolders.getFolder(this.context, sourceFolderId);
|
|
3188
1244
|
|
|
3189
|
-
|
|
3190
|
-
});
|
|
3191
|
-
|
|
3192
|
-
if (result.length) this.publishUpdate();
|
|
3193
|
-
|
|
3194
|
-
return result.length;
|
|
3195
|
-
}
|
|
1245
|
+
if (!sourceFolder) return null;
|
|
3196
1246
|
|
|
3197
|
-
|
|
3198
|
-
|
|
1247
|
+
if (update.folderId) {
|
|
1248
|
+
const targetFolder = mailboxFolders.getFolder(
|
|
1249
|
+
this.context,
|
|
1250
|
+
update.folderId
|
|
1251
|
+
);
|
|
3199
1252
|
|
|
3200
|
-
|
|
3201
|
-
return { outcome: "not_found" as const, deletedCount: 0 };
|
|
1253
|
+
if (!targetFolder || targetFolder.kind !== "custom") return null;
|
|
3202
1254
|
}
|
|
3203
1255
|
|
|
3204
|
-
const
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
if (storedConversations.length !== candidates.length) {
|
|
3218
|
-
return { outcome: "not_found" as const, deletedCount: 0 };
|
|
3219
|
-
}
|
|
1256
|
+
const move = (beforeMerge?: (target: string) => void) =>
|
|
1257
|
+
placeConversations(
|
|
1258
|
+
this.context,
|
|
1259
|
+
conversationIds,
|
|
1260
|
+
{ mailboxState, folderId: update.folderId },
|
|
1261
|
+
{
|
|
1262
|
+
only: folderMembership(sourceFolder),
|
|
1263
|
+
...by,
|
|
1264
|
+
workspaceBlocks,
|
|
1265
|
+
beforeMerge,
|
|
1266
|
+
}
|
|
1267
|
+
);
|
|
3220
1268
|
|
|
3221
1269
|
if (
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
1270
|
+
by.offerUndo &&
|
|
1271
|
+
by.userId &&
|
|
1272
|
+
(mailboxState === "spam" ||
|
|
1273
|
+
(sourceFolderId === "spam" &&
|
|
1274
|
+
(mailboxState === "active" || mailboxState === "archive")))
|
|
3225
1275
|
) {
|
|
3226
|
-
return
|
|
1276
|
+
return withSpamUndo(this.context, by.userId, conversationIds, move);
|
|
3227
1277
|
}
|
|
3228
1278
|
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
id: emails.id,
|
|
3232
|
-
direction: emails.direction,
|
|
3233
|
-
bodyHtmlR2Key: emails.bodyHtmlR2Key,
|
|
3234
|
-
rawMimeR2Key: emails.rawMimeR2Key,
|
|
3235
|
-
attachmentsJson: emails.attachmentsJson,
|
|
3236
|
-
})
|
|
3237
|
-
.from(emails)
|
|
3238
|
-
.where(sql`${emails.conversationId} in (
|
|
3239
|
-
select cast(value as text) from json_each(${candidatesJson})
|
|
3240
|
-
)`)
|
|
3241
|
-
.all();
|
|
3242
|
-
|
|
3243
|
-
const incomingEmailIds = new Set(
|
|
3244
|
-
storedEmails.flatMap((email) =>
|
|
3245
|
-
email.direction === "incoming" ? [email.id] : []
|
|
3246
|
-
)
|
|
3247
|
-
);
|
|
3248
|
-
|
|
3249
|
-
const pendingInboundIds = incomingEmailIds.size
|
|
3250
|
-
? this.db
|
|
3251
|
-
.select({ id: pendingInbound.id })
|
|
3252
|
-
.from(pendingInbound)
|
|
3253
|
-
.all()
|
|
3254
|
-
.flatMap((job) =>
|
|
3255
|
-
incomingEmailIds.has(inboundMessageId(job.id)) ? [job.id] : []
|
|
3256
|
-
)
|
|
3257
|
-
: [];
|
|
3258
|
-
|
|
3259
|
-
const pendingInboundIdsJson = stringListJson(pendingInboundIds);
|
|
3260
|
-
|
|
3261
|
-
const objectKeys = [
|
|
3262
|
-
...new Set(
|
|
3263
|
-
storedEmails.flatMap((email) => [
|
|
3264
|
-
...(email.bodyHtmlR2Key ? [email.bodyHtmlR2Key] : []),
|
|
3265
|
-
...(email.rawMimeR2Key ? [email.rawMimeR2Key] : []),
|
|
3266
|
-
...email.attachmentsJson.flatMap((attachment) => [
|
|
3267
|
-
attachment.r2Key,
|
|
3268
|
-
...(officePreviewExtension(attachment.filename)
|
|
3269
|
-
? [officePreviewKey(attachment.r2Key)]
|
|
3270
|
-
: []),
|
|
3271
|
-
]),
|
|
3272
|
-
])
|
|
3273
|
-
),
|
|
3274
|
-
];
|
|
3275
|
-
|
|
3276
|
-
const referencedObjectKeys = this.referencedObjectKeys(
|
|
3277
|
-
objectKeys,
|
|
3278
|
-
candidates
|
|
3279
|
-
);
|
|
1279
|
+
return { ...move(), undoId: null };
|
|
1280
|
+
}
|
|
3280
1281
|
|
|
3281
|
-
|
|
3282
|
-
|
|
1282
|
+
undoSpamDecision(userId: string, id: string) {
|
|
1283
|
+
return this.state.blockConcurrencyWhile(() =>
|
|
1284
|
+
undoSpam(this.context, userId, id)
|
|
3283
1285
|
);
|
|
1286
|
+
}
|
|
3284
1287
|
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
// without a retry after an interruption. The short delay prevents the
|
|
3288
|
-
// alarm from waking on setAlarm's await before the rows are inserted.
|
|
3289
|
-
const cleanupAlarmAt = cleanupAt.getTime() + ALARM_WAKE_DELAY_MS;
|
|
3290
|
-
|
|
3291
|
-
if (ownedObjectKeys.length) {
|
|
3292
|
-
await this.scheduleAlarm(cleanupAlarmAt);
|
|
3293
|
-
}
|
|
3294
|
-
|
|
3295
|
-
this.db.transaction((tx) => {
|
|
3296
|
-
tx.run(sql`
|
|
3297
|
-
delete from pending_office_previews where email_id in (
|
|
3298
|
-
select id from emails where conversation_id in (
|
|
3299
|
-
select cast(value as text) from json_each(${candidatesJson})
|
|
3300
|
-
)
|
|
3301
|
-
)
|
|
3302
|
-
`);
|
|
3303
|
-
|
|
3304
|
-
for (const objectKey of ownedObjectKeys) {
|
|
3305
|
-
tx.insert(pendingObjectDeletions)
|
|
3306
|
-
.values({ objectKey, nextAttemptAt: cleanupAt })
|
|
3307
|
-
.onConflictDoNothing()
|
|
3308
|
-
.run();
|
|
3309
|
-
}
|
|
3310
|
-
|
|
3311
|
-
if (pendingInboundIds.length) {
|
|
3312
|
-
tx.delete(pendingInbound)
|
|
3313
|
-
.where(sql`${pendingInbound.id} in (
|
|
3314
|
-
select cast(value as text) from json_each(${pendingInboundIdsJson})
|
|
3315
|
-
)`)
|
|
3316
|
-
.run();
|
|
3317
|
-
}
|
|
3318
|
-
|
|
3319
|
-
tx.run(sql`
|
|
3320
|
-
delete from email_search where conversation_id in (
|
|
3321
|
-
select cast(value as text) from json_each(${candidatesJson})
|
|
3322
|
-
)
|
|
3323
|
-
`);
|
|
3324
|
-
tx.run(sql`
|
|
3325
|
-
delete from email_read_states
|
|
3326
|
-
where email_id in (
|
|
3327
|
-
select id from emails where conversation_id in (
|
|
3328
|
-
select cast(value as text) from json_each(${candidatesJson})
|
|
3329
|
-
)
|
|
3330
|
-
)
|
|
3331
|
-
`);
|
|
3332
|
-
tx.delete(conversations)
|
|
3333
|
-
.where(sql`${conversations.id} in (
|
|
3334
|
-
select cast(value as text) from json_each(${candidatesJson})
|
|
3335
|
-
)`)
|
|
3336
|
-
.run();
|
|
3337
|
-
tx.delete(emails)
|
|
3338
|
-
.where(sql`${emails.conversationId} in (
|
|
3339
|
-
select cast(value as text) from json_each(${candidatesJson})
|
|
3340
|
-
)`)
|
|
3341
|
-
.run();
|
|
3342
|
-
});
|
|
3343
|
-
this.recentParticipantSources = null;
|
|
3344
|
-
this.publishUpdate();
|
|
3345
|
-
|
|
3346
|
-
return {
|
|
3347
|
-
outcome: "deleted" as const,
|
|
3348
|
-
deletedCount: storedConversations.length,
|
|
3349
|
-
};
|
|
1288
|
+
permanentlyDeleteEmails(ids: string[]) {
|
|
1289
|
+
return mailboxStorage.permanentlyDeleteEmails(this.context, ids);
|
|
3350
1290
|
}
|
|
3351
1291
|
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
1292
|
+
permanentlyDeleteConversations(
|
|
1293
|
+
conversationIds: string[],
|
|
1294
|
+
fromState: RetentionFolder = "trash"
|
|
3355
1295
|
) {
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
with
|
|
3362
|
-
candidate_keys(object_key) as (
|
|
3363
|
-
select cast(value as text) from json_each(?)
|
|
3364
|
-
),
|
|
3365
|
-
excluded_conversations(id) as (
|
|
3366
|
-
select cast(value as text) from json_each(?)
|
|
3367
|
-
)
|
|
3368
|
-
select candidate.object_key
|
|
3369
|
-
from candidate_keys candidate
|
|
3370
|
-
where exists (
|
|
3371
|
-
select 1
|
|
3372
|
-
from emails message
|
|
3373
|
-
where message.conversation_id not in (
|
|
3374
|
-
select id from excluded_conversations
|
|
3375
|
-
)
|
|
3376
|
-
and (
|
|
3377
|
-
message.body_html_r2_key = candidate.object_key
|
|
3378
|
-
or message.raw_mime_r2_key = candidate.object_key
|
|
3379
|
-
or exists (
|
|
3380
|
-
select 1
|
|
3381
|
-
from json_each(message.attachments_json) attachment
|
|
3382
|
-
where json_extract(attachment.value, '$.r2Key') = candidate.object_key
|
|
3383
|
-
or json_extract(attachment.value, '$.r2Key') || '.preview.pdf' = candidate.object_key
|
|
3384
|
-
)
|
|
3385
|
-
)
|
|
3386
|
-
)
|
|
3387
|
-
`,
|
|
3388
|
-
stringListJson(objectKeys),
|
|
3389
|
-
stringListJson(excludedConversationIds)
|
|
3390
|
-
)
|
|
3391
|
-
.toArray();
|
|
3392
|
-
|
|
3393
|
-
return new Set(rows.map((row) => row.object_key));
|
|
1296
|
+
return mailboxStorage.permanentlyDeleteConversations(
|
|
1297
|
+
this.context,
|
|
1298
|
+
conversationIds,
|
|
1299
|
+
fromState
|
|
1300
|
+
);
|
|
3394
1301
|
}
|
|
3395
1302
|
|
|
3396
1303
|
updateTransport(id: string, update: TransportUpdate) {
|
|
3397
|
-
|
|
3398
|
-
.update(emails)
|
|
3399
|
-
.set({
|
|
3400
|
-
transportState: update.state,
|
|
3401
|
-
messageIdHeader: update.messageIdHeader,
|
|
3402
|
-
transportError: update.error,
|
|
3403
|
-
})
|
|
3404
|
-
.where(and(eq(emails.id, id), eq(emails.direction, "outgoing")))
|
|
3405
|
-
.returning({ id: emails.id })
|
|
3406
|
-
.all();
|
|
3407
|
-
|
|
3408
|
-
return result.length > 0;
|
|
1304
|
+
return mailboxOutbound.updateTransport(this.context, id, update);
|
|
3409
1305
|
}
|
|
3410
1306
|
|
|
3411
1307
|
recordDeliveryStatus(
|
|
3412
1308
|
messageIdHeader: string,
|
|
3413
1309
|
status: RecipientDeliveryStatus
|
|
3414
1310
|
) {
|
|
3415
|
-
|
|
3416
|
-
|
|
3417
|
-
|
|
3418
|
-
|
|
3419
|
-
const existing = email.deliveryStatusJson.find(
|
|
3420
|
-
(item) => item.recipient === status.recipient
|
|
1311
|
+
return mailboxOutbound.recordDeliveryStatus(
|
|
1312
|
+
this.context,
|
|
1313
|
+
messageIdHeader,
|
|
1314
|
+
status
|
|
3421
1315
|
);
|
|
3422
|
-
|
|
3423
|
-
if (existing?.eventId === status.eventId) return "duplicate" as const;
|
|
3424
|
-
|
|
3425
|
-
if (existing && existing.eventAt > status.eventAt) return "stale" as const;
|
|
3426
|
-
|
|
3427
|
-
const next = [
|
|
3428
|
-
...email.deliveryStatusJson.filter(
|
|
3429
|
-
(item) => item.recipient !== status.recipient
|
|
3430
|
-
),
|
|
3431
|
-
status,
|
|
3432
|
-
];
|
|
3433
|
-
|
|
3434
|
-
this.db
|
|
3435
|
-
.update(emails)
|
|
3436
|
-
.set({ deliveryStatusJson: next })
|
|
3437
|
-
.where(eq(emails.id, email.id))
|
|
3438
|
-
.run();
|
|
3439
|
-
this.publishUpdate();
|
|
3440
|
-
|
|
3441
|
-
return "updated" as const;
|
|
3442
|
-
}
|
|
3443
|
-
|
|
3444
|
-
async alarm() {
|
|
3445
|
-
const now = Date.now();
|
|
3446
|
-
await this.finishImport();
|
|
3447
|
-
// Object deletion runs first, so a delivery that keeps failing (or keeps
|
|
3448
|
-
// getting the alarm killed) cannot hold it back.
|
|
3449
|
-
await this.processObjectDeletionJobs(now);
|
|
3450
|
-
|
|
3451
|
-
try {
|
|
3452
|
-
await this.processInboundJobs(now);
|
|
3453
|
-
} finally {
|
|
3454
|
-
// Previews of the mail just stored are queued in the same wake.
|
|
3455
|
-
await dispatchOfficePreviewJobs(
|
|
3456
|
-
this.state.storage.sql,
|
|
3457
|
-
this.bindings,
|
|
3458
|
-
this.state.id.name ?? "unknown-mailbox"
|
|
3459
|
-
);
|
|
3460
|
-
await this.scheduleRemainingWork();
|
|
3461
|
-
}
|
|
3462
1316
|
}
|
|
3463
1317
|
|
|
3464
1318
|
/**
|
|
3465
|
-
*
|
|
3466
|
-
*
|
|
3467
|
-
*
|
|
1319
|
+
* The mailbox's background work, in the order a wake runs it: what an
|
|
1320
|
+
* import left to announce; files to delete (first, so a delivery that keeps
|
|
1321
|
+
* failing can't hold them back); deliveries to process; Trash and Spam to
|
|
1322
|
+
* empty; Office previews to queue (last, with the mail just stored). Each
|
|
1323
|
+
* says when it is next due, which sets the alarm.
|
|
3468
1324
|
*/
|
|
3469
|
-
private
|
|
3470
|
-
const
|
|
3471
|
-
|
|
3472
|
-
if (!messageId) return false;
|
|
3473
|
-
const existing = this.getEmailByMessageId(messageId);
|
|
3474
|
-
|
|
3475
|
-
if (!existing) return false;
|
|
3476
|
-
|
|
3477
|
-
return existing.direction === "incoming" || Boolean(job.listAddress);
|
|
3478
|
-
}
|
|
3479
|
-
|
|
3480
|
-
private async processInboundJobs(now: number) {
|
|
3481
|
-
const jobs = this.db
|
|
3482
|
-
.select()
|
|
3483
|
-
.from(pendingInbound)
|
|
3484
|
-
.where(lte(pendingInbound.nextAttemptAt, new Date(now)))
|
|
3485
|
-
.orderBy(
|
|
3486
|
-
asc(pendingInbound.nextAttemptAt),
|
|
3487
|
-
asc(pendingInbound.receivedAt)
|
|
3488
|
-
)
|
|
3489
|
-
// MIME parsing can be memory-heavy; the next due row schedules a quick
|
|
3490
|
-
// follow-up, so one delivery per wake keeps peak memory bounded.
|
|
3491
|
-
.limit(INBOUND_ALARM_BATCH_SIZE)
|
|
3492
|
-
.all();
|
|
3493
|
-
|
|
3494
|
-
for (const job of jobs) {
|
|
3495
|
-
// oxlint-disable-next-line eslint/no-await-in-loop -- one delivery at a time keeps MIME parsing's peak memory bounded
|
|
3496
|
-
await this.processInboundJob(job, now);
|
|
3497
|
-
}
|
|
3498
|
-
}
|
|
3499
|
-
|
|
3500
|
-
private async processInboundJob(job: PendingInbound, now: number) {
|
|
3501
|
-
const messageId = inboundMessageId(job.id);
|
|
3502
|
-
const existing = this.getEmail(messageId);
|
|
3503
|
-
|
|
3504
|
-
if (existing) {
|
|
3505
|
-
await this.finishStoredInbound(job, existing, now, false);
|
|
3506
|
-
|
|
3507
|
-
return;
|
|
3508
|
-
}
|
|
3509
|
-
|
|
3510
|
-
if (job.attempts > 0 && isPastRetryAge(job, now)) {
|
|
3511
|
-
// Earlier attempts ended without an outcome (the alarm was killed
|
|
3512
|
-
// mid-parse, say); this message is not parsed again.
|
|
3513
|
-
await this.storeUnparsedInbound(
|
|
3514
|
-
job,
|
|
3515
|
-
now,
|
|
3516
|
-
"Message processing did not finish within 24 hours"
|
|
3517
|
-
);
|
|
3518
|
-
|
|
3519
|
-
return;
|
|
3520
|
-
}
|
|
3521
|
-
|
|
3522
|
-
if (job.unfinishedAttempts >= MAX_UNFINISHED_INBOUND_ATTEMPTS) {
|
|
3523
|
-
// Processing it got the alarm killed every time: other mail goes first.
|
|
3524
|
-
await this.storeUnparsedInbound(
|
|
3525
|
-
job,
|
|
3526
|
-
now,
|
|
3527
|
-
`Message processing did not finish in ${MAX_UNFINISHED_INBOUND_ATTEMPTS} attempts`
|
|
3528
|
-
);
|
|
3529
|
-
|
|
3530
|
-
return;
|
|
3531
|
-
}
|
|
3532
|
-
|
|
3533
|
-
await this.recordInboundAttempt(job, now);
|
|
3534
|
-
|
|
3535
|
-
try {
|
|
3536
|
-
const rawMime = await readInboundRawMime(this.bindings, job);
|
|
3537
|
-
|
|
3538
|
-
if (this.isDuplicateDelivery(job, rawMime)) {
|
|
3539
|
-
this.db
|
|
3540
|
-
.delete(pendingInbound)
|
|
3541
|
-
.where(eq(pendingInbound.id, job.id))
|
|
3542
|
-
.run();
|
|
3543
|
-
|
|
3544
|
-
return;
|
|
3545
|
-
}
|
|
3546
|
-
|
|
3547
|
-
const prepared = await prepareInboundEmail({
|
|
3548
|
-
env: this.bindings,
|
|
3549
|
-
mailboxId: this.state.id.name ?? "unknown-mailbox",
|
|
3550
|
-
job,
|
|
3551
|
-
rawMime,
|
|
3552
|
-
resolveParent: (inReplyTo, references) =>
|
|
3553
|
-
this.resolveParent(inReplyTo, references),
|
|
3554
|
-
});
|
|
3555
|
-
|
|
3556
|
-
const { intel, delivery, signals, screening } =
|
|
3557
|
-
await this.inboundSenderSignals(prepared.email, prepared.linkDomains);
|
|
3558
|
-
|
|
3559
|
-
const screeningJson: EmailScreening | null = screening.block
|
|
3560
|
-
? { blocked: screening.block.workspace ? "workspace" : "mailbox" }
|
|
3561
|
-
: null;
|
|
3562
|
-
|
|
3563
|
-
const email: NewEmail = {
|
|
3564
|
-
...prepared.email,
|
|
3565
|
-
senderIntelJson: intel,
|
|
3566
|
-
deliveryJson: delivery,
|
|
3567
|
-
screeningJson,
|
|
3568
|
-
};
|
|
3569
|
-
|
|
3570
|
-
let classification: EmailAiClassification | null = null;
|
|
3571
|
-
// Blocked senders need no model.
|
|
3572
|
-
const skipAi = Boolean(screening.block);
|
|
3573
|
-
|
|
3574
|
-
try {
|
|
3575
|
-
if (!skipAi) {
|
|
3576
|
-
classification = await this.classifyInbound(rawMime, signals);
|
|
3577
|
-
}
|
|
3578
|
-
} catch (error) {
|
|
3579
|
-
if (!(error instanceof EmailAiClassificationError)) throw error;
|
|
3580
|
-
const aiAttempts = job.aiAttempts + 1;
|
|
3581
|
-
|
|
3582
|
-
if (aiAttempts < MAILBOX_AI_MAX_ATTEMPTS) {
|
|
3583
|
-
this.db
|
|
3584
|
-
.update(pendingInbound)
|
|
3585
|
-
.set({
|
|
3586
|
-
// The model failed, not the delivery: the attempt recorded
|
|
3587
|
-
// before parsing is given back.
|
|
3588
|
-
attempts: job.attempts,
|
|
3589
|
-
unfinishedAttempts: job.unfinishedAttempts,
|
|
3590
|
-
aiAttempts,
|
|
3591
|
-
nextAttemptAt: new Date(now + retryDelay(aiAttempts)),
|
|
3592
|
-
})
|
|
3593
|
-
.where(eq(pendingInbound.id, job.id))
|
|
3594
|
-
.run();
|
|
3595
|
-
console.error(
|
|
3596
|
-
`Could not classify inbound delivery ${job.id}; retrying`,
|
|
3597
|
-
error
|
|
3598
|
-
);
|
|
3599
|
-
|
|
3600
|
-
return;
|
|
3601
|
-
}
|
|
3602
|
-
|
|
3603
|
-
console.error(
|
|
3604
|
-
`Could not classify inbound delivery ${job.id}; delivering to Inbox`,
|
|
3605
|
-
error
|
|
3606
|
-
);
|
|
3607
|
-
}
|
|
3608
|
-
|
|
3609
|
-
const stored = this.insertClassifiedInboundEmail(
|
|
3610
|
-
email,
|
|
3611
|
-
classification,
|
|
3612
|
-
this.inboundPlacement(screening, classification)
|
|
3613
|
-
);
|
|
3614
|
-
|
|
3615
|
-
if (!stored) {
|
|
3616
|
-
throw new Error("Parsed inbound email was not persisted");
|
|
3617
|
-
}
|
|
3618
|
-
|
|
3619
|
-
await this.finishStoredInbound(job, stored, now, true);
|
|
3620
|
-
} catch (error) {
|
|
3621
|
-
if (error instanceof UnprocessableInboundEmailError) {
|
|
3622
|
-
const fallback = prepareUnprocessableInboundEmail({
|
|
3623
|
-
job,
|
|
3624
|
-
reason: error.message,
|
|
3625
|
-
rawMimeR2Key: job.rawObjectKey,
|
|
3626
|
-
});
|
|
3627
|
-
|
|
3628
|
-
const stored = await this.insertEmail(fallback);
|
|
3629
|
-
|
|
3630
|
-
if (!stored) {
|
|
3631
|
-
throw new Error("Inbound fallback email was not persisted", {
|
|
3632
|
-
cause: error,
|
|
3633
|
-
});
|
|
3634
|
-
}
|
|
3635
|
-
|
|
3636
|
-
await this.finishStoredInbound(job, stored, now, true);
|
|
3637
|
-
console.error(`Stored fallback for inbound delivery ${job.id}`, error);
|
|
3638
|
-
|
|
3639
|
-
return;
|
|
3640
|
-
}
|
|
3641
|
-
|
|
3642
|
-
if (isPastRetryAge(job, now)) {
|
|
3643
|
-
const fallback = prepareUnprocessableInboundEmail({
|
|
3644
|
-
job,
|
|
3645
|
-
reason: "Message processing remained unavailable for 24 hours",
|
|
3646
|
-
rawMimeR2Key:
|
|
3647
|
-
error instanceof MissingRawMimeError ? null : job.rawObjectKey,
|
|
3648
|
-
});
|
|
3649
|
-
|
|
3650
|
-
const stored = await this.insertEmail(fallback);
|
|
3651
|
-
|
|
3652
|
-
if (!stored) {
|
|
3653
|
-
throw new Error("Inbound infrastructure fallback was not persisted", {
|
|
3654
|
-
cause: error,
|
|
3655
|
-
});
|
|
3656
|
-
}
|
|
1325
|
+
private backgroundWork() {
|
|
1326
|
+
const m = this.context;
|
|
3657
1327
|
|
|
3658
|
-
|
|
3659
|
-
|
|
3660
|
-
|
|
3661
|
-
error
|
|
3662
|
-
);
|
|
3663
|
-
|
|
3664
|
-
return;
|
|
3665
|
-
}
|
|
3666
|
-
|
|
3667
|
-
const attempts = job.attempts + 1;
|
|
1328
|
+
const earliest = (
|
|
1329
|
+
table: typeof pendingInbound | typeof pendingObjectDeletions
|
|
1330
|
+
) =>
|
|
3668
1331
|
this.db
|
|
3669
|
-
.
|
|
3670
|
-
.
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
3691
|
-
|
|
3692
|
-
|
|
3693
|
-
|
|
3694
|
-
|
|
3695
|
-
|
|
3696
|
-
|
|
3697
|
-
|
|
3698
|
-
|
|
3699
|
-
|
|
3700
|
-
|
|
3701
|
-
|
|
3702
|
-
|
|
3703
|
-
|
|
3704
|
-
|
|
1332
|
+
.select({ at: min(table.nextAttemptAt) })
|
|
1333
|
+
.from(table)
|
|
1334
|
+
.get()
|
|
1335
|
+
?.at?.getTime() ?? null;
|
|
1336
|
+
|
|
1337
|
+
return [
|
|
1338
|
+
{
|
|
1339
|
+
nextDue: () => null,
|
|
1340
|
+
run: async () => {
|
|
1341
|
+
await mailboxImport.finishImport(m);
|
|
1342
|
+
},
|
|
1343
|
+
},
|
|
1344
|
+
{
|
|
1345
|
+
nextDue: () => nextSpamUndoExpiry(m),
|
|
1346
|
+
run: (now) => expireSpamUndo(m, now),
|
|
1347
|
+
},
|
|
1348
|
+
{
|
|
1349
|
+
nextDue: () => earliest(pendingObjectDeletions),
|
|
1350
|
+
run: (now) => mailboxStorage.processObjectDeletionJobs(m, now),
|
|
1351
|
+
},
|
|
1352
|
+
{
|
|
1353
|
+
nextDue: () => earliest(pendingInbound),
|
|
1354
|
+
run: (now) => mailboxInbound.processInboundJobs(m, now),
|
|
1355
|
+
},
|
|
1356
|
+
{
|
|
1357
|
+
nextDue: () => mailboxStorage.nextRetentionAt(m),
|
|
1358
|
+
run: (now) => mailboxStorage.processRetention(m, now),
|
|
1359
|
+
},
|
|
1360
|
+
{
|
|
1361
|
+
nextDue: () => nextOfficePreviewAttempt(this.db) ?? null,
|
|
1362
|
+
run: () =>
|
|
1363
|
+
dispatchOfficePreviewJobs(
|
|
1364
|
+
this.db,
|
|
1365
|
+
this.env,
|
|
1366
|
+
this.state.id.name ?? "unknown-mailbox"
|
|
1367
|
+
),
|
|
1368
|
+
},
|
|
1369
|
+
] satisfies {
|
|
1370
|
+
nextDue: () => number | null;
|
|
1371
|
+
run: (now: number) => void | Promise<void>;
|
|
1372
|
+
}[];
|
|
3705
1373
|
}
|
|
3706
1374
|
|
|
3707
1375
|
/**
|
|
3708
|
-
*
|
|
3709
|
-
*
|
|
3710
|
-
*
|
|
1376
|
+
* Runs the background work that is due. One kind failing doesn't stop
|
|
1377
|
+
* the others; the first failure is rethrown after the next wake is set,
|
|
1378
|
+
* so the platform retries the alarm.
|
|
3711
1379
|
*/
|
|
3712
|
-
|
|
3713
|
-
|
|
3714
|
-
|
|
3715
|
-
reason: string
|
|
3716
|
-
) {
|
|
3717
|
-
await this.recordInboundAttempt(job, now);
|
|
3718
|
-
|
|
3719
|
-
try {
|
|
3720
|
-
// Without an answer from R2 the link is kept: a missing object only
|
|
3721
|
-
// makes the download fail.
|
|
3722
|
-
const raw = await this.bindings.MAIL_STORAGE.head(job.rawObjectKey).then(
|
|
3723
|
-
(object) => object !== null,
|
|
3724
|
-
() => true
|
|
3725
|
-
);
|
|
3726
|
-
|
|
3727
|
-
const fallback = prepareUnprocessableInboundEmail({
|
|
3728
|
-
job,
|
|
3729
|
-
reason,
|
|
3730
|
-
rawMimeR2Key: raw ? job.rawObjectKey : null,
|
|
3731
|
-
});
|
|
3732
|
-
|
|
3733
|
-
const stored = await this.insertEmail(fallback);
|
|
1380
|
+
async alarm() {
|
|
1381
|
+
const now = Date.now();
|
|
1382
|
+
const failures: { error: unknown }[] = [];
|
|
3734
1383
|
|
|
3735
|
-
|
|
3736
|
-
|
|
1384
|
+
for (const work of this.backgroundWork()) {
|
|
1385
|
+
try {
|
|
1386
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- in order: see backgroundWork
|
|
1387
|
+
await work.run(now);
|
|
1388
|
+
} catch (error) {
|
|
1389
|
+
failures.push({ error });
|
|
3737
1390
|
}
|
|
3738
|
-
|
|
3739
|
-
await this.finishStoredInbound(job, stored, now, true);
|
|
3740
|
-
console.error(`Stored fallback for unparsed inbound delivery ${job.id}`);
|
|
3741
|
-
} catch (error) {
|
|
3742
|
-
console.error(
|
|
3743
|
-
`Could not store unparsed inbound delivery ${job.id}`,
|
|
3744
|
-
error
|
|
3745
|
-
);
|
|
3746
|
-
}
|
|
3747
|
-
}
|
|
3748
|
-
|
|
3749
|
-
private async processObjectDeletionJobs(now: number) {
|
|
3750
|
-
const jobs = this.db
|
|
3751
|
-
.select()
|
|
3752
|
-
.from(pendingObjectDeletions)
|
|
3753
|
-
.where(lte(pendingObjectDeletions.nextAttemptAt, new Date(now)))
|
|
3754
|
-
.orderBy(asc(pendingObjectDeletions.nextAttemptAt))
|
|
3755
|
-
.limit(OBJECT_DELETION_ALARM_BATCH_SIZE)
|
|
3756
|
-
.all();
|
|
3757
|
-
|
|
3758
|
-
if (!jobs.length) return;
|
|
3759
|
-
const objectKeys = jobs.map((job) => job.objectKey);
|
|
3760
|
-
const referencedObjectKeys = this.referencedObjectKeys(objectKeys, []);
|
|
3761
|
-
|
|
3762
|
-
const retainedKeys = objectKeys.filter((key) =>
|
|
3763
|
-
referencedObjectKeys.has(key)
|
|
3764
|
-
);
|
|
3765
|
-
|
|
3766
|
-
if (retainedKeys.length) {
|
|
3767
|
-
this.db
|
|
3768
|
-
.delete(pendingObjectDeletions)
|
|
3769
|
-
.where(inArray(pendingObjectDeletions.objectKey, retainedKeys))
|
|
3770
|
-
.run();
|
|
3771
1391
|
}
|
|
3772
1392
|
|
|
3773
|
-
|
|
3774
|
-
(job) => !referencedObjectKeys.has(job.objectKey)
|
|
3775
|
-
);
|
|
3776
|
-
|
|
3777
|
-
if (!deletableJobs.length) return;
|
|
3778
|
-
const deletableKeys = deletableJobs.map((job) => job.objectKey);
|
|
3779
|
-
|
|
3780
|
-
try {
|
|
3781
|
-
await this.bindings.MAIL_STORAGE.delete(deletableKeys);
|
|
3782
|
-
this.db
|
|
3783
|
-
.delete(pendingObjectDeletions)
|
|
3784
|
-
.where(inArray(pendingObjectDeletions.objectKey, deletableKeys))
|
|
3785
|
-
.run();
|
|
3786
|
-
} catch (error) {
|
|
3787
|
-
for (const job of deletableJobs) {
|
|
3788
|
-
const attempts = job.attempts + 1;
|
|
3789
|
-
this.db
|
|
3790
|
-
.update(pendingObjectDeletions)
|
|
3791
|
-
.set({
|
|
3792
|
-
attempts,
|
|
3793
|
-
nextAttemptAt: new Date(now + retryDelay(attempts)),
|
|
3794
|
-
})
|
|
3795
|
-
.where(eq(pendingObjectDeletions.objectKey, job.objectKey))
|
|
3796
|
-
.run();
|
|
3797
|
-
}
|
|
1393
|
+
await this.scheduleRemainingWork();
|
|
3798
1394
|
|
|
3799
|
-
|
|
3800
|
-
}
|
|
1395
|
+
if (failures[0]) throw failures[0].error;
|
|
3801
1396
|
}
|
|
3802
1397
|
|
|
3803
|
-
/** When the earliest
|
|
1398
|
+
/** When the earliest background work is due, or null. */
|
|
3804
1399
|
private nextDueWork() {
|
|
3805
|
-
const
|
|
3806
|
-
|
|
3807
|
-
.from(pendingInbound)
|
|
3808
|
-
.orderBy(asc(pendingInbound.nextAttemptAt))
|
|
3809
|
-
.limit(1)
|
|
3810
|
-
.all()[0];
|
|
3811
|
-
|
|
3812
|
-
const nextObjectDeletion = this.db
|
|
3813
|
-
.select({ nextAttemptAt: pendingObjectDeletions.nextAttemptAt })
|
|
3814
|
-
.from(pendingObjectDeletions)
|
|
3815
|
-
.orderBy(asc(pendingObjectDeletions.nextAttemptAt))
|
|
3816
|
-
.limit(1)
|
|
3817
|
-
.all()[0];
|
|
1400
|
+
const due = this.backgroundWork().flatMap((work) => {
|
|
1401
|
+
const at = work.nextDue();
|
|
3818
1402
|
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
);
|
|
3822
|
-
|
|
3823
|
-
const attemptTimes = [
|
|
3824
|
-
nextInbound,
|
|
3825
|
-
nextObjectDeletion,
|
|
3826
|
-
...(officePreviewAttempt === undefined
|
|
3827
|
-
? []
|
|
3828
|
-
: [{ nextAttemptAt: new Date(officePreviewAttempt) }]),
|
|
3829
|
-
].flatMap((job) => (job ? [job.nextAttemptAt.getTime()] : []));
|
|
1403
|
+
return at === null ? [] : [at];
|
|
1404
|
+
});
|
|
3830
1405
|
|
|
3831
|
-
return
|
|
1406
|
+
return due.length > 0 ? Math.min(...due) : null;
|
|
3832
1407
|
}
|
|
3833
1408
|
|
|
3834
1409
|
/**
|
|
@@ -3864,54 +1439,33 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
3864
1439
|
}
|
|
3865
1440
|
}
|
|
3866
1441
|
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
3870
|
-
if (
|
|
3871
|
-
!message ||
|
|
3872
|
-
message.direction !== "outgoing" ||
|
|
3873
|
-
message.transportState !== "unconfirmed"
|
|
3874
|
-
) {
|
|
3875
|
-
throw new Error("Unconfirmed outgoing message was not found");
|
|
3876
|
-
}
|
|
3877
|
-
|
|
3878
|
-
let delivery: Awaited<ReturnType<typeof prepareOutboundDelivery>>;
|
|
3879
|
-
|
|
3880
|
-
try {
|
|
3881
|
-
delivery = await prepareOutboundDelivery(this.bindings, message);
|
|
3882
|
-
} catch (error) {
|
|
3883
|
-
this.updateTransport(message.id, {
|
|
3884
|
-
state: "failed",
|
|
3885
|
-
error: errorMessage(error),
|
|
3886
|
-
});
|
|
3887
|
-
const failed = this.getEmail(id);
|
|
3888
|
-
|
|
3889
|
-
if (!failed) {
|
|
3890
|
-
throw new Error("Failed message was not persisted", { cause: error });
|
|
3891
|
-
}
|
|
1442
|
+
emptyFolder(state: RetentionFolder) {
|
|
1443
|
+
return mailboxStorage.emptyFolder(this.context, state);
|
|
1444
|
+
}
|
|
3892
1445
|
|
|
3893
|
-
|
|
3894
|
-
|
|
1446
|
+
/**
|
|
1447
|
+
* Call after mail enters Trash or Spam: wakes when the oldest there is due.
|
|
1448
|
+
* Only moves the alarm earlier, so it can run beside `scheduleRemainingWork`.
|
|
1449
|
+
*/
|
|
1450
|
+
private scheduleRetention() {
|
|
1451
|
+
const at = mailboxStorage.nextRetentionAt(this.context);
|
|
3895
1452
|
|
|
3896
|
-
|
|
3897
|
-
|
|
3898
|
-
this.
|
|
3899
|
-
|
|
3900
|
-
|
|
3901
|
-
error: null,
|
|
3902
|
-
});
|
|
3903
|
-
} catch (error) {
|
|
3904
|
-
this.updateTransport(message.id, {
|
|
3905
|
-
state: "unconfirmed",
|
|
3906
|
-
error: errorMessage(error),
|
|
3907
|
-
});
|
|
3908
|
-
}
|
|
1453
|
+
if (at === null) return;
|
|
1454
|
+
this.state.waitUntil(
|
|
1455
|
+
this.scheduleAlarm(Math.max(Date.now() + ALARM_WAKE_DELAY_MS, at))
|
|
1456
|
+
);
|
|
1457
|
+
}
|
|
3909
1458
|
|
|
3910
|
-
|
|
1459
|
+
getAutoReply() {
|
|
1460
|
+
return autoReplies.getAutoReply(this.context);
|
|
1461
|
+
}
|
|
3911
1462
|
|
|
3912
|
-
|
|
1463
|
+
setAutoReply(input: AutoReplyInput, userId: string) {
|
|
1464
|
+
return autoReplies.setAutoReply(this.context, input, userId);
|
|
1465
|
+
}
|
|
3913
1466
|
|
|
3914
|
-
|
|
1467
|
+
turnOffAutoReply(userId: string) {
|
|
1468
|
+
return autoReplies.turnOffAutoReply(this.context, userId);
|
|
3915
1469
|
}
|
|
3916
1470
|
|
|
3917
1471
|
private async scheduleAlarm(at: number) {
|
|
@@ -3942,7 +1496,8 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
3942
1496
|
.select({ email: emails, mailboxState: conversations.mailboxState })
|
|
3943
1497
|
.from(emails)
|
|
3944
1498
|
.leftJoin(conversations, eq(conversations.id, emails.conversationId))
|
|
3945
|
-
.
|
|
1499
|
+
// One bound list: In-Reply-To and References can name 200 ids together.
|
|
1500
|
+
.where(inJsonList(emails.messageIdHeader, candidates))
|
|
3946
1501
|
.orderBy(desc(emails.timelineAt))
|
|
3947
1502
|
.all();
|
|
3948
1503
|
|