@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
|
@@ -0,0 +1,866 @@
|
|
|
1
|
+
import {
|
|
2
|
+
resolveBackedUpPeople,
|
|
3
|
+
createDb,
|
|
4
|
+
mailboxAddressPredicate,
|
|
5
|
+
mailboxAddressSql,
|
|
6
|
+
normalizeMailboxAddress,
|
|
7
|
+
} from "@open-workspace/core/module";
|
|
8
|
+
import type {
|
|
9
|
+
AppEnv,
|
|
10
|
+
BackupRestoreItem,
|
|
11
|
+
BackupRestoreResult,
|
|
12
|
+
BackupSnapshot,
|
|
13
|
+
Database,
|
|
14
|
+
} from "@open-workspace/core/module";
|
|
15
|
+
import { mailboxes } from "@open-workspace/core/schema";
|
|
16
|
+
import { and, eq, isNotNull } from "drizzle-orm";
|
|
17
|
+
import type { Context } from "hono";
|
|
18
|
+
import { z } from "zod";
|
|
19
|
+
|
|
20
|
+
import { autoReplyAudiences, replyActionModes } from "../../shared/mail";
|
|
21
|
+
import { normalizeBlockPattern } from "../../shared/mail-feedback";
|
|
22
|
+
import {
|
|
23
|
+
BLOCK_SENDERS_SCOPE,
|
|
24
|
+
IMPORT_MAIL_SCOPE,
|
|
25
|
+
MAIL_ORGANIZE_SCOPE,
|
|
26
|
+
MAIL_SEND_SCOPE,
|
|
27
|
+
} from "../../shared/permissions";
|
|
28
|
+
import {
|
|
29
|
+
blockedSenders,
|
|
30
|
+
mailboxNotificationPreferences,
|
|
31
|
+
signatures,
|
|
32
|
+
} from "../db/schema";
|
|
33
|
+
import { autoReplyImagePrefix } from "../mail/auto-reply";
|
|
34
|
+
import { importedEmailId } from "../mail/import";
|
|
35
|
+
import { ruleActionSchema, ruleConditionSchema } from "../mail/rules";
|
|
36
|
+
import { storedImageRefSchema } from "../mail/schemas";
|
|
37
|
+
import { signatureImagePrefix } from "../mail/signatures";
|
|
38
|
+
import { draftFileKey } from "../mail/uploads";
|
|
39
|
+
import {
|
|
40
|
+
blocksOwnMailDomain,
|
|
41
|
+
forgetWorkspaceBlockPatterns,
|
|
42
|
+
mailboxBlockRefused,
|
|
43
|
+
} from "../mail/workspace-safety";
|
|
44
|
+
import { mailboxStub } from "../mailbox";
|
|
45
|
+
import type { BackupDraftKey } from "../mailbox/mailbox-backup";
|
|
46
|
+
import {
|
|
47
|
+
PART_BYTES,
|
|
48
|
+
backupFile,
|
|
49
|
+
backupFileParts,
|
|
50
|
+
restoreFileParts,
|
|
51
|
+
} from "./file-parts";
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* What a snapshot keeps beside the mail (mail-backup.ts). In each address's
|
|
55
|
+
* folder: a `settings` line (folders, rules, auto-reply, AI instructions,
|
|
56
|
+
* sender blocks, the address's signature, notification choices), a `draft`
|
|
57
|
+
* line a draft, and a `file` line for each image or file they keep in R2.
|
|
58
|
+
* In `workspace`: the workspace's blocked senders and people's signatures,
|
|
59
|
+
* and their images. Each line names a stored object, so what didn't change
|
|
60
|
+
* costs no storage. People are named by id and primary address.
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
export const WORKSPACE_FOLDER = "workspace";
|
|
64
|
+
|
|
65
|
+
const JSON_OBJECT = { extension: "json", contentType: "application/json" };
|
|
66
|
+
|
|
67
|
+
const FILE_OBJECT = {
|
|
68
|
+
extension: "bin",
|
|
69
|
+
contentType: "application/octet-stream",
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
type UserRef = { id: string; address: string | null };
|
|
73
|
+
|
|
74
|
+
/** A line as written; `restorePiece` reads it back with `pieceLine`. */
|
|
75
|
+
type PieceLine = z.infer<typeof pieceLine> & { object?: string };
|
|
76
|
+
|
|
77
|
+
/** A line to write and its object's bytes; null when the object is gone. */
|
|
78
|
+
type Piece = {
|
|
79
|
+
line: PieceLine;
|
|
80
|
+
type: { extension: string; contentType: string };
|
|
81
|
+
bytes: () => Promise<Uint8Array<ArrayBuffer> | null>;
|
|
82
|
+
largeFile?: { env: Env; key: string; size: number };
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
function jsonPiece(line: PieceLine, json: string) {
|
|
86
|
+
return {
|
|
87
|
+
line,
|
|
88
|
+
type: JSON_OBJECT,
|
|
89
|
+
bytes: () => Promise.resolve(new TextEncoder().encode(json)),
|
|
90
|
+
} satisfies Piece;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function filePiece(env: Env, line: PieceLine, key: string, size = 0) {
|
|
94
|
+
return {
|
|
95
|
+
line,
|
|
96
|
+
type: FILE_OBJECT,
|
|
97
|
+
largeFile: size > PART_BYTES ? { env, key, size } : undefined,
|
|
98
|
+
async bytes() {
|
|
99
|
+
const object = await env.MAIL_STORAGE.get(key);
|
|
100
|
+
|
|
101
|
+
return object ? new Uint8Array(await object.arrayBuffer()) : null;
|
|
102
|
+
},
|
|
103
|
+
} satisfies Piece;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Each person's id with their primary address, which finds them again after a restore. */
|
|
107
|
+
export async function userRefs(db: Database) {
|
|
108
|
+
const rows = await db
|
|
109
|
+
.select({ id: mailboxes.ownerUserId, address: mailboxAddressSql })
|
|
110
|
+
.from(mailboxes)
|
|
111
|
+
.where(eq(mailboxes.isPrimary, true));
|
|
112
|
+
|
|
113
|
+
const addresses = new Map(rows.map((row) => [row.id, row.address]));
|
|
114
|
+
|
|
115
|
+
return (id: string) =>
|
|
116
|
+
({ id, address: addresses.get(id) ?? null }) satisfies UserRef;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** What a mailbox keeps beside its mail, as pieces of the snapshot. */
|
|
120
|
+
export async function mailboxPieces(
|
|
121
|
+
env: Env,
|
|
122
|
+
mailboxId: string,
|
|
123
|
+
/** People by id, read once a batch rather than once an address. */
|
|
124
|
+
refs: ReturnType<typeof userRefs>
|
|
125
|
+
) {
|
|
126
|
+
const db = createDb(env.DB);
|
|
127
|
+
|
|
128
|
+
const [settings, [signature], notifications, ref] = await Promise.all([
|
|
129
|
+
mailboxStub(env, mailboxId).backupSettings(),
|
|
130
|
+
db
|
|
131
|
+
.select({
|
|
132
|
+
html: signatures.html,
|
|
133
|
+
text: signatures.text,
|
|
134
|
+
images: signatures.images,
|
|
135
|
+
useOnNew: signatures.useOnNew,
|
|
136
|
+
useOnReply: signatures.useOnReply,
|
|
137
|
+
})
|
|
138
|
+
.from(signatures)
|
|
139
|
+
.where(eq(signatures.mailboxId, mailboxId))
|
|
140
|
+
.limit(1),
|
|
141
|
+
db
|
|
142
|
+
.select({
|
|
143
|
+
userId: mailboxNotificationPreferences.userId,
|
|
144
|
+
enabled: mailboxNotificationPreferences.enabled,
|
|
145
|
+
})
|
|
146
|
+
.from(mailboxNotificationPreferences)
|
|
147
|
+
.where(eq(mailboxNotificationPreferences.mailboxId, mailboxId)),
|
|
148
|
+
refs,
|
|
149
|
+
]);
|
|
150
|
+
|
|
151
|
+
const kept = {
|
|
152
|
+
...settings,
|
|
153
|
+
signature: signature ?? null,
|
|
154
|
+
notifications: notifications.map((row) => ({
|
|
155
|
+
user: ref(row.userId),
|
|
156
|
+
enabled: row.enabled,
|
|
157
|
+
})),
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const pieces: Piece[] = [];
|
|
161
|
+
|
|
162
|
+
// A mailbox with nothing set adds no line.
|
|
163
|
+
if (
|
|
164
|
+
Object.values(kept).some((value) =>
|
|
165
|
+
Array.isArray(value) ? value.length > 0 : value !== null
|
|
166
|
+
)
|
|
167
|
+
) {
|
|
168
|
+
pieces.push(jsonPiece({ kind: "settings" }, JSON.stringify(kept)));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const autoReplyImages = new Map(
|
|
172
|
+
[
|
|
173
|
+
...(settings.autoReply?.inside.images ?? []),
|
|
174
|
+
...(settings.autoReply?.outside.images ?? []),
|
|
175
|
+
].map((image) => [image.contentId, image])
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
for (const image of autoReplyImages.values()) {
|
|
179
|
+
pieces.push(
|
|
180
|
+
filePiece(
|
|
181
|
+
env,
|
|
182
|
+
{
|
|
183
|
+
kind: "file",
|
|
184
|
+
target: "auto-reply",
|
|
185
|
+
name: image.contentId,
|
|
186
|
+
contentType: image.contentType,
|
|
187
|
+
},
|
|
188
|
+
`${autoReplyImagePrefix(mailboxId)}${image.contentId}`
|
|
189
|
+
)
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
for (const image of signature?.images ?? []) {
|
|
194
|
+
pieces.push(
|
|
195
|
+
filePiece(
|
|
196
|
+
env,
|
|
197
|
+
{
|
|
198
|
+
kind: "file",
|
|
199
|
+
target: "signature",
|
|
200
|
+
name: image.contentId,
|
|
201
|
+
contentType: image.contentType,
|
|
202
|
+
},
|
|
203
|
+
`${signatureImagePrefix(mailboxId)}${image.contentId}`
|
|
204
|
+
)
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return pieces;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Each draft and its files go in the same batch, in restore order. */
|
|
212
|
+
export async function writeMailboxDrafts(
|
|
213
|
+
env: Env,
|
|
214
|
+
snapshot: BackupSnapshot,
|
|
215
|
+
mailbox: { id: string; address: string },
|
|
216
|
+
refs: ReturnType<typeof userRefs>,
|
|
217
|
+
after: BackupDraftKey | null,
|
|
218
|
+
budget: number,
|
|
219
|
+
fullBudget: number
|
|
220
|
+
) {
|
|
221
|
+
const stub = mailboxStub(env, mailbox.id);
|
|
222
|
+
const ref = await refs;
|
|
223
|
+
let stored = 0;
|
|
224
|
+
let last = after;
|
|
225
|
+
|
|
226
|
+
while (stored < budget) {
|
|
227
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- each page starts after the last written draft
|
|
228
|
+
const page = await stub.listBackupDrafts(last);
|
|
229
|
+
|
|
230
|
+
if (!page.length) return { stored, more: false, last };
|
|
231
|
+
|
|
232
|
+
for (const draft of page) {
|
|
233
|
+
const user = ref(draft.userId);
|
|
234
|
+
|
|
235
|
+
const pieces: Piece[] = [
|
|
236
|
+
jsonPiece({ kind: "draft", user }, JSON.stringify(draft)),
|
|
237
|
+
];
|
|
238
|
+
|
|
239
|
+
for (const file of draft.attachments) {
|
|
240
|
+
pieces.push(
|
|
241
|
+
filePiece(
|
|
242
|
+
env,
|
|
243
|
+
{
|
|
244
|
+
kind: "file",
|
|
245
|
+
target: "draft",
|
|
246
|
+
user,
|
|
247
|
+
name: file.uploadId,
|
|
248
|
+
filename: file.filename,
|
|
249
|
+
contentType: file.contentType,
|
|
250
|
+
},
|
|
251
|
+
file.r2Key,
|
|
252
|
+
file.size
|
|
253
|
+
)
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const cost = pieces.reduce((sum, piece) => sum + pieceCost(piece), 0);
|
|
258
|
+
|
|
259
|
+
if (cost > budget - stored && budget - stored < fullBudget) {
|
|
260
|
+
return { stored, more: true, last };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- write this draft and its files before advancing the cursor
|
|
264
|
+
await writePieces(snapshot, mailbox.address, pieces, 0, cost);
|
|
265
|
+
stored += cost;
|
|
266
|
+
last = { userId: draft.userId, id: draft.id };
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return { stored, more: true, last };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** The workspace's blocked senders and people's signatures, as pieces. */
|
|
274
|
+
export async function workspacePieces(env: Env) {
|
|
275
|
+
const db = createDb(env.DB);
|
|
276
|
+
|
|
277
|
+
const [blocked, personal, ref] = await Promise.all([
|
|
278
|
+
db
|
|
279
|
+
.select({
|
|
280
|
+
pattern: blockedSenders.pattern,
|
|
281
|
+
createdAt: blockedSenders.createdAt,
|
|
282
|
+
})
|
|
283
|
+
.from(blockedSenders),
|
|
284
|
+
db
|
|
285
|
+
.select({
|
|
286
|
+
userId: signatures.userId,
|
|
287
|
+
html: signatures.html,
|
|
288
|
+
text: signatures.text,
|
|
289
|
+
images: signatures.images,
|
|
290
|
+
useOnNew: signatures.useOnNew,
|
|
291
|
+
useOnReply: signatures.useOnReply,
|
|
292
|
+
})
|
|
293
|
+
.from(signatures)
|
|
294
|
+
.where(isNotNull(signatures.userId)),
|
|
295
|
+
userRefs(db),
|
|
296
|
+
]);
|
|
297
|
+
|
|
298
|
+
const owned = personal.flatMap(({ userId, ...signature }) =>
|
|
299
|
+
userId ? [{ ...signature, user: ref(userId) }] : []
|
|
300
|
+
);
|
|
301
|
+
|
|
302
|
+
if (!blocked.length && !owned.length) return [];
|
|
303
|
+
|
|
304
|
+
return [
|
|
305
|
+
jsonPiece(
|
|
306
|
+
{ kind: "workspace" },
|
|
307
|
+
JSON.stringify({ blockedSenders: blocked, signatures: owned })
|
|
308
|
+
),
|
|
309
|
+
...owned.flatMap((signature) =>
|
|
310
|
+
signature.images.map((image) =>
|
|
311
|
+
filePiece(
|
|
312
|
+
env,
|
|
313
|
+
{
|
|
314
|
+
kind: "file",
|
|
315
|
+
target: "signature",
|
|
316
|
+
user: signature.user,
|
|
317
|
+
name: image.contentId,
|
|
318
|
+
contentType: image.contentType,
|
|
319
|
+
},
|
|
320
|
+
`${signatureImagePrefix(signature.user.id)}${image.contentId}`
|
|
321
|
+
)
|
|
322
|
+
)
|
|
323
|
+
),
|
|
324
|
+
];
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function pieceCost(piece: Piece) {
|
|
328
|
+
return piece.largeFile ? Math.ceil(piece.largeFile.size / PART_BYTES) : 1;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Stores and writes up to `limit` pieces from `skip` on (each about 3
|
|
333
|
+
* subrequests, as a new message), and resolves to how many it took and
|
|
334
|
+
* where the next batch starts, or null after the last.
|
|
335
|
+
*/
|
|
336
|
+
export async function writePieces(
|
|
337
|
+
snapshot: BackupSnapshot,
|
|
338
|
+
folder: string,
|
|
339
|
+
pieces: Piece[],
|
|
340
|
+
skip: number,
|
|
341
|
+
limit: number
|
|
342
|
+
) {
|
|
343
|
+
const lines: PieceLine[] = [];
|
|
344
|
+
|
|
345
|
+
let stored = 0;
|
|
346
|
+
let next = skip;
|
|
347
|
+
|
|
348
|
+
for (const piece of pieces.slice(skip)) {
|
|
349
|
+
const cost = pieceCost(piece);
|
|
350
|
+
|
|
351
|
+
if (limit <= 0 || (stored > 0 && stored + cost > limit)) break;
|
|
352
|
+
next++;
|
|
353
|
+
stored += cost;
|
|
354
|
+
const label = `${folder} ${piece.line.kind} ${"name" in piece.line ? piece.line.name : ""}`;
|
|
355
|
+
|
|
356
|
+
try {
|
|
357
|
+
if (piece.largeFile && piece.line.kind === "file") {
|
|
358
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- bound concurrent reads for this batch
|
|
359
|
+
const file = await backupFileParts(
|
|
360
|
+
piece.largeFile.env.MAIL_STORAGE,
|
|
361
|
+
piece.largeFile.key,
|
|
362
|
+
snapshot
|
|
363
|
+
);
|
|
364
|
+
|
|
365
|
+
lines.push({ ...piece.line, file });
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- one file in memory at a time
|
|
370
|
+
const bytes = await piece.bytes();
|
|
371
|
+
|
|
372
|
+
if (!bytes) {
|
|
373
|
+
snapshot.error(`${label}: missing, left out`);
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- see above
|
|
378
|
+
const sha256 = await snapshot.putObject(bytes, piece.type);
|
|
379
|
+
lines.push({
|
|
380
|
+
...piece.line,
|
|
381
|
+
object: `${sha256}.${piece.type.extension}`,
|
|
382
|
+
});
|
|
383
|
+
} catch (cause) {
|
|
384
|
+
snapshot.error(
|
|
385
|
+
`${label}: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
if (lines.length) snapshot.writeLines(folder, lines);
|
|
391
|
+
|
|
392
|
+
return {
|
|
393
|
+
stored,
|
|
394
|
+
next: next < pieces.length ? next : null,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** The address a folder of the snapshot is for, if it is here and keeps mail. */
|
|
399
|
+
export async function mailboxAt(env: Env, folder: string) {
|
|
400
|
+
const address = normalizeMailboxAddress(folder);
|
|
401
|
+
|
|
402
|
+
const [mailbox] = await createDb(env.DB)
|
|
403
|
+
.select({ id: mailboxes.id, address: mailboxAddressSql })
|
|
404
|
+
.from(mailboxes)
|
|
405
|
+
.where(
|
|
406
|
+
and(mailboxAddressPredicate(address), eq(mailboxes.delivery, "inbox"))
|
|
407
|
+
)
|
|
408
|
+
.limit(1);
|
|
409
|
+
|
|
410
|
+
return mailbox ?? null;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const id = z.string().min(1).max(200);
|
|
414
|
+
|
|
415
|
+
/** A content or upload id, the last part of an R2 key. */
|
|
416
|
+
const keyName = id.regex(/^[^/\\]+$/u).refine((name) => !/^\.\.?$/u.test(name));
|
|
417
|
+
|
|
418
|
+
export const userRef = z.object({
|
|
419
|
+
id,
|
|
420
|
+
address: z.string().max(320).nullable(),
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
const date = z.coerce.date();
|
|
424
|
+
|
|
425
|
+
const richImage = z.object({
|
|
426
|
+
contentId: keyName,
|
|
427
|
+
filename: z.string().max(255),
|
|
428
|
+
contentType: z.string().max(255),
|
|
429
|
+
size: z.number().int().nonnegative(),
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
const richMessage = z.object({
|
|
433
|
+
enabled: z.boolean(),
|
|
434
|
+
subject: z.string().max(998).nullable(),
|
|
435
|
+
html: z.string(),
|
|
436
|
+
text: z.string(),
|
|
437
|
+
images: z.array(richImage),
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
const signature = z.object({
|
|
441
|
+
html: z.string(),
|
|
442
|
+
text: z.string(),
|
|
443
|
+
images: z.array(richImage),
|
|
444
|
+
useOnNew: z.boolean(),
|
|
445
|
+
useOnReply: z.boolean(),
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
const settingsObject = z.object({
|
|
449
|
+
folders: z.array(
|
|
450
|
+
z.object({ id, name: z.string().max(80), sortOrder: z.number().int() })
|
|
451
|
+
),
|
|
452
|
+
systemFolderOrder: z.array(
|
|
453
|
+
z.object({ folderId: id, sortOrder: z.number().int() })
|
|
454
|
+
),
|
|
455
|
+
rules: z.array(
|
|
456
|
+
z.object({
|
|
457
|
+
id,
|
|
458
|
+
position: z.number().int(),
|
|
459
|
+
name: z.string().max(200),
|
|
460
|
+
enabled: z.boolean(),
|
|
461
|
+
match: z.enum(["all", "any"]),
|
|
462
|
+
conditionsJson: z.array(ruleConditionSchema),
|
|
463
|
+
actionsJson: z.array(ruleActionSchema),
|
|
464
|
+
stopProcessing: z.boolean(),
|
|
465
|
+
updatedAt: date,
|
|
466
|
+
})
|
|
467
|
+
),
|
|
468
|
+
autoReply: z
|
|
469
|
+
.object({
|
|
470
|
+
id: z.number().int(),
|
|
471
|
+
enabled: z.boolean(),
|
|
472
|
+
startsAt: date.nullable(),
|
|
473
|
+
endsAt: date.nullable(),
|
|
474
|
+
replyIntervalDays: z.number().int().positive(),
|
|
475
|
+
inside: richMessage,
|
|
476
|
+
outside: richMessage.extend({ audience: z.enum(autoReplyAudiences) }),
|
|
477
|
+
updatedBy: id,
|
|
478
|
+
updatedAt: date,
|
|
479
|
+
})
|
|
480
|
+
.nullable(),
|
|
481
|
+
autoReplyLog: z.array(
|
|
482
|
+
z.object({
|
|
483
|
+
senderAddress: z.string().max(320),
|
|
484
|
+
lastRepliedAt: date,
|
|
485
|
+
lastOriginalEmailId: id,
|
|
486
|
+
lastOutboundMessageId: z.string().max(998).nullable(),
|
|
487
|
+
})
|
|
488
|
+
),
|
|
489
|
+
ai: z
|
|
490
|
+
.object({
|
|
491
|
+
id,
|
|
492
|
+
instructions: z.string().max(4000),
|
|
493
|
+
confidenceThreshold: z.number().int().min(50).max(100),
|
|
494
|
+
updatedAt: date,
|
|
495
|
+
})
|
|
496
|
+
.nullable(),
|
|
497
|
+
senders: z.array(
|
|
498
|
+
z.object({
|
|
499
|
+
address: z.string().max(320),
|
|
500
|
+
domain: z.string().max(320),
|
|
501
|
+
blockedAt: date.nullable(),
|
|
502
|
+
trustedAt: date.nullable(),
|
|
503
|
+
})
|
|
504
|
+
),
|
|
505
|
+
signature: signature.nullable(),
|
|
506
|
+
notifications: z.array(z.object({ user: userRef, enabled: z.boolean() })),
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
const draftObject = z.object({
|
|
510
|
+
id,
|
|
511
|
+
kind: z.enum(["compose", "reply", "forward"]),
|
|
512
|
+
sourceEmailId: id.nullable(),
|
|
513
|
+
forwardedFiles: z.array(z.string()).nullable().default(null),
|
|
514
|
+
/** The Message-ID of the message replied to or forwarded (snapshots from 0.4.0 lack it). */
|
|
515
|
+
sourceMessageId: z.string().max(998).nullable().default(null),
|
|
516
|
+
conversationId: id.nullable(),
|
|
517
|
+
replyMode: z.enum(replyActionModes).nullable(),
|
|
518
|
+
to: z.array(z.string().max(998)),
|
|
519
|
+
cc: z.array(z.string().max(998)),
|
|
520
|
+
bcc: z.array(z.string().max(998)),
|
|
521
|
+
replyTo: z.string().max(998).nullable(),
|
|
522
|
+
subject: z.string(),
|
|
523
|
+
bodyText: z.string(),
|
|
524
|
+
bodyHtml: z.string().nullable(),
|
|
525
|
+
editorHtml: z.string().nullable(),
|
|
526
|
+
// The editor HTML refers to the copied signature image by its original owner and CID.
|
|
527
|
+
attachments: z.array(
|
|
528
|
+
z.object({
|
|
529
|
+
assetId: id,
|
|
530
|
+
storedImage: storedImageRefSchema.optional(),
|
|
531
|
+
uploadId: keyName,
|
|
532
|
+
disposition: z.enum(["attachment", "inline"]),
|
|
533
|
+
contentId: z.string().max(998).nullable(),
|
|
534
|
+
filename: z.string().max(255),
|
|
535
|
+
contentType: z.string().max(255),
|
|
536
|
+
size: z.number().int().nonnegative(),
|
|
537
|
+
})
|
|
538
|
+
),
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
const workspaceObject = z.object({
|
|
542
|
+
blockedSenders: z.array(
|
|
543
|
+
z.object({ pattern: z.string().max(320), createdAt: date })
|
|
544
|
+
),
|
|
545
|
+
signatures: z.array(signature.extend({ user: userRef })),
|
|
546
|
+
});
|
|
547
|
+
|
|
548
|
+
const pieceLine = z.discriminatedUnion("kind", [
|
|
549
|
+
z.object({ kind: z.literal("settings") }),
|
|
550
|
+
z.object({ kind: z.literal("draft"), user: userRef }),
|
|
551
|
+
z.object({ kind: z.literal("workspace") }),
|
|
552
|
+
z.object({
|
|
553
|
+
kind: z.literal("file"),
|
|
554
|
+
target: z.enum(["draft", "auto-reply", "signature"]),
|
|
555
|
+
file: backupFile.optional(),
|
|
556
|
+
user: userRef.optional(),
|
|
557
|
+
name: keyName,
|
|
558
|
+
filename: z.string().max(255).optional(),
|
|
559
|
+
contentType: z.string().max(255),
|
|
560
|
+
}),
|
|
561
|
+
]);
|
|
562
|
+
|
|
563
|
+
function parseObject<T>(schema: z.ZodType<T>, object: Uint8Array) {
|
|
564
|
+
try {
|
|
565
|
+
return schema.safeParse(JSON.parse(new TextDecoder().decode(object))).data;
|
|
566
|
+
} catch {
|
|
567
|
+
return undefined;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** Writing into any mailbox, as importing does, with what its own route asks. */
|
|
572
|
+
const anyMailbox = (scope: string) => [IMPORT_MAIL_SCOPE, scope];
|
|
573
|
+
|
|
574
|
+
/** A team address's signature: Administration → Teams. */
|
|
575
|
+
const TEAMS_SCOPE = "admin.teams";
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* The scopes restoring a piece needs: those of the routes that write what
|
|
579
|
+
* it holds, and `admin.import_mail` for anyone's mailbox, as only importing
|
|
580
|
+
* may write there. Folders, rules, the auto-reply, AI instructions, sender
|
|
581
|
+
* choices, people's signatures and notification choices: `mail.organize`;
|
|
582
|
+
* drafts and their files: `mail.send`; a team address's signature:
|
|
583
|
+
* `admin.teams`; the workspace's blocked senders: `admin.blocked_senders`.
|
|
584
|
+
* Null for a line that is no piece (a message).
|
|
585
|
+
*/
|
|
586
|
+
export function pieceScopes({ line, object }: BackupRestoreItem) {
|
|
587
|
+
const piece = pieceLine.safeParse(line).data;
|
|
588
|
+
|
|
589
|
+
if (!piece) return null;
|
|
590
|
+
|
|
591
|
+
switch (piece.kind) {
|
|
592
|
+
case "draft": {
|
|
593
|
+
return anyMailbox(MAIL_SEND_SCOPE);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
case "file": {
|
|
597
|
+
if (piece.target === "draft") return anyMailbox(MAIL_SEND_SCOPE);
|
|
598
|
+
|
|
599
|
+
return piece.target === "signature" && !piece.user
|
|
600
|
+
? [TEAMS_SCOPE]
|
|
601
|
+
: anyMailbox(MAIL_ORGANIZE_SCOPE);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
case "settings": {
|
|
605
|
+
const data = object && parseObject(settingsObject, object);
|
|
606
|
+
|
|
607
|
+
return [
|
|
608
|
+
...anyMailbox(MAIL_ORGANIZE_SCOPE),
|
|
609
|
+
...(data?.signature ? [TEAMS_SCOPE] : []),
|
|
610
|
+
];
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
case "workspace": {
|
|
614
|
+
const data = object && parseObject(workspaceObject, object);
|
|
615
|
+
|
|
616
|
+
return [
|
|
617
|
+
...(data?.blockedSenders.length ? [BLOCK_SENDERS_SCOPE] : []),
|
|
618
|
+
...(data?.signatures.length ? anyMailbox(MAIL_ORGANIZE_SCOPE) : []),
|
|
619
|
+
];
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
default: {
|
|
623
|
+
const unexpected: never = piece;
|
|
624
|
+
throw new Error(`Unknown backup piece ${JSON.stringify(unexpected)}`);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
const restored = (changed: boolean) =>
|
|
630
|
+
({
|
|
631
|
+
status: changed ? "restored" : "exists",
|
|
632
|
+
}) satisfies BackupRestoreResult;
|
|
633
|
+
|
|
634
|
+
const skipped = (reason: string) =>
|
|
635
|
+
({
|
|
636
|
+
status: "skipped",
|
|
637
|
+
reason,
|
|
638
|
+
}) satisfies BackupRestoreResult;
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Puts a piece back; what exists is left as it is. Null for a line that
|
|
642
|
+
* is no piece (a message).
|
|
643
|
+
*/
|
|
644
|
+
export async function restorePiece(
|
|
645
|
+
c: Context<AppEnv>,
|
|
646
|
+
{ folder, line, object }: BackupRestoreItem
|
|
647
|
+
) {
|
|
648
|
+
const piece = pieceLine.safeParse(line).data;
|
|
649
|
+
|
|
650
|
+
if (!piece) return null;
|
|
651
|
+
|
|
652
|
+
if (!object && !(piece.kind === "file" && piece.file)) {
|
|
653
|
+
return skipped("missing");
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const { env } = c;
|
|
657
|
+
const db = createDb(env.DB);
|
|
658
|
+
|
|
659
|
+
const mailbox =
|
|
660
|
+
folder === WORKSPACE_FOLDER ? null : await mailboxAt(env, folder);
|
|
661
|
+
|
|
662
|
+
if (folder !== WORKSPACE_FOLDER && !mailbox) {
|
|
663
|
+
return skipped(`no mailbox ${folder}`);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const person = "user" in piece ? piece.user : undefined;
|
|
667
|
+
|
|
668
|
+
const owner = person
|
|
669
|
+
? (await resolveBackedUpPeople(db, [person])).get(person)
|
|
670
|
+
: null;
|
|
671
|
+
|
|
672
|
+
if (person && !owner) {
|
|
673
|
+
return skipped("no such person");
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
if (piece.kind === "workspace") {
|
|
677
|
+
const data = object && parseObject(workspaceObject, object);
|
|
678
|
+
|
|
679
|
+
if (!data) return skipped("damaged");
|
|
680
|
+
const actor = c.get("user").id;
|
|
681
|
+
|
|
682
|
+
const blocks = await Promise.all(
|
|
683
|
+
data.blockedSenders.map((row) => {
|
|
684
|
+
const pattern = normalizeBlockPattern(row.pattern);
|
|
685
|
+
|
|
686
|
+
// As the admin screen: never the workspace's own mail domains.
|
|
687
|
+
return pattern && !blocksOwnMailDomain(pattern)
|
|
688
|
+
? db
|
|
689
|
+
.insert(blockedSenders)
|
|
690
|
+
.values({
|
|
691
|
+
pattern,
|
|
692
|
+
createdByUserId: actor,
|
|
693
|
+
createdAt: row.createdAt,
|
|
694
|
+
})
|
|
695
|
+
.onConflictDoNothing()
|
|
696
|
+
.returning({ pattern: blockedSenders.pattern })
|
|
697
|
+
: [];
|
|
698
|
+
})
|
|
699
|
+
);
|
|
700
|
+
|
|
701
|
+
if (blocks.flat().length) forgetWorkspaceBlockPatterns();
|
|
702
|
+
|
|
703
|
+
const people = await resolveBackedUpPeople(
|
|
704
|
+
db,
|
|
705
|
+
data.signatures.map(({ user }) => user)
|
|
706
|
+
);
|
|
707
|
+
|
|
708
|
+
const added = await Promise.all(
|
|
709
|
+
data.signatures.map(({ user, ...row }) => {
|
|
710
|
+
const userId = people.get(user);
|
|
711
|
+
|
|
712
|
+
return userId
|
|
713
|
+
? db
|
|
714
|
+
.insert(signatures)
|
|
715
|
+
.values({ ...row, userId })
|
|
716
|
+
.onConflictDoNothing()
|
|
717
|
+
.returning({ userId: signatures.userId })
|
|
718
|
+
: [];
|
|
719
|
+
})
|
|
720
|
+
);
|
|
721
|
+
|
|
722
|
+
return restored([...blocks, ...added].flat().length > 0);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
if (piece.kind === "file") {
|
|
726
|
+
// Where the file lives under its new owner: the address, or the person.
|
|
727
|
+
const prefixes = {
|
|
728
|
+
signature: owner ?? mailbox?.id,
|
|
729
|
+
"auto-reply": mailbox && autoReplyImagePrefix(mailbox.id),
|
|
730
|
+
draft: mailbox && owner && draftFileKey(mailbox.id, owner, ""),
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
const prefix =
|
|
734
|
+
piece.target === "signature"
|
|
735
|
+
? prefixes.signature && signatureImagePrefix(prefixes.signature)
|
|
736
|
+
: prefixes[piece.target];
|
|
737
|
+
|
|
738
|
+
if (!prefix) return skipped("no owner");
|
|
739
|
+
const target = `${prefix}${piece.name}`;
|
|
740
|
+
|
|
741
|
+
// Keep a dependent file retryable if its draft was skipped or failed.
|
|
742
|
+
if (
|
|
743
|
+
piece.target === "draft" &&
|
|
744
|
+
mailbox &&
|
|
745
|
+
owner &&
|
|
746
|
+
!(await mailboxStub(env, mailbox.id).holdsDraftFile(owner, target))
|
|
747
|
+
) {
|
|
748
|
+
return skipped("no draft holds this file");
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
if (await env.MAIL_STORAGE.head(target)) return restored(false);
|
|
752
|
+
|
|
753
|
+
const options = {
|
|
754
|
+
httpMetadata: { contentType: piece.contentType },
|
|
755
|
+
customMetadata: piece.filename
|
|
756
|
+
? { filename: piece.filename, contentType: piece.contentType }
|
|
757
|
+
: undefined,
|
|
758
|
+
};
|
|
759
|
+
|
|
760
|
+
if (piece.file) {
|
|
761
|
+
await restoreFileParts(
|
|
762
|
+
env.MAIL_STORAGE,
|
|
763
|
+
c.get("user").id,
|
|
764
|
+
target,
|
|
765
|
+
piece.file,
|
|
766
|
+
options
|
|
767
|
+
);
|
|
768
|
+
} else if (object) await env.MAIL_STORAGE.put(target, object, options);
|
|
769
|
+
|
|
770
|
+
// A draft's file goes again unless a draft holds it: its draft line
|
|
771
|
+
// comes first, so a draft that was skipped (the drafts limit, one already
|
|
772
|
+
// there) leaves no stray file. The queue keeps keys a draft holds.
|
|
773
|
+
if (piece.target === "draft" && mailbox) {
|
|
774
|
+
await mailboxStub(env, mailbox.id).forgetDraftFiles([target]);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
return restored(true);
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
if (!mailbox) return skipped("not a workspace line");
|
|
781
|
+
const stub = mailboxStub(env, mailbox.id);
|
|
782
|
+
|
|
783
|
+
if (piece.kind === "draft") {
|
|
784
|
+
const draft = object && parseObject(draftObject, object);
|
|
785
|
+
|
|
786
|
+
if (!draft || !owner) return skipped("damaged");
|
|
787
|
+
const { sourceMessageId, forwardedFiles, ...input } = draft;
|
|
788
|
+
|
|
789
|
+
const status = await stub.restoreDraft(
|
|
790
|
+
owner,
|
|
791
|
+
{
|
|
792
|
+
...input,
|
|
793
|
+
forwardedAttachmentIds: null,
|
|
794
|
+
attachments: input.attachments.map((file) => ({
|
|
795
|
+
...file,
|
|
796
|
+
r2Key: draftFileKey(mailbox.id, owner, file.uploadId),
|
|
797
|
+
})),
|
|
798
|
+
},
|
|
799
|
+
{
|
|
800
|
+
id: input.sourceEmailId
|
|
801
|
+
? await importedEmailId(`backup:${input.sourceEmailId}`)
|
|
802
|
+
: null,
|
|
803
|
+
messageId: sourceMessageId,
|
|
804
|
+
forwardedFiles,
|
|
805
|
+
}
|
|
806
|
+
);
|
|
807
|
+
|
|
808
|
+
if (status === "replyExists") {
|
|
809
|
+
return skipped("conversation already has a reply draft");
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
return status === "limit"
|
|
813
|
+
? skipped("drafts limit")
|
|
814
|
+
: restored(status === "saved");
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
const data = object && parseObject(settingsObject, object);
|
|
818
|
+
|
|
819
|
+
if (!data) return skipped("damaged");
|
|
820
|
+
const { signature: own, notifications, ...settings } = data;
|
|
821
|
+
|
|
822
|
+
const people = await resolveBackedUpPeople(
|
|
823
|
+
db,
|
|
824
|
+
notifications.map(({ user }) => user)
|
|
825
|
+
);
|
|
826
|
+
|
|
827
|
+
const [mailboxSettings, kept, choices] = await Promise.all([
|
|
828
|
+
stub.restoreSettings({
|
|
829
|
+
...settings,
|
|
830
|
+
// As the mailbox's screen: never a block it may not hold.
|
|
831
|
+
senders: settings.senders.filter(
|
|
832
|
+
(sender) =>
|
|
833
|
+
!sender.blockedAt ||
|
|
834
|
+
!mailboxBlockRefused(mailbox.address, sender.address)
|
|
835
|
+
),
|
|
836
|
+
}),
|
|
837
|
+
own
|
|
838
|
+
? db
|
|
839
|
+
.insert(signatures)
|
|
840
|
+
.values({ ...own, mailboxId: mailbox.id })
|
|
841
|
+
.onConflictDoNothing()
|
|
842
|
+
.returning({ mailboxId: signatures.mailboxId })
|
|
843
|
+
: [],
|
|
844
|
+
Promise.all(
|
|
845
|
+
notifications.map(({ user, enabled }) => {
|
|
846
|
+
const userId = people.get(user);
|
|
847
|
+
|
|
848
|
+
return userId
|
|
849
|
+
? db
|
|
850
|
+
.insert(mailboxNotificationPreferences)
|
|
851
|
+
.values({ mailboxId: mailbox.id, userId, enabled })
|
|
852
|
+
.onConflictDoNothing()
|
|
853
|
+
.returning({ userId: mailboxNotificationPreferences.userId })
|
|
854
|
+
: [];
|
|
855
|
+
})
|
|
856
|
+
),
|
|
857
|
+
]);
|
|
858
|
+
|
|
859
|
+
if (mailboxSettings.skipped.length) {
|
|
860
|
+
return skipped(mailboxSettings.skipped.join(", "));
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
return restored(
|
|
864
|
+
mailboxSettings.changed || kept.length > 0 || choices.flat().length > 0
|
|
865
|
+
);
|
|
866
|
+
}
|