refactor: organize source web and tests by business module

This commit is contained in:
abaishu0730 committed 2026-10-19 08:45:51 +08:00
1 parent 9854d2d5c2
commit 2aed328774
113 files changed
+189 -183

No files matched your search

-76
View File
@@ -1,76 +0,0 @@
'use strict';
const fs=require('node:fs/promises');const path=require('node:path');
const {SmbClient,segments,inside}=require('./storage-files.cjs');
const {orderFolder}=require('./storage-order.cjs');
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
const safe=e=>e.status?e:fail(({ENOENT:'找不到文件或归档目录,请检查路径。',EACCES:'没有共享目录访问权限。',EPERM:'没有共享目录操作权限。',ENOSPC:'存储服务器空间不足。',ENOTDIR:'指定路径不是目录。'})[e.code]||'存储操作未完成,请检查服务器与网络。',502);
class StorageService{
constructor({store,jobs,outputDir,client=new SmbClient(),checkTimeoutMs=15000}){this.store=store;this.jobs=jobs;this.outputDir=outputDir;this.client=client;this.running=new Map();this.pendingChecks=new Set();this.probeControllers=new Set();this.checkTimeoutMs=checkTimeoutMs;this.stopped=false;}
busy(id){return this.running.has(id);}
async saveServer(input){
if(this.stopped)throw fail('存储服务正在停止。',503);
const snapshot=structuredClone(input),{changed}=this.store.prepareServer(snapshot);
if(snapshot.id&&this.busy(snapshot.id))throw fail('此服务器正在执行操作,请稍后保存。',409);
const readState=changed?await this.checkConnection(snapshot):null;
if(this.stopped)throw fail('存储服务正在停止。',503);
if(snapshot.id&&this.busy(snapshot.id))throw fail('此服务器正在执行操作,请稍后保存。',409);
return this.store.saveServer(snapshot,readState);
}
async probe(saved,{signal}={}){
if(this.stopped)throw fail('存储服务正在停止。',503);
const controller=new AbortController();const cancel=()=>controller.abort(signal.reason?.status?signal.reason:fail('已取消连接操作。',499));
if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true});
const timer=setTimeout(()=>controller.abort(fail('连接超时,请检查服务器地址、网络及共享权限后重试。',504)),this.checkTimeoutMs);
const task=(async()=>{let onAbort,work;
try{return await Promise.race([
new Promise((resolve,reject)=>{onAbort=()=>reject(controller.signal.reason);if(controller.signal.aborted)onAbort();else controller.signal.addEventListener('abort',onAbort,{once:true});}),
work=(async()=>{if(controller.signal.aborted)throw controller.signal.reason;
if(this.client.browse)return await this.client.browse(saved,{signal:controller.signal});
const area=await this.client.area(saved),listing=await area.list('');return {serverRoot:false,readable:true,entries:listing.entries.filter(e=>e.type==='directory'),truncated:listing.truncated};
})()
]);}catch(error){throw safe(error);}finally{if(controller.signal.aborted&&this.client.browse&&work){let cleanup;await Promise.race([work.catch(()=>{}),new Promise(resolve=>{cleanup=setTimeout(resolve,1800);})]);clearTimeout(cleanup);}clearTimeout(timer);signal?.removeEventListener('abort',cancel);if(onAbort)controller.signal.removeEventListener('abort',onAbort);this.probeControllers.delete(controller);}
})();
this.pendingChecks.add(task);this.probeControllers.add(controller);try{return await task;}finally{this.pendingChecks.delete(task);this.probeControllers.delete(controller);}
}
async browseConnection(input,options){
const {saved}=this.store.prepareServer(input,{allowServerRoot:true});return this.probe(saved,options);
}
async checkConnection(input,options){
const {saved}=this.store.prepareServer(input,{allowServerRoot:true});const result=await this.probe(saved,options);
if(!saved.share)return {...result,readable:false,serverRoot:true,message:'已连接服务器,请浏览并选择一个共享目录。'};
return {...result,readable:true,checkedAt:new Date().toISOString(),message:'连接成功,目标目录可读取。'};
}
saveSettings(input){if(input?.enabled){const server=this.store.publicServer(input.serverId);if(!server.enabled||!server.state.readable||!server.state.writable)throw fail('请先启用服务器并检查读写成功。',409);}return this.store.saveSettings(input);}
run(id,work){
if(this.stopped)return Promise.reject(fail('存储服务正在停止。',503));
const previous=this.running.get(id)||Promise.resolve();
const task=previous.catch(()=>{}).then(async()=>{const server=this.store.secret(id);if(!server.enabled)throw fail('此存储服务器已停用。',409);try{return await work(server);}catch(e){throw safe(e);}});
this.running.set(id,task);task.finally(()=>{if(this.running.get(id)===task)this.running.delete(id);}).catch(()=>{});return task;
}
check(id){return this.run(id,async server=>{try{const area=await this.client.area(server),result=await area.check();const state={...result,checkedAt:new Date().toISOString(),message:'共享目录读写正常'};this.store.setState(id,server.version,state);return this.store.publicServer(id);}catch(e){const error=safe(e);this.store.setState(id,server.version,{readable:false,writable:false,checkedAt:new Date().toISOString(),message:error.message});throw error;}});}
list(id,relative){return this.run(id,async server=>(await this.client.area(server)).list(relative));}
mkdir(id,relative){return this.run(id,async server=>(await this.client.area(server)).mkdir(relative));}
readPdf(id,relative){return this.run(id,async server=>(await this.client.area(server)).readPdf(relative));}
previewInfo(id,relative){return this.run(id,async server=>(await this.client.area(server)).previewInfo(relative));}
readPreview(id,relative){return this.run(id,async server=>(await this.client.area(server)).readPreview(relative));}
readFile(id,relative){return this.run(id,async server=>(await this.client.area(server)).readFile(relative));}
archive(id,jobId,directory='',actor='自动归档'){
return this.run(id,async server=>{
segments(directory);if(typeof jobId!=='string'||!jobId||jobId.length>200)throw fail('请选择已完成的 PDF 导出任务。');
const job=this.jobs.jobs().find(j=>j.jobId===jobId);if(!job||job.status!=='success'||typeof job.path!=='string')throw fail('请选择已完成且存在的 PDF。');
const record=this.store.beginArchive(id,jobId,actor,directory);
try{
const [root,file]=await Promise.all([fs.realpath(this.outputDir),fs.realpath(job.path)]);
if(!inside(root,file)||file===root||path.extname(file).toLowerCase()!=='.pdf')throw fail('PDF 不在本工具输出目录内。');
const grouping=orderFolder(job),base=segments(directory),current=base.at(-1)||segments(server.directory).at(-1);
const target=(current===grouping.orderFolder?base:[...base,grouping.orderFolder]).join('/');segments(target);
const area=await this.client.area(server),result=await area.archive(file,path.basename(file),target);
return this.store.finishArchive(record.id,'success',{...result,...grouping,baseDirectory:directory,directory:target,serverName:server.name});
}
catch(e){const error=safe(e);this.store.finishArchive(record.id,'error',{error:error.message,serverName:server.name});throw error;}
});
}
async automatic(job){const settings=this.store.settings();if(!settings.enabled||job.status!=='success'||!job.createdAt||job.createdAt<settings.since)return null;return this.archive(settings.serverId,job.jobId,'','自动归档');}
async stop(){this.stopped=true;for(const controller of this.probeControllers)controller.abort(fail('存储服务正在停止。',503));await Promise.allSettled([...this.running.values(),...this.pendingChecks]);}
}
module.exports={StorageService};