// 极简 WebDAV 客户端(基于 fetch),支持坚果云 / Nextcloud 等标准 WebDAV 服务
const PROPFIND_BODY = `<?xml version="1.0" encoding="utf-8"?>
<d:propfind xmlns:d="DAV:">
<d:prop>
<d:displayname/>
<d:getcontentlength/>
<d:getlastmodified/>
<d:resourcetype/>
</d:prop>
</d:propfind>`;
function decodeXmlEntities(text) {
return String(text || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
export class WebDavClient {
constructor(baseUrl, username, password) {
const trimmed = String(baseUrl || '').trim();
if (!/^https?:\/\//i.test(trimmed)) throw new Error('WebDAV 地址需以 http:// 或 https:// 开头');
this.baseUrl = trimmed.endsWith('/') ? trimmed : trimmed + '/';
this.authorization =
'Basic ' + Buffer.from(`${username || ''}:${password || ''}`).toString('base64');
}
/** 拼接远程路径(逐段编码,避免中文/空格问题) */
buildUrl(remotePath) {
const base = new URL(this.baseUrl);
const segments = String(remotePath || '')
.split('/')
.filter((s) => s && s !== '.' && s !== '..')
.map(encodeURIComponent);
const basePath = base.pathname.endsWith('/') ? base.pathname : base.pathname + '/';
base.pathname = basePath + segments.join('/');
return base.toString();
}
async request(method, remotePath, { body, headers = {} } = {}) {
const res = await fetch(this.buildUrl(remotePath), {
method,
headers: {
Authorization: this.authorization,
...headers,
},
body,
redirect: 'follow',
});
return res;
}
/** 递归创建目录(已存在时服务器通常返回 405) */
async ensureDir(remotePath) {
const segments = String(remotePath || '')
.split('/')
.filter(Boolean);
let current = '';
for (const segment of segments) {
current = current ? `${current}/${segment}` : segment;
const res = await this.request('MKCOL', current);
if (![201, 200, 204, 405, 301, 302].includes(res.status)) {
const text = await res.text().catch(() => '');
throw new Error(`创建 WebDAV 目录失败 (${res.status}) ${text.slice(0, 120)}`);
}
}
}
async put(remotePath, buffer, contentType = 'application/octet-stream') {
const res = await this.request('PUT', remotePath, {
body: buffer,
headers: { 'Content-Type': contentType, 'Content-Length': String(buffer.length) },
});
if (![200, 201, 204].includes(res.status)) {
const text = await res.text().catch(() => '');
throw new Error(`上传备份失败 (${res.status}) ${text.slice(0, 120)}`);
}
}
async get(remotePath) {
const res = await this.request('GET', remotePath);
if (!res.ok) throw new Error(`下载备份失败 (${res.status})`);
return Buffer.from(await res.arrayBuffer());
}
async remove(remotePath) {
const res = await this.request('DELETE', remotePath);
if (![200, 204, 404].includes(res.status)) {
throw new Error(`删除远程文件失败 (${res.status})`);
}
}
/** 列目录,返回文件名、大小、修改时间 */
async list(remotePath) {
const res = await this.request('PROPFIND', remotePath, {
headers: { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' },
body: PROPFIND_BODY,
});
if (!res.ok) throw new Error(`读取远程目录失败 (${res.status})`);
const xml = await res.text();
const blocks = xml.match(/<(?:\w+:)?response\b[\s\S]*?<\/(?:\w+:)?response>/gi) || [];
const items = [];
for (const block of blocks) {
const hrefMatch = block.match(/<(?:\w+:)?href[^>]*>([\s\S]*?)<\/(?:\w+:)?href>/i);
if (!hrefMatch) continue;
let href = decodeXmlEntities(hrefMatch[1].trim());
try {
href = decodeURIComponent(href);
} catch {
/* 部分服务器返回已解码的 href */
}
const name = href.replace(/\/+$/, '').split('/').pop();
if (!name) continue;
const isCollection = /<(?:\w+:)?resourcetype[^>]*>[\s\S]*?collection/i.test(block);
const sizeMatch = block.match(/<(?:\w+:)?getcontentlength[^>]*>(\d+)</i);
const dateMatch = block.match(/<(?:\w+:)?getlastmodified[^>]*>([^<]*)</i);
items.push({
name,
isCollection,
size: sizeMatch ? Number(sizeMatch[1]) : 0,
lastModified: dateMatch ? Date.parse(dateMatch[1]) || null : null,
});
}
// 去掉 PROPFIND 返回的自身目录
return items.filter((item, index) => !(index === 0 && item.isCollection));
}
}
/** 从用户备份设置创建客户端 */
export function clientFromSettings(backupSettings, password) {
return new WebDavClient(backupSettings.webdavUrl, backupSettings.webdavUsername, password);
}