-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathactions.ts
More file actions
179 lines (153 loc) · 5.96 KB
/
Copy pathactions.ts
File metadata and controls
179 lines (153 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
"use server"
import { getCurrentUser } from "@/lib/auth"
import { encryptSecret, decryptSecret } from "@/lib/encryption"
import { testImapConnection } from "@/lib/email-sync/imap-client"
import { validateImapTarget } from "@/lib/email-sync/imap-validation"
import { runEmailSync } from "@/lib/email-sync/ingest"
import { getAppData, setAppData } from "@/models/apps"
import { randomUUID } from "crypto"
import { revalidatePath } from "next/cache"
import { EmailAppData, EmailServer } from "./page"
const getDefaultAppData = (): EmailAppData => ({
servers: [],
globalSettings: {
defaultExtensions: [".pdf", ".jpg", ".jpeg", ".png", ".docx", ".xlsx"],
defaultSyncInterval: 60, // minutes (hourly)
},
})
export async function addEmailServerAction(
serverData: Omit<EmailServer, "id" | "status" | "lastSync" | "addedAt">
): Promise<{ success: boolean; error?: string }> {
try {
const user = await getCurrentUser()
const appData = (await getAppData(user, "email")) as EmailAppData | null
const currentData = appData || getDefaultAppData()
await validateImapTarget(serverData.host, serverData.port)
const newServer: EmailServer = {
...serverData,
id: randomUUID(),
status: "pending",
lastSync: undefined,
addedAt: new Date().toISOString(),
password: encryptSecret(serverData.password),
}
const updatedData: EmailAppData = {
...currentData,
servers: [...currentData.servers, newServer],
}
await setAppData(user, "email", updatedData)
revalidatePath("/apps/email")
return { success: true }
} catch (error) {
console.error("Error adding email server:", error)
return { success: false, error: "Failed to add email server" }
}
}
export async function updateEmailServerAction(
serverId: string,
serverData: Partial<EmailServer>
): Promise<{ success: boolean; error?: string }> {
try {
const user = await getCurrentUser()
const appData = (await getAppData(user, "email")) as EmailAppData | null
if (!appData) {
return { success: false, error: "No email servers found" }
}
if (serverData.host !== undefined && serverData.port !== undefined) {
await validateImapTarget(serverData.host, serverData.port)
} else if (serverData.host !== undefined || serverData.port !== undefined) {
const existingServer = appData.servers.find((server) => server.id === serverId)
if (!existingServer) {
return { success: false, error: "Server not found" }
}
await validateImapTarget(serverData.host ?? existingServer.host, serverData.port ?? existingServer.port)
}
const patch = { ...serverData }
if (typeof patch.password === "string" && patch.password.length > 0) {
patch.password = encryptSecret(patch.password)
} else {
delete patch.password
}
const updatedServers = appData.servers.map((server) =>
server.id === serverId ? { ...server, ...patch } : server
)
const updatedData: EmailAppData = {
...appData,
servers: updatedServers,
}
await setAppData(user, "email", updatedData)
revalidatePath("/apps/email")
return { success: true }
} catch (error) {
console.error("Error updating email server:", error)
return { success: false, error: "Failed to update email server" }
}
}
export async function deleteEmailServerAction(serverId: string): Promise<{ success: boolean; error?: string }> {
try {
const user = await getCurrentUser()
const appData = (await getAppData(user, "email")) as EmailAppData | null
if (!appData) {
return { success: false, error: "No email servers found" }
}
const updatedServers = appData.servers.filter((server) => server.id !== serverId)
const updatedData: EmailAppData = {
...appData,
servers: updatedServers,
}
await setAppData(user, "email", updatedData)
revalidatePath("/apps/email")
return { success: true }
} catch (error) {
console.error("Error deleting email server:", error)
return { success: false, error: "Failed to delete email server" }
}
}
export async function testEmailConnectionAction(serverId: string): Promise<{ success: boolean; error?: string }> {
try {
const user = await getCurrentUser()
const appData = (await getAppData(user, "email")) as EmailAppData | null
if (!appData) return { success: false, error: "No email servers found" }
const server = appData.servers.find((s) => s.id === serverId)
if (!server) return { success: false, error: "Server not found" }
let status: EmailServer["status"] = "connected"
let errorMessage: string | undefined
try {
await testImapConnection({
user: server.username,
password: decryptSecret(server.password),
host: server.host,
port: server.port,
tls: server.useSSL,
})
} catch (e) {
status = "error"
errorMessage = e instanceof Error ? e.message : String(e)
}
const updatedData: EmailAppData = {
...appData,
servers: appData.servers.map((s) =>
s.id === serverId ? { ...s, status, errorMessage, lastSync: new Date() } : s
),
}
await setAppData(user, "email", updatedData)
revalidatePath("/apps/email")
return status === "connected" ? { success: true } : { success: false, error: errorMessage }
} catch (error) {
console.error("Error testing email connection:", error)
return { success: false, error: "Connection test failed" }
}
}
export async function syncEmailNowAction(serverId: string): Promise<{ success: boolean; error?: string }> {
try {
const user = await getCurrentUser()
const results = await runEmailSync({ userId: user.id, serverId })
revalidatePath("/apps/email")
const failed = results.find((r) => r.status === "error")
if (failed) return { success: false, error: failed.errorMessage || "Sync failed" }
return { success: true }
} catch (error) {
console.error("Error syncing emails:", error)
return { success: false, error: "Failed to sync emails" }
}
}