@mysterycode-liwen/dsh-mail 1.1.0 → 1.3.0
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/LICENSE +21 -21
- package/README.md +238 -219
- package/bridge.py +1257 -1131
- package/client.js +580 -163
- package/cordis.patch.yml +8 -8
- package/icon.svg +3 -3
- package/index.js +497 -396
- package/package.json +64 -64
- package/tools.js +158 -158
package/index.js
CHANGED
|
@@ -1,396 +1,497 @@
|
|
|
1
|
-
import { execFile } from 'node:child_process';
|
|
2
|
-
import { promisify } from 'node:util';
|
|
3
|
-
import { fileURLToPath } from 'node:url';
|
|
4
|
-
import { existsSync } from 'node:fs';
|
|
5
|
-
|
|
6
|
-
const execFileAsync = promisify(execFile);
|
|
7
|
-
const BRIDGE_PATH = fileURLToPath(new URL('./bridge.py', import.meta.url));
|
|
8
|
-
|
|
9
|
-
export const inject = ['connection', 'credentials', 'tools'];
|
|
10
|
-
|
|
11
|
-
import { mailQueryTool } from './tools.js';
|
|
12
|
-
|
|
13
|
-
const API = '/api/dsh-mail';
|
|
14
|
-
|
|
15
|
-
function candidatePythons() {
|
|
16
|
-
return [
|
|
17
|
-
process.env.MAIL_PYTHON,
|
|
18
|
-
'C:\\Python314\\python.exe',
|
|
19
|
-
'C:\\Python313\\python.exe',
|
|
20
|
-
'C:\\Python312\\python.exe',
|
|
21
|
-
'C:\\Python311\\python.exe',
|
|
22
|
-
'C:\\Python310\\python.exe',
|
|
23
|
-
'python',
|
|
24
|
-
].filter(Boolean);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function findPython() {
|
|
28
|
-
for (const candidate of candidatePythons()) {
|
|
29
|
-
if (candidate === 'python' || existsSync(candidate)) return candidate;
|
|
30
|
-
}
|
|
31
|
-
return 'python';
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
async function runBridge(op, extra = {}) {
|
|
35
|
-
const request = JSON.stringify({ op, ...extra });
|
|
36
|
-
const { stdout } = await execFileAsync(findPython(), [BRIDGE_PATH], {
|
|
37
|
-
env: { ...process.env, MAIL_REQUEST: request },
|
|
38
|
-
maxBuffer: 4 * 1024 * 1024,
|
|
39
|
-
timeout: 90000,
|
|
40
|
-
});
|
|
41
|
-
const text = String(stdout).trim();
|
|
42
|
-
if (!text) return { ok: false, error: 'bridge returned empty output' };
|
|
43
|
-
try {
|
|
44
|
-
return JSON.parse(text);
|
|
45
|
-
} catch {
|
|
46
|
-
return { ok: false, error: 'bridge returned invalid JSON: ' + text.slice(0, 200) };
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function accountId(seed) {
|
|
51
|
-
let h = 2166136261;
|
|
52
|
-
for (const ch of String(seed)) {
|
|
53
|
-
h ^= ch.charCodeAt(0);
|
|
54
|
-
h = Math.imul(h, 16777619) >>> 0;
|
|
55
|
-
}
|
|
56
|
-
return 'acct-' + h.toString(16).padStart(8, '0');
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function recordKey(id) {
|
|
60
|
-
return 'mail/' + id;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function outboxKey(id) {
|
|
64
|
-
return 'mail-outbox/' + id;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function contactsKey(id) {
|
|
68
|
-
return 'mail-contacts/' + id;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// Global plugin settings live under their own scope so listAccounts (which
|
|
72
|
-
// treats every "mail/<id>" record as an account) never picks this record up.
|
|
73
|
-
const SETTINGS_KEY = 'mail-settings/main';
|
|
74
|
-
|
|
75
|
-
async function readSettings(ctx) {
|
|
76
|
-
const data = await readData(ctx, SETTINGS_KEY, {});
|
|
77
|
-
const rawInterval = Number(data.notifyInterval);
|
|
78
|
-
return {
|
|
79
|
-
agentMailAccess: data.agentMailAccess === true,
|
|
80
|
-
// New-mail alerts are on by default. Delivery is via the desktop pet
|
|
81
|
-
// (default), a browser system notification, or both.
|
|
82
|
-
notifyEnabled: data.notifyEnabled !== false,
|
|
83
|
-
// Clamp to 15s..3600s; 60s default. Keeps IMAP polling reasonable.
|
|
84
|
-
notifyInterval: Number.isFinite(rawInterval) ? Math.min(3600, Math.max(15, Math.round(rawInterval))) : 60,
|
|
85
|
-
notifyMode: ['pet', 'system', 'both'].includes(data.notifyMode) ? data.notifyMode : 'pet',
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
async function writeSettings(ctx, value) {
|
|
90
|
-
const input = value && typeof value === 'object' ? value : {};
|
|
91
|
-
const rawInterval = Number(input.notifyInterval);
|
|
92
|
-
const next = {
|
|
93
|
-
agentMailAccess: input.agentMailAccess === true,
|
|
94
|
-
notifyEnabled: input.notifyEnabled !== false,
|
|
95
|
-
notifyInterval: Number.isFinite(rawInterval) ? Math.min(3600, Math.max(15, Math.round(rawInterval))) : 60,
|
|
96
|
-
notifyMode: ['pet', 'system', 'both'].includes(input.notifyMode) ? input.notifyMode : 'pet',
|
|
97
|
-
};
|
|
98
|
-
await writeData(ctx, SETTINGS_KEY, next);
|
|
99
|
-
return next;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
// Read a plain JSON payload record (kind 'grant') from the credential store, returning
|
|
103
|
-
// a fallback when it does not exist yet. Account-specific data lives under a
|
|
104
|
-
// key derived from the account id, so switching accounts never mixes data.
|
|
105
|
-
async function readData(ctx, key, fallback) {
|
|
106
|
-
try {
|
|
107
|
-
const record = await ctx.credentials.readRecord(key);
|
|
108
|
-
if (record && (record.kind === 'grant' || record.kind === 'data') && record.payload && typeof record.payload === 'object') {
|
|
109
|
-
return record.payload;
|
|
110
|
-
}
|
|
111
|
-
} catch {
|
|
112
|
-
// First use: the record simply does not exist.
|
|
113
|
-
}
|
|
114
|
-
return fallback;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
async function writeData(ctx, key, payload) {
|
|
118
|
-
await ctx.credentials.modifyRecord(key, async () => ({ kind: 'grant', payload }));
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// Contacts are stored locally only (per account in the credential store);
|
|
122
|
-
// they are never written to the IMAP server.
|
|
123
|
-
function publicAccount(id, payload) {
|
|
124
|
-
return {
|
|
125
|
-
id,
|
|
126
|
-
name: payload.name || payload.username,
|
|
127
|
-
username: payload.username,
|
|
128
|
-
imapHost: payload.imapHost,
|
|
129
|
-
imapPort: payload.imapPort,
|
|
130
|
-
smtpHost: payload.smtpHost,
|
|
131
|
-
smtpPort: payload.smtpPort,
|
|
132
|
-
imapTls: payload.imapTls !== false,
|
|
133
|
-
smtpTls: payload.smtpTls !== false,
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
async function listAccounts(ctx) {
|
|
138
|
-
const entries = await ctx.credentials.listRecords();
|
|
139
|
-
const accounts = [];
|
|
140
|
-
for (const entry of entries) {
|
|
141
|
-
const key = String(entry.key);
|
|
142
|
-
if (!key.startsWith('mail/')) continue;
|
|
143
|
-
const id = key.slice(5);
|
|
144
|
-
const record = await ctx.credentials.readRecord(key);
|
|
145
|
-
if (!record || record.kind !== 'grant' || typeof record.payload !== 'object' || record.payload === null) continue;
|
|
146
|
-
accounts.push(publicAccount(id, record.payload));
|
|
147
|
-
}
|
|
148
|
-
return accounts.sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
async function getAccountPayload(ctx, id) {
|
|
152
|
-
const record = await ctx.credentials.readRecord(recordKey(id));
|
|
153
|
-
if (!record || record.kind !== 'grant' || typeof record.payload !== 'object' || record.payload === null) {
|
|
154
|
-
throw new Error('account not found: ' + id);
|
|
155
|
-
}
|
|
156
|
-
return record.payload;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
function bridgeAccount(payload) {
|
|
160
|
-
return {
|
|
161
|
-
username: payload.username,
|
|
162
|
-
authCode: payload.authCode,
|
|
163
|
-
imapHost: payload.imapHost,
|
|
164
|
-
imapPort: Number(payload.imapPort) || 993,
|
|
165
|
-
smtpHost: payload.smtpHost,
|
|
166
|
-
smtpPort: Number(payload.smtpPort) || 465,
|
|
167
|
-
imapTls: payload.imapTls !== false,
|
|
168
|
-
smtpTls: payload.smtpTls !== false,
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
function json(result, status = 200) {
|
|
173
|
-
return new Response(JSON.stringify(result), {
|
|
174
|
-
status,
|
|
175
|
-
headers: { 'content-type': 'application/json; charset=utf-8' },
|
|
176
|
-
});
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
}
|
|
294
|
-
if (
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
const payload = await getAccountPayload(ctx, id);
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
const
|
|
352
|
-
const
|
|
353
|
-
if (!
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
|
|
6
|
+
const execFileAsync = promisify(execFile);
|
|
7
|
+
const BRIDGE_PATH = fileURLToPath(new URL('./bridge.py', import.meta.url));
|
|
8
|
+
|
|
9
|
+
export const inject = ['connection', 'credentials', 'tools'];
|
|
10
|
+
|
|
11
|
+
import { mailQueryTool } from './tools.js';
|
|
12
|
+
|
|
13
|
+
const API = '/api/dsh-mail';
|
|
14
|
+
|
|
15
|
+
function candidatePythons() {
|
|
16
|
+
return [
|
|
17
|
+
process.env.MAIL_PYTHON,
|
|
18
|
+
'C:\\Python314\\python.exe',
|
|
19
|
+
'C:\\Python313\\python.exe',
|
|
20
|
+
'C:\\Python312\\python.exe',
|
|
21
|
+
'C:\\Python311\\python.exe',
|
|
22
|
+
'C:\\Python310\\python.exe',
|
|
23
|
+
'python',
|
|
24
|
+
].filter(Boolean);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function findPython() {
|
|
28
|
+
for (const candidate of candidatePythons()) {
|
|
29
|
+
if (candidate === 'python' || existsSync(candidate)) return candidate;
|
|
30
|
+
}
|
|
31
|
+
return 'python';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function runBridge(op, extra = {}) {
|
|
35
|
+
const request = JSON.stringify({ op, ...extra });
|
|
36
|
+
const { stdout } = await execFileAsync(findPython(), [BRIDGE_PATH], {
|
|
37
|
+
env: { ...process.env, MAIL_REQUEST: request },
|
|
38
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
39
|
+
timeout: 90000,
|
|
40
|
+
});
|
|
41
|
+
const text = String(stdout).trim();
|
|
42
|
+
if (!text) return { ok: false, error: 'bridge returned empty output' };
|
|
43
|
+
try {
|
|
44
|
+
return JSON.parse(text);
|
|
45
|
+
} catch {
|
|
46
|
+
return { ok: false, error: 'bridge returned invalid JSON: ' + text.slice(0, 200) };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function accountId(seed) {
|
|
51
|
+
let h = 2166136261;
|
|
52
|
+
for (const ch of String(seed)) {
|
|
53
|
+
h ^= ch.charCodeAt(0);
|
|
54
|
+
h = Math.imul(h, 16777619) >>> 0;
|
|
55
|
+
}
|
|
56
|
+
return 'acct-' + h.toString(16).padStart(8, '0');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function recordKey(id) {
|
|
60
|
+
return 'mail/' + id;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function outboxKey(id) {
|
|
64
|
+
return 'mail-outbox/' + id;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function contactsKey(id) {
|
|
68
|
+
return 'mail-contacts/' + id;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Global plugin settings live under their own scope so listAccounts (which
|
|
72
|
+
// treats every "mail/<id>" record as an account) never picks this record up.
|
|
73
|
+
const SETTINGS_KEY = 'mail-settings/main';
|
|
74
|
+
|
|
75
|
+
async function readSettings(ctx) {
|
|
76
|
+
const data = await readData(ctx, SETTINGS_KEY, {});
|
|
77
|
+
const rawInterval = Number(data.notifyInterval);
|
|
78
|
+
return {
|
|
79
|
+
agentMailAccess: data.agentMailAccess === true,
|
|
80
|
+
// New-mail alerts are on by default. Delivery is via the desktop pet
|
|
81
|
+
// (default), a browser system notification, or both.
|
|
82
|
+
notifyEnabled: data.notifyEnabled !== false,
|
|
83
|
+
// Clamp to 15s..3600s; 60s default. Keeps IMAP polling reasonable.
|
|
84
|
+
notifyInterval: Number.isFinite(rawInterval) ? Math.min(3600, Math.max(15, Math.round(rawInterval))) : 60,
|
|
85
|
+
notifyMode: ['pet', 'system', 'both'].includes(data.notifyMode) ? data.notifyMode : 'pet',
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function writeSettings(ctx, value) {
|
|
90
|
+
const input = value && typeof value === 'object' ? value : {};
|
|
91
|
+
const rawInterval = Number(input.notifyInterval);
|
|
92
|
+
const next = {
|
|
93
|
+
agentMailAccess: input.agentMailAccess === true,
|
|
94
|
+
notifyEnabled: input.notifyEnabled !== false,
|
|
95
|
+
notifyInterval: Number.isFinite(rawInterval) ? Math.min(3600, Math.max(15, Math.round(rawInterval))) : 60,
|
|
96
|
+
notifyMode: ['pet', 'system', 'both'].includes(input.notifyMode) ? input.notifyMode : 'pet',
|
|
97
|
+
};
|
|
98
|
+
await writeData(ctx, SETTINGS_KEY, next);
|
|
99
|
+
return next;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Read a plain JSON payload record (kind 'grant') from the credential store, returning
|
|
103
|
+
// a fallback when it does not exist yet. Account-specific data lives under a
|
|
104
|
+
// key derived from the account id, so switching accounts never mixes data.
|
|
105
|
+
async function readData(ctx, key, fallback) {
|
|
106
|
+
try {
|
|
107
|
+
const record = await ctx.credentials.readRecord(key);
|
|
108
|
+
if (record && (record.kind === 'grant' || record.kind === 'data') && record.payload && typeof record.payload === 'object') {
|
|
109
|
+
return record.payload;
|
|
110
|
+
}
|
|
111
|
+
} catch {
|
|
112
|
+
// First use: the record simply does not exist.
|
|
113
|
+
}
|
|
114
|
+
return fallback;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function writeData(ctx, key, payload) {
|
|
118
|
+
await ctx.credentials.modifyRecord(key, async () => ({ kind: 'grant', payload }));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Contacts are stored locally only (per account in the credential store);
|
|
122
|
+
// they are never written to the IMAP server.
|
|
123
|
+
function publicAccount(id, payload) {
|
|
124
|
+
return {
|
|
125
|
+
id,
|
|
126
|
+
name: payload.name || payload.username,
|
|
127
|
+
username: payload.username,
|
|
128
|
+
imapHost: payload.imapHost,
|
|
129
|
+
imapPort: payload.imapPort,
|
|
130
|
+
smtpHost: payload.smtpHost,
|
|
131
|
+
smtpPort: payload.smtpPort,
|
|
132
|
+
imapTls: payload.imapTls !== false,
|
|
133
|
+
smtpTls: payload.smtpTls !== false,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function listAccounts(ctx) {
|
|
138
|
+
const entries = await ctx.credentials.listRecords();
|
|
139
|
+
const accounts = [];
|
|
140
|
+
for (const entry of entries) {
|
|
141
|
+
const key = String(entry.key);
|
|
142
|
+
if (!key.startsWith('mail/')) continue;
|
|
143
|
+
const id = key.slice(5);
|
|
144
|
+
const record = await ctx.credentials.readRecord(key);
|
|
145
|
+
if (!record || record.kind !== 'grant' || typeof record.payload !== 'object' || record.payload === null) continue;
|
|
146
|
+
accounts.push(publicAccount(id, record.payload));
|
|
147
|
+
}
|
|
148
|
+
return accounts.sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function getAccountPayload(ctx, id) {
|
|
152
|
+
const record = await ctx.credentials.readRecord(recordKey(id));
|
|
153
|
+
if (!record || record.kind !== 'grant' || typeof record.payload !== 'object' || record.payload === null) {
|
|
154
|
+
throw new Error('account not found: ' + id);
|
|
155
|
+
}
|
|
156
|
+
return record.payload;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function bridgeAccount(payload) {
|
|
160
|
+
return {
|
|
161
|
+
username: payload.username,
|
|
162
|
+
authCode: payload.authCode,
|
|
163
|
+
imapHost: payload.imapHost,
|
|
164
|
+
imapPort: Number(payload.imapPort) || 993,
|
|
165
|
+
smtpHost: payload.smtpHost,
|
|
166
|
+
smtpPort: Number(payload.smtpPort) || 465,
|
|
167
|
+
imapTls: payload.imapTls !== false,
|
|
168
|
+
smtpTls: payload.smtpTls !== false,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function json(result, status = 200) {
|
|
173
|
+
return new Response(JSON.stringify(result), {
|
|
174
|
+
status,
|
|
175
|
+
headers: { 'content-type': 'application/json; charset=utf-8' },
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
// Mail translation.
|
|
181
|
+
//
|
|
182
|
+
// Translation reuses DSH's built-in `translator` service. That service comes
|
|
183
|
+
// from an opt-in experimental bundle, so it is NOT declared in `inject` (a
|
|
184
|
+
// hard dependency would leave the whole plugin PENDING on machines where the
|
|
185
|
+
// bundle is off). We probe it lazily and degrade to a clear error instead.
|
|
186
|
+
// Bing is the default provider — no login, no API key, no extra cost.
|
|
187
|
+
//
|
|
188
|
+
// The service caps a single request at 4000 UTF-16 code units. Mail bodies are
|
|
189
|
+
// routinely longer, so we split on line boundaries (keeping the newlines) and
|
|
190
|
+
// translate chunk by chunk, then stitch the translated chunks back together.
|
|
191
|
+
// ---------------------------------------------------------------------------
|
|
192
|
+
const TRANSLATION_CHUNK_CHARS = 3500; // headroom below the service's 4000 limit
|
|
193
|
+
|
|
194
|
+
function splitForTranslation(text, maxChars) {
|
|
195
|
+
if (text.length <= maxChars) return [text];
|
|
196
|
+
const chunks = [];
|
|
197
|
+
let current = '';
|
|
198
|
+
// Keep each line's trailing newline attached so joins restore the exact
|
|
199
|
+
// original line structure instead of collapsing blank lines.
|
|
200
|
+
const segments = text.split(/(?<=\n)/);
|
|
201
|
+
for (const segment of segments) {
|
|
202
|
+
if (!segment) continue;
|
|
203
|
+
if (segment.length > maxChars) {
|
|
204
|
+
// One very long line: hard-split it into code-unit-sized pieces.
|
|
205
|
+
if (current) { chunks.push(current); current = ''; }
|
|
206
|
+
for (let i = 0; i < segment.length; i += maxChars) {
|
|
207
|
+
chunks.push(segment.slice(i, i + maxChars));
|
|
208
|
+
}
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (current && current.length + segment.length > maxChars) {
|
|
212
|
+
chunks.push(current);
|
|
213
|
+
current = segment;
|
|
214
|
+
} else {
|
|
215
|
+
current += segment;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (current) chunks.push(current);
|
|
219
|
+
return chunks;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function getTranslator(ctx) {
|
|
223
|
+
// Optional service: NEVER declare `translator` in `inject` (that would hold
|
|
224
|
+
// this plugin PENDING whenever the experimental bundle is off), and NEVER
|
|
225
|
+
// read `ctx.translator` here — the Context proxy throws
|
|
226
|
+
// `cannot get property "translator" without inject` when it is not injected.
|
|
227
|
+
// ctx.get() reads without the inject requirement; the false-strict retry
|
|
228
|
+
// also finds a provider whose fiber is not currently ACTIVE.
|
|
229
|
+
if (typeof ctx.get !== 'function') return undefined;
|
|
230
|
+
try {
|
|
231
|
+
return ctx.get('translator') ?? ctx.get('translator', false);
|
|
232
|
+
} catch {
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function translateMailText(ctx, text, targetLanguage, signal) {
|
|
238
|
+
const translator = getTranslator(ctx);
|
|
239
|
+
if (!translator || typeof translator.translate !== 'function') {
|
|
240
|
+
const error = new Error('translation service unavailable');
|
|
241
|
+
error.code = 'TRANSLATION_UNAVAILABLE';
|
|
242
|
+
throw error;
|
|
243
|
+
}
|
|
244
|
+
const chunks = splitForTranslation(text, TRANSLATION_CHUNK_CHARS);
|
|
245
|
+
const results = [];
|
|
246
|
+
for (const chunk of chunks) {
|
|
247
|
+
if (!chunk) { results.push(''); continue; }
|
|
248
|
+
const spec = translator.resolve({
|
|
249
|
+
text: chunk,
|
|
250
|
+
targetLanguage,
|
|
251
|
+
sourceLanguage: 'auto',
|
|
252
|
+
});
|
|
253
|
+
results.push(await translator.translate(spec, signal));
|
|
254
|
+
}
|
|
255
|
+
return results.join('');
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function handleRequest(ctx, request) {
|
|
259
|
+
const url = new URL(request.url);
|
|
260
|
+
let body = {};
|
|
261
|
+
if (request.method === 'POST') {
|
|
262
|
+
try {
|
|
263
|
+
body = await request.json();
|
|
264
|
+
} catch {
|
|
265
|
+
return json({ ok: false, error: 'invalid JSON body' }, 400);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const op = body.op || url.searchParams.get('op');
|
|
269
|
+
try {
|
|
270
|
+
switch (op) {
|
|
271
|
+
case 'getSettings':
|
|
272
|
+
return json({ ok: true, settings: await readSettings(ctx) });
|
|
273
|
+
case 'setSettings':
|
|
274
|
+
return json({ ok: true, settings: await writeSettings(ctx, body.value) });
|
|
275
|
+
case 'listAccounts':
|
|
276
|
+
return json({ ok: true, accounts: await listAccounts(ctx) });
|
|
277
|
+
case 'saveAccount': {
|
|
278
|
+
const username = String(body.username || '').trim();
|
|
279
|
+
if (!username) return json({ ok: false, error: 'username is required' }, 400);
|
|
280
|
+
const authCode = String(body.authCode || '');
|
|
281
|
+
if (!authCode) return json({ ok: false, error: 'authCode is required' }, 400);
|
|
282
|
+
const id = body.id || accountId(username.toLowerCase());
|
|
283
|
+
const payload = {
|
|
284
|
+
name: String(body.name || username).trim(),
|
|
285
|
+
username,
|
|
286
|
+
authCode,
|
|
287
|
+
imapHost: String(body.imapHost || '').trim(),
|
|
288
|
+
imapPort: Number(body.imapPort) || 993,
|
|
289
|
+
smtpHost: String(body.smtpHost || '').trim(),
|
|
290
|
+
smtpPort: Number(body.smtpPort) || 465,
|
|
291
|
+
imapTls: body.imapTls !== false,
|
|
292
|
+
smtpTls: body.smtpTls !== false,
|
|
293
|
+
};
|
|
294
|
+
if (!payload.imapHost) return json({ ok: false, error: 'imapHost is required' }, 400);
|
|
295
|
+
if (!payload.smtpHost) return json({ ok: false, error: 'smtpHost is required' }, 400);
|
|
296
|
+
await ctx.credentials.modifyRecord(recordKey(id), async () => ({
|
|
297
|
+
kind: 'grant',
|
|
298
|
+
payload,
|
|
299
|
+
}));
|
|
300
|
+
return json({ ok: true, account: publicAccount(id, payload) });
|
|
301
|
+
}
|
|
302
|
+
case 'renameAccount': {
|
|
303
|
+
// The account label is user-chosen and local to this machine, so nothing
|
|
304
|
+
// is read from the mailbox or any online profile API.
|
|
305
|
+
const id = String(body.id || '');
|
|
306
|
+
const name = String(body.name || '').trim();
|
|
307
|
+
if (!id) return json({ ok: false, error: 'id is required' }, 400);
|
|
308
|
+
if (!name) return json({ ok: false, error: 'name is required' }, 400);
|
|
309
|
+
const payload = await getAccountPayload(ctx, id);
|
|
310
|
+
const next = Object.assign({}, payload, { name });
|
|
311
|
+
await ctx.credentials.modifyRecord(recordKey(id), async () => ({ kind: 'grant', payload: next }));
|
|
312
|
+
return json({ ok: true, account: publicAccount(id, next) });
|
|
313
|
+
}
|
|
314
|
+
case 'deleteAccount': {
|
|
315
|
+
const id = String(body.id || '');
|
|
316
|
+
if (!id) return json({ ok: false, error: 'id is required' }, 400);
|
|
317
|
+
await ctx.credentials.deleteRecord(recordKey(id));
|
|
318
|
+
return json({ ok: true });
|
|
319
|
+
}
|
|
320
|
+
case 'testAccount': {
|
|
321
|
+
const payload = await getAccountPayload(ctx, String(body.id || ''));
|
|
322
|
+
return json(await runBridge('test', { account: bridgeAccount(payload) }));
|
|
323
|
+
}
|
|
324
|
+
case 'listMessages': {
|
|
325
|
+
const payload = await getAccountPayload(ctx, String(body.id || ''));
|
|
326
|
+
return json(await runBridge('listMessages', {
|
|
327
|
+
account: bridgeAccount(payload),
|
|
328
|
+
folder: body.folder || 'INBOX',
|
|
329
|
+
limit: Number(body.limit) || 20,
|
|
330
|
+
}));
|
|
331
|
+
}
|
|
332
|
+
case 'getMessage': {
|
|
333
|
+
const payload = await getAccountPayload(ctx, String(body.id || ''));
|
|
334
|
+
return json(await runBridge('getMessage', {
|
|
335
|
+
account: bridgeAccount(payload),
|
|
336
|
+
uid: String(body.uid || ''),
|
|
337
|
+
folder: body.folder || 'INBOX',
|
|
338
|
+
}));
|
|
339
|
+
}
|
|
340
|
+
case 'getAttachment': {
|
|
341
|
+
const payload = await getAccountPayload(ctx, String(body.id || ''));
|
|
342
|
+
return json(await runBridge('getAttachment', {
|
|
343
|
+
account: bridgeAccount(payload),
|
|
344
|
+
uid: String(body.uid || ''),
|
|
345
|
+
folder: body.folder || 'INBOX',
|
|
346
|
+
index: Number(body.index) || 0,
|
|
347
|
+
}));
|
|
348
|
+
}
|
|
349
|
+
case 'sendMessage': {
|
|
350
|
+
const id = String(body.id || '');
|
|
351
|
+
const payload = await getAccountPayload(ctx, id);
|
|
352
|
+
const to = String(body.to || '').trim();
|
|
353
|
+
if (!to) return json({ ok: false, error: 'to is required' }, 400);
|
|
354
|
+
const attachments = Array.isArray(body.attachments) ? body.attachments : [];
|
|
355
|
+
// Guard the outbound path: each attachment arrives base64-encoded in the
|
|
356
|
+
// request body and is buffered in memory on both sides of the bridge.
|
|
357
|
+
let totalBytes = 0;
|
|
358
|
+
for (const att of attachments) {
|
|
359
|
+
const content = String((att && att.content) || '');
|
|
360
|
+
if (!content) continue;
|
|
361
|
+
totalBytes += Math.floor((content.length * 3) / 4);
|
|
362
|
+
}
|
|
363
|
+
if (totalBytes > 25 * 1024 * 1024) {
|
|
364
|
+
return json({ ok: false, error: '附件总大小超过 25 MB,请分开发送。' }, 400);
|
|
365
|
+
}
|
|
366
|
+
const result = await runBridge('sendMessage', {
|
|
367
|
+
account: bridgeAccount(payload),
|
|
368
|
+
to,
|
|
369
|
+
subject: String(body.subject || ''),
|
|
370
|
+
body: String(body.body || ''),
|
|
371
|
+
attachments,
|
|
372
|
+
});
|
|
373
|
+
if (result.ok) {
|
|
374
|
+
// Keep a local outbox record as an instant, offline-capable mirror of
|
|
375
|
+
// the IMAP Sent folder. The outbox is per-account (key includes id).
|
|
376
|
+
try {
|
|
377
|
+
const store = await readData(ctx, outboxKey(id), { sent: [] });
|
|
378
|
+
const list = Array.isArray(store.sent) ? store.sent : [];
|
|
379
|
+
list.unshift({
|
|
380
|
+
id: String(Date.now()) + '-' + Math.random().toString(36).slice(2, 8),
|
|
381
|
+
to,
|
|
382
|
+
subject: String(body.subject || ''),
|
|
383
|
+
body: String(body.body || ''),
|
|
384
|
+
date: new Date().toISOString(),
|
|
385
|
+
attachments: attachments.map(a => ({
|
|
386
|
+
name: String((a && a.name) || 'attachment'),
|
|
387
|
+
size: Math.floor((String((a && a.content) || '').length * 3) / 4),
|
|
388
|
+
mime: String((a && a.mime) || ''),
|
|
389
|
+
})),
|
|
390
|
+
});
|
|
391
|
+
await writeData(ctx, outboxKey(id), { sent: list.slice(0, 200) });
|
|
392
|
+
} catch {
|
|
393
|
+
// Local mirror must never fail an already-delivered message.
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return json(result);
|
|
397
|
+
}
|
|
398
|
+
case 'sentMessages': {
|
|
399
|
+
const id = String(body.id || '');
|
|
400
|
+
const payload = await getAccountPayload(ctx, id);
|
|
401
|
+
// Read Sent from the mail server so mails sent on other devices show up.
|
|
402
|
+
try {
|
|
403
|
+
const r = await runBridge('listSent', { account: bridgeAccount(payload), limit: 50 });
|
|
404
|
+
if (r && r.ok && Array.isArray(r.messages)) {
|
|
405
|
+
const sent = r.messages.map(m => ({
|
|
406
|
+
id: m.id || ((m.folder || '') + ':' + m.uid),
|
|
407
|
+
to: m.to || '',
|
|
408
|
+
subject: m.subject || '',
|
|
409
|
+
body: m.snippet || '',
|
|
410
|
+
date: m.date || '',
|
|
411
|
+
from: m.from || '',
|
|
412
|
+
uid: m.uid || '',
|
|
413
|
+
folder: m.folder || '',
|
|
414
|
+
}));
|
|
415
|
+
try { await writeData(ctx, outboxKey(id), { sent }); } catch {}
|
|
416
|
+
return json({ ok: true, sent });
|
|
417
|
+
}
|
|
418
|
+
} catch {
|
|
419
|
+
// Fall through to the local cache below.
|
|
420
|
+
}
|
|
421
|
+
const store = await readData(ctx, outboxKey(id), { sent: [] });
|
|
422
|
+
return json({ ok: true, sent: Array.isArray(store.sent) ? store.sent : [] });
|
|
423
|
+
}
|
|
424
|
+
case 'listContacts': {
|
|
425
|
+
const id = String(body.id || '');
|
|
426
|
+
const store = await readData(ctx, contactsKey(id), { contacts: [] });
|
|
427
|
+
return json({ ok: true, contacts: Array.isArray(store.contacts) ? store.contacts : [] });
|
|
428
|
+
}
|
|
429
|
+
case 'saveContact': {
|
|
430
|
+
const id = String(body.id || '');
|
|
431
|
+
const email = String(body.email || '').trim().toLowerCase();
|
|
432
|
+
if (!email || !email.includes('@')) return json({ ok: false, error: 'valid email is required' }, 400);
|
|
433
|
+
const emailLower = c => String(c.email || '').toLowerCase();
|
|
434
|
+
const store = await readData(ctx, contactsKey(id), { contacts: [] });
|
|
435
|
+
const list = Array.isArray(store.contacts) ? store.contacts.slice() : [];
|
|
436
|
+
const existing = list.find(c => emailLower(c) === email);
|
|
437
|
+
if (existing) existing.name = String(body.name || existing.name || '');
|
|
438
|
+
else list.push({ email, name: String(body.name || '') });
|
|
439
|
+
list.sort((a, b) => String(a.name || a.email).localeCompare(String(b.name || b.email)));
|
|
440
|
+
await writeData(ctx, contactsKey(id), { contacts: list });
|
|
441
|
+
return json({ ok: true, contacts: list });
|
|
442
|
+
}
|
|
443
|
+
case 'deleteContact': {
|
|
444
|
+
const id = String(body.id || '');
|
|
445
|
+
const email = String(body.email || '').trim().toLowerCase();
|
|
446
|
+
const store = await readData(ctx, contactsKey(id), { contacts: [] });
|
|
447
|
+
const list = (Array.isArray(store.contacts) ? store.contacts : [])
|
|
448
|
+
.filter(c => String(c.email || '').toLowerCase() !== email);
|
|
449
|
+
await writeData(ctx, contactsKey(id), { contacts: list });
|
|
450
|
+
return json({ ok: true, contacts: list });
|
|
451
|
+
}
|
|
452
|
+
case 'translate': {
|
|
453
|
+
const text = typeof body.text === 'string' ? body.text : '';
|
|
454
|
+
if (!text.trim()) {
|
|
455
|
+
return json({ ok: false, error: 'text is required' }, 400);
|
|
456
|
+
}
|
|
457
|
+
const targetLanguage =
|
|
458
|
+
typeof body.targetLanguage === 'string' && body.targetLanguage.trim()
|
|
459
|
+
? body.targetLanguage.trim()
|
|
460
|
+
: 'zh-CN';
|
|
461
|
+
try {
|
|
462
|
+
const translated = await translateMailText(ctx, text, targetLanguage, request.signal);
|
|
463
|
+
return json({ ok: true, text: translated });
|
|
464
|
+
} catch (error) {
|
|
465
|
+
const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;
|
|
466
|
+
const status = code === 'TRANSLATION_UNAVAILABLE' ? 503 : 502;
|
|
467
|
+
return json({
|
|
468
|
+
ok: false,
|
|
469
|
+
error: error instanceof Error ? error.message : String(error),
|
|
470
|
+
...(code ? { code } : {}),
|
|
471
|
+
}, status);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
default:
|
|
475
|
+
return json({ ok: false, error: 'unknown op: ' + op }, 400);
|
|
476
|
+
}
|
|
477
|
+
} catch (error) {
|
|
478
|
+
return json({ ok: false, error: error instanceof Error ? error.message : String(error) }, 500);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
export function apply(ctx) {
|
|
483
|
+
ctx.effect(() => ctx.connection.fetch.register({
|
|
484
|
+
path: API,
|
|
485
|
+
methods: ['POST'],
|
|
486
|
+
requestBody: 'buffered',
|
|
487
|
+
fetch: (request) => handleRequest(ctx, request),
|
|
488
|
+
}), 'dsh-mail: fetch route');
|
|
489
|
+
|
|
490
|
+
// Read-only mailbox tool for the AI assistant. The tool itself checks the
|
|
491
|
+
// `agentMailAccess` setting on every call, so turning the switch off revokes
|
|
492
|
+
// access immediately without reloading the plugin.
|
|
493
|
+
ctx.effect(() => ctx.tools.register(mailQueryTool(
|
|
494
|
+
ctx, handleRequest,
|
|
495
|
+
async () => (await readSettings(ctx)).agentMailAccess === true
|
|
496
|
+
)), 'dsh-mail: mail_query tool');
|
|
497
|
+
}
|