feat(storage): browse SMB shares and bound connection checks

This commit is contained in:
阿白叔 committed 2026-10-17 17:47:22 +08:00
1 parent 8417b1dff8
commit a785fa73d4
15 files changed
+277 -39

No files matched your search

+39 -17
View File
@@ -12,36 +12,58 @@
const slash=String.fromCharCode(92),address=s.id?slash.repeat(2)+s.host+slash+s.share+(s.directory?slash+s.directory.split('/').join(slash):''):'';
const host=container.querySelector('#storage-editor'),mode=s.authMode||'credentials';
host.innerHTML=`<form class="card mb-3" id="storage-form"><div class="card-header"><h3 class="card-title">${s.id?'管理服务器':'添加服务器'}</h3></div><div class="card-body">
<div class="mb-3"><label class="form-label" for="storage-address">共享路径</label><input class="form-control" id="storage-address" value="${esc(address)}" placeholder="${esc(slash.repeat(2)+'服务器'+slash+'共享名称'+slash+'子目录')}" required maxlength="1800" autocomplete="off"><div class="form-hint">从文件资源管理器复制完整共享路径即可。</div></div>
<div class="mb-3"><label class="form-label" for="storage-address">共享路径</label><div class="d-flex gap-2"><input class="form-control" id="storage-address" value="${esc(address)}" placeholder="${esc(slash.repeat(2)+'服务器'+slash+'共享名称'+slash+'子目录')}" required maxlength="1800" autocomplete="off"><button class="btn" type="button" id="storage-directory-browse">浏览</button></div><div class="form-hint">可先输入服务器 IP / 主机名,点击浏览选择共享及目录;也可粘贴完整共享路径。</div></div>
<div class="mb-3"><label class="form-label" for="storage-auth">访问方式</label><select class="form-select" id="storage-auth"><option value="windows" ${mode==='windows'?'selected':''}>免填账号密码(使用 Windows 权限)</option><option value="credentials" ${mode==='credentials'?'selected':''}>指定账号</option></select><div class="form-hint">免填模式复用部署机已有 Windows 共享登录或服务账号权限,也适用于系统允许的免密共享。切换方式不会断开系统已有连接。</div></div>
<fieldset id="storage-credentials" class="row g-3 mb-3"><div class="col-md-6"><label class="form-label" for="storage-username">登录账号</label><input class="form-control" id="storage-username" value="${esc(s.username)}" maxlength="200" required autocomplete="off"></div><div class="col-md-6"><label class="form-label" for="storage-password">SMB 密码</label><input class="form-control" type="password" id="storage-password" maxlength="2048" autocomplete="new-password"><div class="form-hint">${s.id&&s.hasPassword?'留空保留现有密码;更换服务器、共享或账号时重新填写。':'密码加密保存在部署机。'}</div></div><div class="col-12"><label class="form-check"><input class="form-check-input" type="checkbox" id="storage-passwordless" ${s.passwordless?'checked':''}><span class="form-check-label">此账号无密码</span></label></div></fieldset>
<div class="mb-3"><label class="form-label" for="storage-name">服务器名称</label><input class="form-control" id="storage-name" value="${esc(s.name)}" maxlength="80" placeholder="可选,留空自动生成" autocomplete="off"></div>
<label class="form-check"><input class="form-check-input" type="checkbox" id="storage-active" ${s.enabled?'checked':''}><span class="form-check-label">启用服务器</span></label><div class="text-secondary mt-3" id="storage-connection-status" role="status">${s.id?'修改连接信息后需重新检查。':'请先检查连接,确认目录可读取后再保存。'}</div><div class="text-danger mt-3" id="storage-error" role="alert"></div></div><div class="card-footer btn-list"><button class="btn" type="button" id="storage-cancel">取消编辑</button><button class="btn ms-auto" type="button" id="storage-connection-check">检查连接</button><button class="btn btn-primary" type="submit" ${s.id?'':'disabled'}>保存服务器</button></div></form>`;
<div id="storage-directory-picker" class="mb-3" hidden></div><label class="form-check"><input class="form-check-input" type="checkbox" id="storage-active" ${s.enabled?'checked':''}><span class="form-check-label">启用服务器</span></label><div class="text-secondary mt-3" id="storage-connection-status" role="status">${s.id?'修改连接信息后需重新检查。':'请先检查连接,确认目录可读取后再保存。'}</div><div class="text-danger mt-3" id="storage-error" role="alert"></div></div><div class="card-footer btn-list"><button class="btn" type="button" id="storage-cancel">取消编辑</button><button class="btn ms-auto" type="button" id="storage-operation-cancel" hidden>取消操作</button><button class="btn" type="button" id="storage-connection-check">检查连接</button><button class="btn btn-primary" type="submit" ${s.id?'':'disabled'}>保存服务器</button></div></form>`;
const auth=host.querySelector('#storage-auth'),credentials=host.querySelector('#storage-credentials'),passwordless=host.querySelector('#storage-passwordless'),password=host.querySelector('#storage-password');
function syncAuth(){const custom=auth.value==='credentials';credentials.hidden=!custom;credentials.disabled=!custom;password.disabled=!custom||passwordless.checked;password.required=custom&&!passwordless.checked&&(!s.hasPassword||mode!=='credentials');}
auth.onchange=syncAuth;passwordless.onchange=syncAuth;syncAuth();
const form=host.querySelector('form'),checkButton=host.querySelector('#storage-connection-check'),saveButton=form.querySelector('[type="submit"]'),status=host.querySelector('#storage-connection-status'),errorBox=host.querySelector('#storage-error');
let verified=!!s.id,checking=false,saving=false,revision=0;
const form=host.querySelector('form'),checkButton=host.querySelector('#storage-connection-check'),browseButton=host.querySelector('#storage-directory-browse'),cancelButton=host.querySelector('#storage-operation-cancel'),picker=host.querySelector('#storage-directory-picker'),saveButton=form.querySelector('[type="submit"]'),status=host.querySelector('#storage-connection-status'),errorBox=host.querySelector('#storage-error'),addressInput=host.querySelector('#storage-address');
let verified=!!s.id,checking=false,saving=false,revision=0,operation=null;
const alive=()=>isActive()&&form.isConnected;
const update=()=>{saveButton.disabled=!verified||checking||saving;checkButton.disabled=checking||saving;};
const update=()=>{saveButton.disabled=!verified||checking||saving;checkButton.disabled=checking||saving;browseButton.disabled=checking||saving;cancelButton.hidden=!checking;};
function details(){
const input={...(s.id?{id:s.id,version:s.version}:{}),address:host.querySelector('#storage-address').value,name:host.querySelector('#storage-name').value,authMode:auth.value,enabled:host.querySelector('#storage-active').checked};
const input={...(s.id?{id:s.id,version:s.version}:{}),address:addressInput.value,name:host.querySelector('#storage-name').value,authMode:auth.value,enabled:host.querySelector('#storage-active').checked};
if(auth.value==='credentials')Object.assign(input,{username:host.querySelector('#storage-username').value,password:passwordless.checked?'':password.value,passwordless:passwordless.checked});return input;
}
function invalidate(event){if(!['storage-address','storage-auth','storage-username','storage-password','storage-passwordless'].includes(event.target.id)&&!(event.target.id==='storage-active'&&!s.enabled&&event.target.checked))return;revision++;verified=false;errorBox.textContent='';status.textContent='连接信息已变更,请重新检查。';update();}
async function request(route,input,signal,timeout=18000){
const controller=new AbortController(),cancel=()=>controller.abort(signal.reason);let timedOut=false;
if(signal?.aborted)cancel();else signal?.addEventListener('abort',cancel,{once:true});
const timer=setTimeout(()=>{timedOut=true;controller.abort();},timeout);
try{const response=await fetch('/api/storage/servers'+route,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify(input),signal:controller.signal});const body=await response.json();if(!response.ok)throw new Error(body.error||'存储操作失败。');return body;}
catch(error){if(timedOut)throw new Error(route===''?'保存响应超时,请刷新列表确认保存结果。':'连接超时,请检查网络后重试。');throw error;}
finally{clearTimeout(timer);signal?.removeEventListener('abort',cancel);}
}
function cancelOperation(){const current=operation;operation=null;revision++;checking=false;verified=false;current?.abort();if(alive()){status.textContent='已取消连接操作,可修改后重试。';update();}}
cancelButton.onclick=cancelOperation;
function invalidate(event){if(!['storage-address','storage-auth','storage-username','storage-password','storage-passwordless'].includes(event.target.id)&&!(event.target.id==='storage-active'&&!s.enabled&&event.target.checked))return;
if(operation)cancelOperation();revision++;verified=false;errorBox.textContent='';picker.hidden=true;status.textContent='连接信息已变更,请重新检查。';update();
}
form.addEventListener('input',invalidate);form.addEventListener('change',invalidate);
checkButton.onclick=async()=>{
function showDirectories(result){
picker.hidden=false;picker.innerHTML=`<div class="border rounded p-3"><div class="d-flex flex-wrap align-items-center gap-2 mb-2"><strong class="text-break flex-fill">${esc(result.address||addressInput.value)}</strong>${result.parent?'<button type="button" class="btn btn-sm" data-picker-up>上一级</button>':''}${result.readable?'<button type="button" class="btn btn-sm btn-primary" data-picker-select>选择此目录</button>':''}</div><div class="list-group">${(result.entries||[]).map((entry,index)=>`<button type="button" class="list-group-item list-group-item-action text-start text-break" data-picker-entry="${index}">${esc(entry.name)}</button>`).join('')||'<div class="text-secondary p-2">没有可列出的子目录。</div>'}</div>${result.serverRoot?'<div class="form-hint mt-2">点击一个共享继续浏览;若服务器禁止列举共享,可直接填写完整共享路径。</div>':''}${result.truncated?'<div class="form-hint">仅显示前 500 项。</div>':''}</div>`;
picker.querySelectorAll('[data-picker-entry]').forEach(button=>button.onclick=()=>navigate(result.entries[Number(button.dataset.pickerEntry)].address));
const up=picker.querySelector('[data-picker-up]');if(up)up.onclick=()=>navigate(result.parent);
const select=picker.querySelector('[data-picker-select]');if(select)select.onclick=()=>{addressInput.value=result.address;revision++;verified=true;picker.hidden=true;status.textContent='连接成功,目标目录可读取。';update();};
}
function navigate(address){addressInput.value=address;revision++;verified=false;return runConnection(true);}
async function runConnection(browse){
if(checking||saving||!form.reportValidity())return;
const at=revision;verified=false;checking=true;errorBox.textContent='';status.textContent='正在检查连接…';update();
try{const result=await api('/storage/servers/check',details());if(alive()&&at===revision){verified=result.readable===true;status.textContent=result.message;}}
catch(error){if(alive()&&at===revision){errorBox.textContent=error.message;status.textContent='连接检查失败,尚未保存。';}}
finally{checking=false;if(alive())update();}
};
host.querySelector('#storage-cancel').onclick=()=>host.replaceChildren();
const at=revision,controller=new AbortController();operation=controller;verified=false;checking=true;errorBox.textContent='';status.textContent=browse?'正在浏览共享目录…':'正在检查连接…';picker.hidden=true;update();
try{const result=await request(browse?'/browse':'/check',details(),controller.signal);
if(alive()&&operation===controller&&at===revision){if(result.address)addressInput.value=result.address;verified=result.readable===true;status.textContent=result.message||(result.serverRoot?'请选择一个共享目录。':'连接成功,目标目录可读取。');if(browse||result.serverRoot)showDirectories(result);}
}catch(error){if(alive()&&operation===controller&&at===revision){errorBox.textContent=error.message;status.textContent='连接操作未完成,尚未保存。';}}
finally{if(operation===controller){operation=null;checking=false;if(alive())update();}}
}
checkButton.onclick=()=>runConnection(false);browseButton.onclick=()=>runConnection(true);
const observer=new MutationObserver(()=>{if(!form.isConnected){cancelOperation();observer.disconnect();}});observer.observe(container,{childList:true,subtree:true});
host.querySelector('#storage-cancel').onclick=()=>{cancelOperation();observer.disconnect();host.replaceChildren();};
form.onsubmit=async e=>{
e.preventDefault();if(saving||checking)return;if(!verified){errorBox.textContent='请先检查连接,确认目录可读取后再保存。';return;}
const input=details();saving=true;errorBox.textContent='';form.querySelectorAll('input,select,button').forEach(node=>node.disabled=true);
try{await api('/storage/servers',input);if(alive()){notify('存储服务器已保存。');await render(container,isActive);}}
e.preventDefault();if(saving||checking)return;if(!verified){errorBox.textContent='请先检查连接或浏览选择可读取目录。';return;}
const input=details();saving=true;errorBox.textContent='';status.textContent='正在确认目录并保存…';picker.hidden=true;form.querySelectorAll('input,select,button').forEach(node=>node.disabled=true);
try{await request('',input,undefined,45000);if(alive()){notify('存储服务器已保存。');await render(container,isActive);}}
catch(error){if(alive()){verified=false;errorBox.textContent=error.message;status.textContent='保存失败,请重新检查连接后重试。';}}
finally{saving=false;if(alive()){form.querySelectorAll('input,select,button').forEach(node=>node.disabled=false);syncAuth();update();}}
};update();host.scrollIntoView({block:'start',behavior:'smooth'});