feat: unify SMTP and optional IMAP account settings
This commit is contained in:
1 parent
39afafefa7
commit
7104b6745c
8 files changed
+56
-14
No files matched your search
@@ -0,0 +1,13 @@
|
||||
'use strict';
|
||||
const providers={'163.com':['smtp.163.com','imap.163.com'],'126.com':['smtp.126.com','imap.126.com'],'qq.com':['smtp.qq.com','imap.qq.com'],'foxmail.com':['smtp.qq.com','imap.qq.com'],'yeah.net':['smtp.yeah.net','imap.yeah.net']};
|
||||
function expandAccount(input,old,address){
|
||||
const preset=providers[address.split('@')[1]];const shared=Object.hasOwn(input,'password');
|
||||
const result={...input,senders:input.senders??old?.senders??[],enabled:input.enabled??old?.enabled??false};
|
||||
for(const [index,kind] of ['smtp','imap'].entries()){
|
||||
const previous=old?.[kind],given=input[kind]||{};
|
||||
result[kind]={host:previous?.host||preset?.[index]||'',port:previous?.port||(kind==='smtp'?465:993),security:previous?.security||'tls',user:previous?.user||address,...given};
|
||||
result[kind].password=given.password!==undefined&&given.password!==''?given.password:shared?input.password:(given.password??'');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
module.exports={expandAccount};
|
||||
@@ -22,12 +22,12 @@ class MailService{
|
||||
});}
|
||||
async withImap(config,work){const client=this.imapFactory(config);client.on?.('error',()=>{});this.clients.add(client);try{await client.connect();return await work(client);}finally{try{await client.logout();}catch{}client.close?.();this.clients.delete(client);}}
|
||||
history(id,input){return this.exclusive(id,async()=>{
|
||||
const config=this.store.channelSecret(id);
|
||||
const config=this.store.channelSecret(id);if(config.receiveEnabled===false)fail('此邮箱未启用 IMAP 收信。',409);
|
||||
try{const result=await this.withImap(config.imap,client=>require('./history.cjs').readHistory(client,input));this.store.guard(id,config.version);return result;}
|
||||
catch(error){if([400,404,409,413].includes(error.status))throw error;fail(safeError(error,'IMAP'));}
|
||||
});}
|
||||
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱仅支持查询已发送邮件。',409);let smtp=false,imap=false,message='SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能收取模板。',409);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
|
||||
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱仅支持查询已发送邮件。',409);let smtp=false,imap=false,message=c.receiveEnabled===false?'SMTP 连接正常(IMAP 未启用)':'SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}if(c.receiveEnabled!==false)try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能收取模板。',409);if(c.receiveEnabled===false)fail('此邮箱未启用 IMAP 收信。',409);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
|
||||
await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});try{const epoch=String(client.mailbox.uidValidity),cursor=this.store.cursor(id);const sameEpoch=cursor.epoch===epoch;const last=sameEpoch?(cursor.uid||0):0;const query={since:new Date(sameEpoch&&cursor.since?cursor.since:Date.now()-7*86400000),...(last?{uid:(last+1)+':*'}:{})};const found=await client.search(query,{uid:true});const uids=(found||[]).filter(uid=>uid>last).sort((a,b)=>a-b).slice(0,50);
|
||||
for(const uid of uids){if(this.stopped)break;this.store.guard(id,c.version);const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
|
||||
if(!/^\[模板\]/.test((info.envelope?.subject||'').trim())){this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,uid);});continue;}
|
||||
@@ -42,7 +42,7 @@ class MailService{
|
||||
this.store.setState(id,c.version,{imap:true,pollAt:new Date().toISOString(),message:`收信完成:新增 ${imported} 个模板,${rejected} 封未导入`});return {imported,rejected};
|
||||
}catch(error){if(error.status===409)throw error;const message=safeError(error,'IMAP');try{this.store.setState(id,c.version,{imap:false,pollAt:new Date().toISOString(),message});}catch{}fail(message);}});}
|
||||
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST','类别名称':'测试通知','订单明细':'订单号:TEST 机芯号:CORE 产品型号:MODEL 客户简称:示例 出货方式:CBU 总数量:1','存放地址':'示例归档目录(测试数据)'};const rendered=require('./content.cjs').appendSignature(renderTemplate(t,values),{...c.signature,channelId:c.id,version:c.version});const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
|
||||
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.receiveEnabled!==false&&c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);clearTimeout(this.startTimer);for(const client of this.clients)try{client.close?.();}catch{}await Promise.allSettled([...this.running.values()]);}
|
||||
}
|
||||
module.exports={MailService};
|
||||
@@ -32,19 +32,23 @@ class MailStore{
|
||||
encode(id,value){try{return this.vault.encode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
|
||||
decode(id,value){try{return this.vault.decode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
|
||||
row(id){const row=this.db.prepare('SELECT * FROM channels WHERE id=?').get(id);if(!row)fail('邮箱不存在。',404);return row;}
|
||||
channelSecret(id){const row=this.row(id);return {...this.decode(id,row.payload),id,version:row.version};}
|
||||
publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp?.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap.password},state};}
|
||||
channelSecret(id){const row=this.row(id);return {receiveEnabled:true,...this.decode(id,row.payload),id,version:row.version};}
|
||||
publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp?.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap?.password},state};}
|
||||
channels(){return this.db.prepare('SELECT id FROM channels ORDER BY rowid').all().map(r=>this.publicChannel(r.id));}
|
||||
saveChannel(input){return this.transaction(()=>{
|
||||
if(!input||typeof input!=='object')fail('邮箱配置无效。');const old=input.id?this.channelSecret(input.id):null;if(old&&old.version!==input.version)fail('邮箱已被修改,请刷新后重试。',409);
|
||||
const id=old?.id||crypto.randomUUID(),address=email(input.email);const existing=this.db.prepare('SELECT id FROM channels WHERE email=?').get(address);if(existing&&existing.id!==id)fail('此邮箱已托管,请使用已有邮箱。',409);
|
||||
if(input.enabled!==undefined&&typeof input.enabled!=='boolean')fail('模板收信开关必须是布尔值。');
|
||||
const readOnly=input.readOnly===true;
|
||||
if(!readOnly&&(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100))fail('请填写模板发件人名单,并选择是否启用收信。');
|
||||
const receiveEnabled=input.receiveEnabled===undefined?(old?.receiveEnabled??true):input.receiveEnabled;if(typeof receiveEnabled!=='boolean')fail('请选择是否启用 IMAP 收信。');
|
||||
input=require('./account-config.cjs').expandAccount(input,old,address);
|
||||
const enabled=!readOnly&&receiveEnabled&&input.enabled===true;
|
||||
if(!readOnly&&(!Array.isArray(input.senders)||input.senders.length>100||(enabled&&!input.senders.length)))fail('请填写模板发件人名单,并选择是否启用收信。');
|
||||
const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind]?.password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
|
||||
const saved={name:text(input.name,'邮箱名称',80),email:address,readOnly,smtp:readOnly?{}:endpoint('smtp'),imap:endpoint('imap'),senders:readOnly?[]:[...new Set(input.senders.map(email))],enabled:readOnly?false:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
|
||||
const saved={name:text(input.name,'邮箱名称',80),email:address,readOnly,receiveEnabled,smtp:readOnly?{}:endpoint('smtp'),imap:receiveEnabled?endpoint('imap'):(old?.imap||{}),senders:readOnly?[]:[...new Set(input.senders.map(email))],enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
|
||||
if(input.signature!==undefined)saved.signature=require('./content.cjs').normalizeSignature(input.signature);else if(old?.signature)saved.signature=old.signature;
|
||||
const reset=!old||old.email!==address||JSON.stringify(old.imap)!==JSON.stringify(saved.imap);const oldrow=old?this.row(id):null;
|
||||
const changed=reset||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
|
||||
const changed=reset||old?.receiveEnabled!==receiveEnabled||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
|
||||
this.db.prepare('INSERT INTO channels VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET email=excluded.email,version=excluded.version,payload=excluded.payload,state=excluded.state,cursor=excluded.cursor').run(id,address,(old?.version||0)+1,this.encode(id,saved),JSON.stringify(state),reset?'{}':oldrow.cursor);return this.publicChannel(id);
|
||||
});}
|
||||
guard(id,version){if(this.row(id).version!==version)fail('邮箱配置已变化,请重试。',409);}
|
||||
|
||||
Reference in new issue
Block a user