dsh-skillpie-mail 0.1.0 → 0.1.2

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/lib/imap.js CHANGED
@@ -226,9 +226,11 @@ function decodeEncodedWord(word) {
226
226
  export function decodeHeaderValue(value) {
227
227
  if (value == null) return ''
228
228
  let s = value.replace(/\r?\n[ \t]+/g, ' ') // 折行展开
229
- if (/=[\s\S]*\?/.test(s)) s = s.replace(/=\?[^?]+\?[BbQq]\?[\s\S]*?\?=/g, decodeEncodedWord)
230
- // 剩余裸 8bit(非 ASCII)按字节还原(GBK 链优先,兼容发件方不标编码)
231
- if (/[^\x00-\x7F]/.test(s) && !s.includes('\uFFFD')) {
229
+ const hadEncodedWords = /=\?[^?]+\?[BbQq]\?/.test(s)
230
+ if (hadEncodedWords) s = s.replace(/=\?[^?]+\?[BbQq]\?[\s\S]*?\?=/g, decodeEncodedWord)
231
+ // 裸 8bit 兜底只在没有 encoded-word 时做:展开后已是正常 Unicode,
232
+ // 再按 latin1→GBK 链重解会把正确的中文二次搅成乱码
233
+ if (!hadEncodedWords && /[^\x00-\x7F]/.test(s) && !s.includes('\uFFFD')) {
232
234
  try {
233
235
  const buf = Buffer.from(s, 'latin1')
234
236
  for (const enc of ['utf-8', 'gbk', 'gb18030', 'big5']) {
@@ -294,7 +296,7 @@ export function extractText(rawBuf, maxLength = 800, preferHtml = false) {
294
296
  const sep = rawBuf.indexOf('\r\n\r\n')
295
297
  const headerBlock = rawBuf.subarray(0, sep < 0 ? 0 : sep).toString('latin1')
296
298
  const bodyBuf = sep < 0 ? rawBuf : rawBuf.subarray(sep + 4)
297
- const walk = (buf, ct) => {
299
+ const walk = (buf, ct, headers) => {
298
300
  if (ct.type.startsWith('multipart/') && ct.boundary) {
299
301
  const b = '--' + ct.boundary
300
302
  const parts = []
@@ -310,12 +312,13 @@ export function extractText(rawBuf, maxLength = 800, preferHtml = false) {
310
312
  if (psep < 0) continue
311
313
  const ph = part.subarray(0, psep).toString('latin1')
312
314
  const pct = contentTypeOf(ph)
313
- const text = walk(part.subarray(psep + 4), pct)
315
+ const text = walk(part.subarray(psep + 4), pct, ph)
314
316
  if (text) return text
315
317
  }
316
318
  return ''
317
319
  }
318
- const cte = (getHeader(buf.toString('latin1', 0, Math.min(buf.length, 4096)), 'Content-Transfer-Encoding') || '').trim()
320
+ // 非多部件邮件的传输编码在顶层头里;多部件则在部件头里
321
+ const cte = (getHeader(headers || buf.toString('latin1', 0, Math.min(buf.length, 4096)), 'Content-Transfer-Encoding') || '').trim()
319
322
  const text = decodeBodyText(buf, cte, ct.charset)
320
323
  if (ct.type === 'text/plain' || ct.type === 'text/html' || !ct.type) {
321
324
  if (ct.type === 'text/html') return preferHtml ? sanitizeHtml(text) : text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
@@ -323,7 +326,7 @@ export function extractText(rawBuf, maxLength = 800, preferHtml = false) {
323
326
  }
324
327
  return ''
325
328
  }
326
- const text = walk(bodyBuf, contentTypeOf(headerBlock)) || (preferHtml ? '' : bodyBuf.toString('utf-8'))
329
+ const text = walk(bodyBuf, contentTypeOf(headerBlock), headerBlock) || (preferHtml ? '' : bodyBuf.toString('utf-8'))
327
330
  return text.length > maxLength ? text.slice(0, maxLength) + '…' : text
328
331
  }
329
332
 
@@ -377,7 +380,7 @@ export function extractHtml(rawBuf, maxLength = 20000) {
377
380
  const headerBlock = rawBuf.subarray(0, sep < 0 ? 0 : sep).toString('latin1')
378
381
  const bodyBuf = sep < 0 ? rawBuf : rawBuf.subarray(sep + 4)
379
382
  let found = ''
380
- const walk = (buf, ct) => {
383
+ const walk = (buf, ct, headers) => {
381
384
  if (found) return
382
385
  if (ct.type.startsWith('multipart/') && ct.boundary) {
383
386
  const b = '--' + ct.boundary
@@ -387,16 +390,21 @@ export function extractHtml(rawBuf, maxLength = 20000) {
387
390
  if (next < 0) break
388
391
  const part = buf.subarray(idx + b.length, next)
389
392
  const psep = part.indexOf('\r\n\r\n')
390
- if (psep >= 0) walk(part.subarray(psep + 4), contentTypeOf(part.subarray(0, psep).toString('latin1')))
393
+ if (psep >= 0) {
394
+ const partHeaders = part.subarray(0, psep).toString('latin1')
395
+ walk(part.subarray(psep + 4), contentTypeOf(partHeaders), partHeaders)
396
+ }
391
397
  idx = next
392
398
  }
393
399
  return
394
400
  }
395
401
  if (ct.type !== 'text/html') return
396
- const cte = (getHeader(buf.toString('latin1', 0, Math.min(buf.length, 4096)), 'Content-Transfer-Encoding') || '').trim()
402
+ // 非多部件邮件的传输编码在顶层头里;多部件则在部件头里
403
+ const cte = (getHeader(headers, 'Content-Transfer-Encoding') || '').trim()
397
404
  found = sanitizeHtml(decodeBodyText(buf, cte, ct.charset))
398
405
  }
399
- walk(bodyBuf, contentTypeOf(headerBlock))
406
+ const topHeaders = headerBlock
407
+ walk(bodyBuf, contentTypeOf(topHeaders), topHeaders)
400
408
  return found.length > maxLength ? found.slice(0, maxLength) + '…' : found
401
409
  }
402
410
 
@@ -406,28 +414,37 @@ export function extractHtml(rawBuf, maxLength = 20000) {
406
414
  * 检查邮箱自 lastUid 以来的新邮件。
407
415
  * @returns {Promise<{messages: Array<{uid, folder, from, to, subject, date, text, html}>, lastUid}>}
408
416
  */
409
- export async function fetchNewMail({ host, port, user, password, folders = ['INBOX'], lastUid = 0 }) {
417
+ export async function fetchNewMail({ host, port, user, password, folders = ['INBOX'], lastUid = 0, lastUidByFolder = null, lastTimeByFolder = null }) {
410
418
  const client = new ImapClient({ host, port, user, password })
411
419
  await client.connect()
412
420
  try {
413
421
  const messages = []
414
- let maxUid = lastUid
422
+ const marks = {} // 各文件夹独立水位(UID 序列互不相干)
423
+ const times = {} // 各文件夹独立时间水位(收件时间)
415
424
  for (const folder of folders) {
425
+ const base = Math.max(lastUidByFolder?.[folder] ?? 0, lastUid) // 兼容旧水位
426
+ const timeFloor = Date.parse(lastTimeByFolder?.[folder] ?? '') || 0 // 时间兜底:UID 回退(文件夹重建等)时靠收件时间过滤
416
427
  await client.select(folder)
417
- const uids = await client.searchUids(lastUid + 1)
418
- const fresh = uids.filter((u) => u > lastUid)
428
+ const uids = await client.searchUids(base + 1)
429
+ const fresh = uids.filter((u) => u > base)
430
+ let newestTs = 0
419
431
  for (const uid of fresh) {
420
432
  const lines = await client.command('UID', 'FETCH', String(uid), '(BODY.PEEK[])')
421
433
  for (const l of lines) {
422
434
  const m = /\x00LIT\x00([\s\S]*)\x00END\x00/.exec(l)
423
435
  if (!m) continue
424
436
  const parsed = parseMail(Buffer.from(m[1], 'utf-8'))
437
+ const ts = Date.parse(parsed.date || '') || 0
438
+ if (timeFloor && ts && ts <= timeFloor) continue // 早于水位时间的旧信跳过(只记 UID 不推送)
425
439
  messages.push({ uid, folder, ...parsed })
426
- if (uid > maxUid) maxUid = uid
440
+ if (ts > newestTs) newestTs = ts
427
441
  }
442
+ if (uid > (marks[folder] ?? 0)) marks[folder] = uid
428
443
  }
444
+ if (!(marks[folder] > base)) marks[folder] = base
445
+ times[folder] = timeFloor && !newestTs ? new Date(timeFloor).toISOString() : (newestTs ? new Date(newestTs).toISOString() : (lastTimeByFolder?.[folder] ?? ''))
429
446
  }
430
- return { messages, lastUid: maxUid }
447
+ return { messages, lastUidByFolder: marks, lastTimeByFolder: times, lastUid: Math.max(...Object.values(marks), lastUid) }
431
448
  } finally {
432
449
  await client.logout().catch(() => {})
433
450
  }
package/lib/index.js CHANGED
@@ -108,6 +108,26 @@ async function dispatch(store, cfg, body) {
108
108
  case 'list': {
109
109
  return { ok: true, mailboxes: await store.list() }
110
110
  }
111
+ case 'addOrRegister': {
112
+ // 合并入口:有应用密码先按已有邮箱验证添加;不通过/没填则自动注册
113
+ const username = String(body.username || '').trim().toLowerCase()
114
+ const note = String(body.note || '')
115
+ const password = String(body.password || '')
116
+ if (!/^[a-z0-9][a-z0-9._-]{2,30}$/.test(username)) {
117
+ return { ok: false, error: '用户名格式不对(3-31位小写字母/数字/._-)' }
118
+ }
119
+ if (password) {
120
+ try {
121
+ const email = username.includes('@') ? username : username + '@skillpie.cn'
122
+ await verifyImap(cfg.imapHost, cfg.imapPort, email, password)
123
+ await store.add(email, password, note)
124
+ return { ok: true, mode: 'added', mailboxes: await store.list() }
125
+ } catch (e) { /* 登录失败→当新邮箱自动注册 */ }
126
+ }
127
+ const result = await registerMailbox(cfg.registerUrl, username, note)
128
+ await store.addFromRegister({ address: result.address, appPassword: result.appPassword, note })
129
+ return { ok: true, mode: 'registered', address: result.address, appPassword: result.appPassword, mailboxes: await store.list() }
130
+ }
111
131
  case 'add': {
112
132
  const email = String(body.email || '').trim().toLowerCase()
113
133
  const password = String(body.password || '')
@@ -127,9 +147,28 @@ async function dispatch(store, cfg, body) {
127
147
  await store.addFromRegister({ address: result.address, appPassword: result.appPassword, note })
128
148
  return { ok: true, address: result.address, appPassword: result.appPassword, mailboxes: await store.list() }
129
149
  }
150
+ case 'unread': {
151
+ return { ok: true, count: await store.unreadCount() }
152
+ }
153
+ case 'markAllRead': {
154
+ await store.markAllRead(String(body.email || ''))
155
+ return { ok: true }
156
+ }
157
+ case 'deleteMail': {
158
+ await store.deleteMail(String(body.id || ''))
159
+ return { ok: true }
160
+ }
161
+ case 'markRead': {
162
+ await store.markRead(String(body.id || ''))
163
+ return { ok: true }
164
+ }
130
165
  case 'history': {
131
166
  return { ok: true, messages: await store.history(String(body.email || '').trim().toLowerCase()) }
132
167
  }
168
+ case 'clearHistory': {
169
+ const remaining = await store.clearHistory(String(body.email || '').trim().toLowerCase())
170
+ return { ok: true, remaining }
171
+ }
133
172
  case 'poll': {
134
173
  const sinceSeq = Number(body.sinceSeq) || 0
135
174
  return { ok: true, notifications: store.takeNotifications(sinceSeq) }
@@ -161,8 +200,9 @@ export default {
161
200
  // store 由 credentials 注入填充; HTTP 路由不依赖它, 先注册保证 API 可用
162
201
  const holder = { store: null }
163
202
 
164
- ctx.inject(['credentials'], async (child) => {
165
- const credentials = await child.credentials
203
+ // 同步回调!async 回调会让宿主无法在插件停用时回收定时器,每次热重载泄漏一个轮询实例
204
+ ctx.inject(['credentials'], (child) => {
205
+ const credentials = child.credentials
166
206
  holder.store = new MailStore(credentials)
167
207
  const imapOpts = { host: cfg.imapHost, port: cfg.imapPort, folders }
168
208
  // 首轮立即拉一次,保证基线 lastUid(不推历史邮件:首轮只记水位)
package/lib/store.js CHANGED
@@ -25,7 +25,10 @@ export class MailStore {
25
25
  return {
26
26
  mailboxes: Array.isArray(payload.mailboxes) ? payload.mailboxes : [],
27
27
  lastUid: payload.lastUid ?? {},
28
+ lastUidByFolder: payload.lastUidByFolder ?? {},
29
+ lastTimeByFolder: payload.lastTimeByFolder ?? {},
28
30
  history: Array.isArray(payload.history) ? payload.history : [],
31
+ readIds: payload.readIds && typeof payload.readIds === 'object' ? payload.readIds : {},
29
32
  }
30
33
  }
31
34
 
@@ -72,20 +75,38 @@ export class MailStore {
72
75
  const fresh = []
73
76
  for (const box of state.mailboxes) {
74
77
  try {
78
+ // 水位按 (邮箱, 文件夹) 独立记:各文件夹 UID 序列独立,共用一个水位会漏新信
75
79
  const lastUid = state.lastUid[box.email] ?? 0
76
- const result = await fetchNewMail({ host, port, user: box.email, password: box.password, folders, lastUid })
80
+ const folderMarks = state.lastUidByFolder?.[box.email] ?? {}
81
+ const folderTimes = state.lastTimeByFolder?.[box.email] ?? {}
82
+ const result = await fetchNewMail({ host, port, user: box.email, password: box.password, folders, lastUidByFolder: folderMarks, lastTimeByFolder: folderTimes })
77
83
  if (!baseline) {
78
84
  for (const message of result.messages) {
79
85
  fresh.push({ email: box.email, ...message })
80
86
  }
81
87
  }
82
- if (result.lastUid > (state.lastUid[box.email] ?? 0)) state.lastUid[box.email] = result.lastUid
88
+ if (result.lastUidByFolder) {
89
+ state.lastUidByFolder = state.lastUidByFolder ?? {}
90
+ state.lastUidByFolder[box.email] = result.lastUidByFolder
91
+ state.lastTimeByFolder = state.lastTimeByFolder ?? {}
92
+ state.lastTimeByFolder[box.email] = result.lastTimeByFolder ?? state.lastTimeByFolder[box.email] ?? {}
93
+ } else if (result.lastUid > (state.lastUid[box.email] ?? 0)) {
94
+ state.lastUid[box.email] = result.lastUid // 兼容旧格式
95
+ }
83
96
  } catch (error) {
84
97
  // 单个邮箱失败不影响其它邮箱(密码错/网络断等)
85
98
  if (options.onBoxError) options.onBoxError(box.email, error)
86
99
  }
87
100
  }
88
- // 收件历史(持久,最新在前,截断;不存密码)
101
+ // 收件历史(持久,最新在前,截断;不存密码);按 id 去重防历史损坏期间/并发轮询造成的重复
102
+ {
103
+ const seen = new Set()
104
+ state.history = (state.history ?? []).filter((m) => {
105
+ if (!m?.id || seen.has(m.id)) return false
106
+ seen.add(m.id)
107
+ return true
108
+ })
109
+ }
89
110
  if (fresh.length) {
90
111
  for (const message of fresh) {
91
112
  state.history.unshift({
@@ -94,7 +115,7 @@ export class MailStore {
94
115
  from: message.from, to: message.to, subject: message.subject, date: message.date,
95
116
  text: (message.text || '').slice(0, 2000),
96
117
  html: sanitizeHtml(message.html || '', 8000),
97
- receivedAt: new Date().toISOString(),
118
+ receivedAt: (() => { const t = Date.parse(message.date || ''); return isNaN(t) ? new Date().toISOString() : new Date(t).toISOString() })(), // 优先邮件头 Date,解析失败才用本机时间
98
119
  })
99
120
  }
100
121
  if (state.history.length > MAX_HISTORY) state.history.length = MAX_HISTORY
@@ -114,9 +135,61 @@ export class MailStore {
114
135
 
115
136
  /** 收件历史(不含密码,最新在前)。 */
116
137
  async history(email = '') {
117
- const { history } = await this.#read()
138
+ const { history, readIds } = await this.#read()
118
139
  const list = email ? history.filter((m) => m.email === email) : history
119
- return list
140
+ return list.map((m) => ({ ...m, read: Boolean(readIds[m.id]) }))
141
+ }
142
+
143
+ /** 删除单封历史邮件(按 id)。返回是否删除。 */
144
+ async deleteMail(id) {
145
+ const target = String(id || '')
146
+ await this.credentials.modifyRecord(RECORD_ID, (current) => {
147
+ const payload = current?.payload ?? { mailboxes: [], lastUid: {}, history: [] }
148
+ payload.history = (payload.history || []).filter((m) => m.id !== target)
149
+ return { kind: 'grant', payload }
150
+ })
151
+ return true
152
+ }
153
+
154
+ /** 未读邮件总数(全部邮箱)。 */
155
+ async unreadCount() {
156
+ const { history, readIds } = await this.#read()
157
+ return history.filter((m) => !readIds[m.id]).length
158
+ }
159
+
160
+ /** 全部已读:email 指定邮箱则只标该邮箱。 */
161
+ async markAllRead(email = '') {
162
+ const target = (email || '').trim().toLowerCase()
163
+ await this.credentials.modifyRecord(RECORD_ID, (current) => {
164
+ const payload = current?.payload ?? { mailboxes: [], lastUid: {}, history: [] }
165
+ payload.readIds = payload.readIds || {}
166
+ for (const m of payload.history || []) {
167
+ if (!target || m.email === target) payload.readIds[m.id] = true
168
+ }
169
+ return { kind: 'grant', payload }
170
+ })
171
+ }
172
+
173
+ /** 标记邮件已读(按 history 条目 id)。 */
174
+ async markRead(id) {
175
+ await this.credentials.modifyRecord(RECORD_ID, (current) => {
176
+ const payload = current?.payload ?? { mailboxes: [], lastUid: {}, history: [] }
177
+ payload.readIds = payload.readIds || {}
178
+ payload.readIds[id] = true
179
+ return { kind: 'grant', payload } // 必须返回完整记录(含 kind),否则记录失效列表变空
180
+ })
181
+ }
182
+
183
+ /** 清空收件历史:email 指定邮箱则只清该邮箱,否则全清。返回剩余条数。 */
184
+ async clearHistory(email = '') {
185
+ const target = (email || '').trim().toLowerCase()
186
+ await this.credentials.modifyRecord(RECORD_ID, (current) => {
187
+ const payload = current?.payload ?? { mailboxes: [], lastUid: {}, history: [] }
188
+ const left = target ? (payload.history ?? []).filter((m) => m.email !== target) : []
189
+ return { kind: 'grant', payload: { ...payload, history: left } }
190
+ })
191
+ const { history } = await this.#read()
192
+ return { remaining: history.length }
120
193
  }
121
194
 
122
195
  /** 取走通知(客户端轮询)。sinceSeq 之后的消息。 */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-skillpie-mail",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "SkillPie邮箱:管理 @skillpie.cn 邮箱(快速注册/手动添加/移除),后台 IMAP 轮询,收到新邮件全局弹窗展示并注明收件邮箱。",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -24,7 +24,9 @@
24
24
  "locale/*.json",
25
25
  "cordis.patch.yml",
26
26
  "icon.svg",
27
- "README.md"
27
+ "README.md",
28
+ "docs",
29
+ "screenshots.json"
28
30
  ],
29
31
  "engines": {
30
32
  "node": ">=22.13",
@@ -45,4 +47,4 @@
45
47
  "publishConfig": {
46
48
  "access": "public"
47
49
  }
48
- }
50
+ }
@@ -0,0 +1,4 @@
1
+ [
2
+ "docs/screenshots/inbox.webp",
3
+ "docs/screenshots/add-mailbox.webp"
4
+ ]