@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-11
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/CHANGELOG.md +103 -0
- package/LICENSE +21 -0
- package/README.md +149 -2
- package/client.js +3791 -0
- package/cordis.patch.yml +4 -0
- package/host/engine/archive.js +223 -0
- package/host/engine/atomic.js +27 -0
- package/host/engine/attachments.js +102 -0
- package/host/engine/config.js +218 -0
- package/host/engine/index.js +356 -0
- package/host/engine/ledger.js +108 -0
- package/host/engine/paths.js +81 -0
- package/host/engine/pluginlist.js +81 -0
- package/host/engine/projcache.js +202 -0
- package/host/engine/prune.js +187 -0
- package/host/engine/scan.js +177 -0
- package/host/engine/session.js +138 -0
- package/host/engine/sessions.js +395 -0
- package/host/engine/workspace.js +255 -0
- package/host/engine/zstd.js +91 -0
- package/host/envcheck.js +289 -0
- package/host/mirror.js +502 -0
- package/host/move.js +196 -0
- package/host/overwrite.js +305 -0
- package/host/restart.js +158 -0
- package/host/schedule.js +319 -0
- package/host/search.js +250 -0
- package/host/sync.js +608 -0
- package/host/trash.js +738 -0
- package/host/trashsync.js +204 -0
- package/host/webdav.js +429 -0
- package/icon.svg +1 -0
- package/index.js +412 -0
- package/locale/en.json +68 -0
- package/locale/zh.json +68 -0
- package/package.json +79 -4
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-machine recycle-bin sync for DSH增强.
|
|
3
|
+
*
|
|
4
|
+
* The PowerShell engine syncs sessions, config and attachments, but the recycle
|
|
5
|
+
* bin is plugin-owned data with deletes of its own, so it needs different rules:
|
|
6
|
+
* a plain "copy if newer" pass would resurrect entries the user purged. This
|
|
7
|
+
* module therefore keeps two small documents in the share:
|
|
8
|
+
*
|
|
9
|
+
* config/sync-state/trash-tombstones.json entry key -> deletion time
|
|
10
|
+
* config/sync-state/trash-state-<machine>.json keys this machine held last run
|
|
11
|
+
*
|
|
12
|
+
* An entry that disappears locally becomes a tombstone, a tombstone removes the
|
|
13
|
+
* entry on both sides, and an entry newer than its tombstone revives it (the user
|
|
14
|
+
* restored the session and later deleted it again).
|
|
15
|
+
*/
|
|
16
|
+
import { promises as fsp } from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
|
|
19
|
+
const UNGROUPED = '_ungrouped';
|
|
20
|
+
|
|
21
|
+
async function readJson(file) {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
24
|
+
} catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function writeJson(file, value) {
|
|
30
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
31
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
32
|
+
await fsp.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
33
|
+
await fsp.rm(file, { force: true });
|
|
34
|
+
await fsp.rename(temporary, file);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function readDirSafe(dir) {
|
|
38
|
+
try {
|
|
39
|
+
return await fsp.readdir(dir, { withFileTypes: true });
|
|
40
|
+
} catch {
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Newest mtime of any file inside one entry, so "edited then deleted" wins. */
|
|
46
|
+
async function newestMtime(dir) {
|
|
47
|
+
let newest = 0;
|
|
48
|
+
async function walk(current) {
|
|
49
|
+
let entries;
|
|
50
|
+
try {
|
|
51
|
+
entries = await fsp.readdir(current, { withFileTypes: true });
|
|
52
|
+
} catch {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
for (const entry of entries) {
|
|
56
|
+
const full = path.join(current, entry.name);
|
|
57
|
+
if (entry.isDirectory()) {
|
|
58
|
+
await walk(full);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const stat = await fsp.stat(full);
|
|
63
|
+
if (stat.mtimeMs > newest) newest = stat.mtimeMs;
|
|
64
|
+
} catch {
|
|
65
|
+
// A file removed mid-walk is simply absent.
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
await walk(dir);
|
|
70
|
+
return newest;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** One entry key plus its metadata, from one side of the sync. */
|
|
74
|
+
async function scanTrashSide(root) {
|
|
75
|
+
const entries = new Map();
|
|
76
|
+
for (const bucket of await readDirSafe(root)) {
|
|
77
|
+
if (!bucket.isDirectory()) continue;
|
|
78
|
+
const bucketDir = path.join(root, bucket.name);
|
|
79
|
+
for (const item of await readDirSafe(bucketDir)) {
|
|
80
|
+
if (!item.isDirectory()) continue;
|
|
81
|
+
if (item.name.includes('.staging-')) continue;
|
|
82
|
+
const dir = path.join(bucketDir, item.name);
|
|
83
|
+
const meta = (await readJson(path.join(dir, 'meta.json'))) ?? {};
|
|
84
|
+
let stamp = 0;
|
|
85
|
+
if (typeof meta.deletedAt === 'string') {
|
|
86
|
+
const parsed = Date.parse(meta.deletedAt);
|
|
87
|
+
if (Number.isFinite(parsed)) stamp = parsed;
|
|
88
|
+
}
|
|
89
|
+
if (stamp === 0) {
|
|
90
|
+
try { stamp = (await fsp.stat(dir)).mtimeMs; } catch { stamp = 0; }
|
|
91
|
+
}
|
|
92
|
+
const contentMtime = await newestMtime(dir);
|
|
93
|
+
entries.set(`${bucket.name}/${item.name}`, { key: `${bucket.name}/${item.name}`, dir, meta, stamp, contentMtime });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return entries;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Copy one entry directory next to its target, then swap it in. */
|
|
100
|
+
async function copyEntry(sourceDir, targetDir) {
|
|
101
|
+
const staging = `${targetDir}.sync-${String(process.pid)}`;
|
|
102
|
+
await fsp.rm(staging, { recursive: true, force: true });
|
|
103
|
+
await fsp.mkdir(path.dirname(targetDir), { recursive: true });
|
|
104
|
+
await fsp.cp(sourceDir, staging, { recursive: true });
|
|
105
|
+
await fsp.rm(targetDir, { recursive: true, force: true });
|
|
106
|
+
await fsp.rename(staging, targetDir);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Sync the recycle bin between this machine and the share.
|
|
111
|
+
* @param deps - Host paths, sync settings and the resolved machine id.
|
|
112
|
+
* @returns counters plus the tombstone count, for the run summary.
|
|
113
|
+
*/
|
|
114
|
+
export async function syncTrash(deps) {
|
|
115
|
+
const { paths, settings, machineId, syncDir } = deps;
|
|
116
|
+
const localRoot = paths.trashDir;
|
|
117
|
+
const sharedRoot = path.join(syncDir, 'trash');
|
|
118
|
+
const stateDir = path.join(syncDir, 'config', 'sync-state');
|
|
119
|
+
const tombstoneFile = path.join(stateDir, 'trash-tombstones.json');
|
|
120
|
+
const machineFile = path.join(stateDir, `trash-state-${machineId}.json`);
|
|
121
|
+
|
|
122
|
+
const local = await scanTrashSide(localRoot);
|
|
123
|
+
const shared = await scanTrashSide(sharedRoot);
|
|
124
|
+
const tombDoc = (await readJson(tombstoneFile)) ?? { version: 1, deleted: {} };
|
|
125
|
+
const tombstones = new Map(Object.entries(tombDoc.deleted ?? {}));
|
|
126
|
+
const previous = (await readJson(machineFile)) ?? { version: 1, keys: {} };
|
|
127
|
+
const previousKeys = new Set(Object.keys(previous.keys ?? {}));
|
|
128
|
+
|
|
129
|
+
let tombstoneChanges = 0;
|
|
130
|
+
const now = Date.now();
|
|
131
|
+
|
|
132
|
+
// 1. Local deletions become tombstones (a key we held last run but no longer do).
|
|
133
|
+
for (const key of previousKeys) {
|
|
134
|
+
if (local.has(key)) continue;
|
|
135
|
+
if (tombstones.has(key)) continue;
|
|
136
|
+
tombstones.set(key, new Date(now).toISOString());
|
|
137
|
+
tombstoneChanges += 1;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 2. Apply tombstones on both sides; a newer entry revives instead.
|
|
141
|
+
for (const [key, iso] of [...tombstones.entries()]) {
|
|
142
|
+
const tombTime = Date.parse(iso);
|
|
143
|
+
const sides = [local, shared];
|
|
144
|
+
let revived = false;
|
|
145
|
+
for (const side of sides) {
|
|
146
|
+
const entry = side.get(key);
|
|
147
|
+
if (entry === undefined) continue;
|
|
148
|
+
if (Number.isFinite(tombTime) && entry.stamp > tombTime) {
|
|
149
|
+
revived = true;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
await fsp.rm(entry.dir, { recursive: true, force: true }).catch(() => {});
|
|
153
|
+
side.delete(key);
|
|
154
|
+
}
|
|
155
|
+
if (revived) {
|
|
156
|
+
tombstones.delete(key);
|
|
157
|
+
tombstoneChanges += 1;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// 3. Union both sides: missing entries are copied, differing ones keep the newer.
|
|
162
|
+
let pushed = 0;
|
|
163
|
+
let pulled = 0;
|
|
164
|
+
const keys = new Set([...local.keys(), ...shared.keys()]);
|
|
165
|
+
for (const key of keys) {
|
|
166
|
+
if (tombstones.has(key)) continue;
|
|
167
|
+
const left = local.get(key);
|
|
168
|
+
const right = shared.get(key);
|
|
169
|
+
if (left !== undefined && right === undefined) {
|
|
170
|
+
await copyEntry(left.dir, path.join(sharedRoot, key));
|
|
171
|
+
pushed += 1;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (left === undefined && right !== undefined) {
|
|
175
|
+
await copyEntry(right.dir, path.join(localRoot, key));
|
|
176
|
+
pulled += 1;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (left === undefined || right === undefined) continue;
|
|
180
|
+
// "Edited, then deleted" leaves two entries with the same deletion time but
|
|
181
|
+
// different content: the newer log must win on both sides.
|
|
182
|
+
const newerLeft = left.contentMtime > right.contentMtime + 1
|
|
183
|
+
|| (Math.abs(left.contentMtime - right.contentMtime) <= 1 && left.stamp > right.stamp);
|
|
184
|
+
if (newerLeft) {
|
|
185
|
+
await copyEntry(left.dir, path.join(sharedRoot, key));
|
|
186
|
+
pushed += 1;
|
|
187
|
+
} else if (right.contentMtime > left.contentMtime + 1 || right.stamp > left.stamp) {
|
|
188
|
+
await copyEntry(right.dir, path.join(localRoot, key));
|
|
189
|
+
pulled += 1;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// 4. Remember what this machine holds, so the next run can spot deletions.
|
|
194
|
+
const keysNow = {};
|
|
195
|
+
for (const [key, entry] of local.entries()) keysNow[key] = new Date(entry.stamp).toISOString();
|
|
196
|
+
await writeJson(machineFile, { version: 1, machine: machineId, updatedAt: new Date().toISOString(), keys: keysNow });
|
|
197
|
+
if (tombstoneChanges > 0) {
|
|
198
|
+
const ordered = {};
|
|
199
|
+
for (const key of [...tombstones.keys()].sort()) ordered[key] = tombstones.get(key);
|
|
200
|
+
await writeJson(tombstoneFile, { version: 1, note: '回收站条目的删除墓碑,插件据此删除两端副本,请勿手改', deleted: ordered });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return { pushed, pulled, tombstones: tombstones.size, local: local.size, shared: shared.size };
|
|
204
|
+
}
|
package/host/webdav.js
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal WebDAV client for DSH增强.
|
|
3
|
+
*
|
|
4
|
+
* Only what the sync flow needs: a directory listing (PROPFIND) for the
|
|
5
|
+
* connection test now, and room for GET/PUT/MKCOL/DELETE when the mirror layer
|
|
6
|
+
* lands. No dependencies: Node's fetch sends the verb, Basic auth carries the
|
|
7
|
+
* credentials (坚果云 wants an application password, not the login password).
|
|
8
|
+
*
|
|
9
|
+
* Remote paths may contain Chinese and spaces; every segment is percent-encoded
|
|
10
|
+
* before the request is built.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const PROPFIND_BODY = '<?xml version="1.0" encoding="utf-8"?><d:propfind xmlns:d="DAV:"><d:prop><d:resourcetype/><d:getcontentlength/><d:getlastmodified/></d:prop></d:propfind>';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Normalize a user-typed WebDAV path: backslashes become forward slashes,
|
|
17
|
+
* duplicate and leading/trailing slashes are dropped. Callers always join, so a
|
|
18
|
+
* missing leading slash (or a trailing one) simply does not matter.
|
|
19
|
+
*/
|
|
20
|
+
export function normalizeRemotePath(value) {
|
|
21
|
+
if (typeof value !== 'string') return '';
|
|
22
|
+
return value
|
|
23
|
+
.replace(/\\/gu, '/')
|
|
24
|
+
.replace(/\/{2,}/gu, '/')
|
|
25
|
+
.replace(/^\/+/u, '')
|
|
26
|
+
.replace(/\/+$/u, '');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Encode one URL path, leaving already-escaped segments alone. */
|
|
30
|
+
export function encodePath(value) {
|
|
31
|
+
return String(value)
|
|
32
|
+
.split('/')
|
|
33
|
+
.map((segment) => {
|
|
34
|
+
if (segment === '') return '';
|
|
35
|
+
try {
|
|
36
|
+
return encodeURIComponent(decodeURIComponent(segment));
|
|
37
|
+
} catch {
|
|
38
|
+
return encodeURIComponent(segment);
|
|
39
|
+
}
|
|
40
|
+
})
|
|
41
|
+
.join('/');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Combine the server address with a remote path, tolerating a full URL in the path. */
|
|
45
|
+
export function buildRemoteUrl(baseUrl, remotePath) {
|
|
46
|
+
const base = typeof baseUrl === 'string' ? baseUrl.trim() : '';
|
|
47
|
+
const remote = normalizeRemotePath(typeof remotePath === 'string' ? remotePath : '');
|
|
48
|
+
if (/^https?:\/\//iu.test(remote)) return remote;
|
|
49
|
+
if (base === '') return remote;
|
|
50
|
+
const normalizedBase = base.endsWith('/') ? base : `${base}/`;
|
|
51
|
+
const cleanRemote = normalizeRemotePath(remote);
|
|
52
|
+
try {
|
|
53
|
+
const joined = new URL(normalizedBase);
|
|
54
|
+
joined.pathname = `${joined.pathname.replace(/\/+$/u, '')}/${cleanRemote}`;
|
|
55
|
+
return `${joined.origin}${encodePath(joined.pathname)}`;
|
|
56
|
+
} catch {
|
|
57
|
+
return `${normalizedBase}${encodePath(cleanRemote)}`;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function basicAuth(user, password) {
|
|
62
|
+
return `Basic ${Buffer.from(`${user}:${password}`, 'utf8').toString('base64')}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Split a URL into the encoded path segments that may need to be created. */
|
|
66
|
+
export function pathSegments(url) {
|
|
67
|
+
try {
|
|
68
|
+
const parsed = new URL(url);
|
|
69
|
+
return parsed.pathname.split('/').filter((segment) => segment !== '');
|
|
70
|
+
} catch {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Rebuild one absolute URL from the origin plus the first `count` segments. */
|
|
76
|
+
function urlForSegments(url, count) {
|
|
77
|
+
const parsed = new URL(url);
|
|
78
|
+
const segments = parsed.pathname.split('/').filter((segment) => segment !== '');
|
|
79
|
+
const tail = segments.slice(0, count).join('/');
|
|
80
|
+
return `${parsed.origin}/${tail}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** PROPFIND one collection without listing it. 207 is the normal exists answer. */
|
|
84
|
+
async function collectionExists(url, headers, signal) {
|
|
85
|
+
try {
|
|
86
|
+
const response = await davFetch(url, { method: 'PROPFIND', headers: { ...headers, Depth: '0' }, body: PROPFIND_BODY }, signal);
|
|
87
|
+
return response.status === 207 || response.status === 200;
|
|
88
|
+
} catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Create the configured remote path, one missing segment at a time.
|
|
95
|
+
* @returns the created segments plus a failure message when one cannot be made.
|
|
96
|
+
*/
|
|
97
|
+
export async function ensureRemotePath(url, headers, signal) {
|
|
98
|
+
const segments = pathSegments(url);
|
|
99
|
+
const created = [];
|
|
100
|
+
let existing = -1;
|
|
101
|
+
for (let count = segments.length; count >= 0; count -= 1) {
|
|
102
|
+
if (await collectionExists(urlForSegments(url, count), headers, signal)) {
|
|
103
|
+
existing = count;
|
|
104
|
+
break;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (existing < 0) return { ok: false, created, message: '远程地址不可访问,连最深一级父目录都不存在。' };
|
|
108
|
+
|
|
109
|
+
for (let count = existing + 1; count <= segments.length; count += 1) {
|
|
110
|
+
const target = urlForSegments(url, count);
|
|
111
|
+
let response;
|
|
112
|
+
try {
|
|
113
|
+
response = await davFetch(target, { method: 'MKCOL', headers }, signal);
|
|
114
|
+
} catch (error) {
|
|
115
|
+
return { ok: false, created, message: `创建目录失败:${error?.message ?? String(error)}` };
|
|
116
|
+
}
|
|
117
|
+
if (response.status === 201) {
|
|
118
|
+
created.push(segments[count - 1]);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
// 405 means the collection already exists on some servers; 409 means a parent is missing.
|
|
122
|
+
if (response.status === 405) continue;
|
|
123
|
+
if (response.status === 409) return { ok: false, created, message: '创建目录失败:父目录不存在。' };
|
|
124
|
+
if (response.status === 401 || response.status === 403) return { ok: false, created, message: '创建目录失败:账号没有写入权限。' };
|
|
125
|
+
return { ok: false, created, message: `创建目录失败:HTTP ${String(response.status)}。` };
|
|
126
|
+
}
|
|
127
|
+
return { ok: true, created, message: created.length === 0 ? '目录已存在。' : `已自动创建 ${String(created.length)} 级目录。` };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Pull the DAV hrefs out of a multistatus body without a namespace-aware parser. */
|
|
131
|
+
function parseMultistatus(text) {
|
|
132
|
+
const blocks = text.split(/<\/[^>]*:?response>/iu);
|
|
133
|
+
const entries = [];
|
|
134
|
+
for (const block of blocks) {
|
|
135
|
+
const href = /<[^>]*:?href[^>]*>([\s\S]*?)<\/[^>]*:?href>/iu.exec(block);
|
|
136
|
+
if (href === null) continue;
|
|
137
|
+
const isCollection = /<[^>]*:?collection\s*\/?>/iu.test(block);
|
|
138
|
+
const length = /<[^>]*:?getcontentlength[^>]*>([\s\S]*?)<\/[^>]*:?getcontentlength>/iu.exec(block);
|
|
139
|
+
const modified = /<[^>]*:?getlastmodified[^>]*>([\s\S]*?)<\/[^>]*:?getlastmodified>/iu.exec(block);
|
|
140
|
+
let decoded = href[1].trim();
|
|
141
|
+
try { decoded = decodeURIComponent(decoded); } catch { /* keep raw */ }
|
|
142
|
+
const name = decoded.replace(/\/+$/u, '').split('/').pop() ?? '';
|
|
143
|
+
const mtime = modified === null ? 0 : Date.parse(modified[1].trim());
|
|
144
|
+
entries.push({
|
|
145
|
+
href: decoded,
|
|
146
|
+
name,
|
|
147
|
+
collection: isCollection,
|
|
148
|
+
size: length === null ? 0 : Number(length[1].trim()) || 0,
|
|
149
|
+
mtime: Number.isFinite(mtime) ? mtime : 0,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
return entries;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* List one remote directory.
|
|
157
|
+
* @param settings - WebDAV settings (url, user, password, root).
|
|
158
|
+
* @returns ok/status/entries plus a human message the panel can show.
|
|
159
|
+
*/
|
|
160
|
+
export async function testConnection(settings, signal) {
|
|
161
|
+
const url = buildRemoteUrl(settings.webdavUrl, settings.webdavRoot);
|
|
162
|
+
if (url === '') throw Object.assign(new Error('请先填写 WebDAV 地址。'), { code: 'webdav-url-missing' });
|
|
163
|
+
if (typeof settings.webdavUser !== 'string' || settings.webdavUser.trim() === '') {
|
|
164
|
+
throw Object.assign(new Error('请先填写 WebDAV 账号。'), { code: 'webdav-user-missing' });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const headers = {
|
|
168
|
+
Depth: '1',
|
|
169
|
+
'Content-Type': 'application/xml; charset=utf-8',
|
|
170
|
+
Authorization: basicAuth(settings.webdavUser, settings.webdavPassword ?? ''),
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
let response;
|
|
174
|
+
try {
|
|
175
|
+
response = await davFetch(url, { method: 'PROPFIND', headers, body: PROPFIND_BODY }, signal);
|
|
176
|
+
} catch (error) {
|
|
177
|
+
throw Object.assign(new Error(`无法连接:${error?.message ?? String(error)}`), { code: 'webdav-unreachable' });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (response.status === 401 || response.status === 403) {
|
|
181
|
+
return { ok: false, status: response.status, url, message: '认证失败。坚果云需要填“应用密码”,不是登录密码。' };
|
|
182
|
+
}
|
|
183
|
+
if (response.status === 404) {
|
|
184
|
+
if (settings.webdavAutoCreate === false) {
|
|
185
|
+
return { ok: false, status: response.status, url, message: '路径不存在。请确认远程根目录已经在服务器上创建,或打开“自动创建目录”。' };
|
|
186
|
+
}
|
|
187
|
+
const made = await ensureRemotePath(url, headers, signal);
|
|
188
|
+
if (made.ok !== true) return { ok: false, status: response.status, url, message: made.message };
|
|
189
|
+
const retry = await davFetch(url, { method: 'PROPFIND', headers, body: PROPFIND_BODY }, signal);
|
|
190
|
+
if (!retry.ok) {
|
|
191
|
+
return { ok: false, status: retry.status, url, message: `${made.message}但随后无法读取该目录(HTTP ${String(retry.status)})。` };
|
|
192
|
+
}
|
|
193
|
+
const entries = parseMultistatus(await retry.text());
|
|
194
|
+
return {
|
|
195
|
+
ok: true,
|
|
196
|
+
status: retry.status,
|
|
197
|
+
url,
|
|
198
|
+
created: made.created,
|
|
199
|
+
entries: entries.slice(0, 50),
|
|
200
|
+
count: entries.length,
|
|
201
|
+
message: `${made.message}目录下 ${String(Math.max(0, entries.length - 1))} 项。`,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
if (response.status === 405) {
|
|
205
|
+
return { ok: false, status: response.status, url, message: '服务器不接受 PROPFIND,可能不是标准 WebDAV 地址。' };
|
|
206
|
+
}
|
|
207
|
+
if (!response.ok) {
|
|
208
|
+
return { ok: false, status: response.status, url, message: `服务器返回 HTTP ${String(response.status)}。` };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const text = await response.text();
|
|
212
|
+
const entries = parseMultistatus(text);
|
|
213
|
+
return {
|
|
214
|
+
ok: true,
|
|
215
|
+
status: response.status,
|
|
216
|
+
url,
|
|
217
|
+
entries: entries.slice(0, 50),
|
|
218
|
+
count: entries.length,
|
|
219
|
+
message: `目录下 ${String(Math.max(0, entries.length - 1))} 项。`,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Resolve one absolute URL from a DAV href (absolute path or full URL). */
|
|
224
|
+
function hrefToUrl(base, href) {
|
|
225
|
+
if (/^https?:\/\//iu.test(href)) return href;
|
|
226
|
+
const origin = new URL(base).origin;
|
|
227
|
+
return `${origin}${href.startsWith('/') ? '' : '/'}${encodePath(href)}`;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Relative path of one href under the configured root, decoded.
|
|
232
|
+
*
|
|
233
|
+
* DAV hrefs arrive percent-decoded from `parseMultistatus`, while the configured
|
|
234
|
+
* root comes from `new URL(...).pathname` and is still encoded. Comparing the two
|
|
235
|
+
* directly silently fails for any non-ASCII folder (坚果云 uses 我的坚果云), which
|
|
236
|
+
* used to make every file look like it existed on only one side.
|
|
237
|
+
*/
|
|
238
|
+
function relativeUnder(rootPath, href) {
|
|
239
|
+
let target = href;
|
|
240
|
+
if (/^https?:\/\//iu.test(target)) {
|
|
241
|
+
try { target = new URL(target).pathname; } catch { /* keep raw */ }
|
|
242
|
+
}
|
|
243
|
+
let root = rootPath;
|
|
244
|
+
try { root = decodeURIComponent(root); } catch { /* keep raw */ }
|
|
245
|
+
try { target = decodeURIComponent(target); } catch { /* keep raw */ }
|
|
246
|
+
root = root.replace(/\/+$/u, '');
|
|
247
|
+
target = target.replace(/\/+$/u, '');
|
|
248
|
+
if (target === root) return '';
|
|
249
|
+
if (target.startsWith(`${root}/`)) return target.slice(root.length + 1);
|
|
250
|
+
return target.replace(/^\/+/u, '');
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
254
|
+
|
|
255
|
+
/** fetch with 429/503 backoff — most WebDAV servers rate-limit per request. */
|
|
256
|
+
// A throttled server does not get better by hammering it: once a request ends
|
|
257
|
+
// in 429/503 (after its own retries) every later request fails fast for a while.
|
|
258
|
+
const THROTTLE_COOLDOWN_MS = 10 * 60_000;
|
|
259
|
+
let throttleUntil = 0;
|
|
260
|
+
let throttleStatus = 0;
|
|
261
|
+
|
|
262
|
+
/** Current throttle window, for diagnostics and the scheduler. */
|
|
263
|
+
export function throttleState() {
|
|
264
|
+
return { until: throttleUntil, status: throttleStatus };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function throttledError() {
|
|
268
|
+
const minutes = Math.max(1, Math.ceil((throttleUntil - Date.now()) / 60_000));
|
|
269
|
+
return Object.assign(
|
|
270
|
+
new Error(`云端限流中(HTTP ${String(throttleStatus)}),约 ${String(minutes)} 分钟后自动恢复`),
|
|
271
|
+
{ code: 'webdav-throttled', status: throttleStatus, until: throttleUntil },
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async function davFetch(url, init, signal, attempts = 5) {
|
|
276
|
+
if (Date.now() < throttleUntil) throw throttledError();
|
|
277
|
+
let response = await fetch(url, { ...init, signal });
|
|
278
|
+
for (let attempt = 1; attempt < attempts && (response.status === 429 || response.status === 503); attempt += 1) {
|
|
279
|
+
// Jianguoyun answers 503 when it is throttling; exponential backoff with the
|
|
280
|
+
// server's own Retry-After hint is the only sane way through.
|
|
281
|
+
const hinted = Number(response.headers?.get?.('retry-after'));
|
|
282
|
+
const delay = Number.isFinite(hinted) && hinted > 0 ? hinted * 1000 : Math.min(8000, 500 * (2 ** attempt));
|
|
283
|
+
await sleep(delay);
|
|
284
|
+
response = await fetch(url, { ...init, signal });
|
|
285
|
+
}
|
|
286
|
+
if (response.status === 429 || response.status === 503) {
|
|
287
|
+
throttleStatus = response.status;
|
|
288
|
+
throttleUntil = Date.now() + THROTTLE_COOLDOWN_MS;
|
|
289
|
+
}
|
|
290
|
+
return response;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Walk the configured remote tree, one PROPFIND per directory.
|
|
295
|
+
* @returns Map keyed by the path relative to the configured root.
|
|
296
|
+
*/
|
|
297
|
+
export async function listRemoteTree(settings, signal, options = {}) {
|
|
298
|
+
const base = buildRemoteUrl(settings.webdavUrl, settings.webdavRoot);
|
|
299
|
+
const maxDepth = Number.isInteger(options.maxDepth) ? options.maxDepth : 12;
|
|
300
|
+
const maxEntries = Number.isInteger(options.maxEntries) ? options.maxEntries : 20_000;
|
|
301
|
+
const headers = {
|
|
302
|
+
'Content-Type': 'application/xml; charset=utf-8',
|
|
303
|
+
Authorization: basicAuth(settings.webdavUser, settings.webdavPassword ?? ''),
|
|
304
|
+
};
|
|
305
|
+
const rootPath = new URL(base).pathname.replace(/\/+$/u, '');
|
|
306
|
+
const files = new Map();
|
|
307
|
+
const queue = [{ url: base, rel: '', depth: 0 }];
|
|
308
|
+
let requests = 0;
|
|
309
|
+
|
|
310
|
+
while (queue.length > 0) {
|
|
311
|
+
const item = queue.shift();
|
|
312
|
+
let response;
|
|
313
|
+
response = await davFetch(item.url, { method: 'PROPFIND', headers: { ...headers, Depth: '1' }, body: PROPFIND_BODY }, signal);
|
|
314
|
+
requests += 1;
|
|
315
|
+
if (response === undefined) break;
|
|
316
|
+
if (response.status === 404) continue;
|
|
317
|
+
if (response.status !== 207 && response.status !== 200) {
|
|
318
|
+
const hint = response.status === 429 || response.status === 503
|
|
319
|
+
? '(云端限流或暂时不可用,已自动重试并进入 10 分钟冷却)'
|
|
320
|
+
: (response.status >= 500 ? '(云端服务异常)' : '');
|
|
321
|
+
throw Object.assign(new Error(`列目录失败:HTTP ${String(response.status)}${hint}`), { code: 'webdav-list-failed', status: response.status });
|
|
322
|
+
}
|
|
323
|
+
for (const entry of parseMultistatus(await response.text())) {
|
|
324
|
+
const rel = relativeUnder(rootPath, entry.href);
|
|
325
|
+
if (rel === '' || rel === item.rel) continue;
|
|
326
|
+
if (entry.collection) {
|
|
327
|
+
if (item.depth < maxDepth) queue.push({ url: hrefToUrl(base, entry.href).replace(/\/+$/u, ''), rel, depth: item.depth + 1 });
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
files.set(rel, { size: entry.size, mtime: entry.mtime });
|
|
331
|
+
if (files.size > maxEntries) {
|
|
332
|
+
return { files, requests, truncated: true };
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return { files, requests, truncated: false };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Read the remote manifest document, if the share has one. */
|
|
340
|
+
export async function readRemoteManifest(settings, signal) {
|
|
341
|
+
const base = buildRemoteUrl(settings.webdavUrl, settings.webdavRoot);
|
|
342
|
+
const url = `${base.replace(/\/+$/u, '')}/_sync-manifest.json`;
|
|
343
|
+
const headers = { Authorization: basicAuth(settings.webdavUser, settings.webdavPassword ?? '') };
|
|
344
|
+
const response = await davFetch(url, { headers }, signal);
|
|
345
|
+
if (response.status === 404) return null;
|
|
346
|
+
if (!response.ok) return null;
|
|
347
|
+
const text = await response.text();
|
|
348
|
+
try {
|
|
349
|
+
return { text, json: JSON.parse(text) };
|
|
350
|
+
} catch {
|
|
351
|
+
return { text, json: null };
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Auth + XML headers for one configured share. */
|
|
356
|
+
export function shareHeaders(settings) {
|
|
357
|
+
return {
|
|
358
|
+
'Content-Type': 'application/xml; charset=utf-8',
|
|
359
|
+
Authorization: basicAuth(settings.webdavUser, settings.webdavPassword ?? ''),
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Absolute URL of one path relative to the configured root. */
|
|
364
|
+
export function remoteUrlFor(settings, rel) {
|
|
365
|
+
const base = buildRemoteUrl(settings.webdavUrl, settings.webdavRoot).replace(/\/+$/u, '');
|
|
366
|
+
return `${base}/${encodePath(rel.split('/').filter(Boolean).join('/'))}`;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Download one file; null on 404. */
|
|
370
|
+
export async function fetchRemoteFile(settings, rel, signal) {
|
|
371
|
+
const response = await davFetch(remoteUrlFor(settings, rel), { headers: shareHeaders(settings) }, signal);
|
|
372
|
+
if (response.status === 404) return null;
|
|
373
|
+
if (!response.ok) throw Object.assign(new Error(`下载失败 ${rel}:HTTP ${String(response.status)}`), { code: 'webdav-get-failed' });
|
|
374
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Upload one file, creating its parent collections first. */
|
|
378
|
+
export async function uploadRemoteFile(settings, rel, bytes, ensured, signal) {
|
|
379
|
+
const segments = rel.split('/');
|
|
380
|
+
const parent = segments.slice(0, -1).join('/');
|
|
381
|
+
if (parent !== '' && !ensured.has(parent)) {
|
|
382
|
+
const parentUrl = remoteUrlFor(settings, parent);
|
|
383
|
+
const made = await ensureRemotePath(parentUrl, shareHeaders(settings), signal);
|
|
384
|
+
if (made.ok !== true) throw Object.assign(new Error(made.message), { code: 'webdav-mkcol-failed' });
|
|
385
|
+
ensured.add(parent);
|
|
386
|
+
}
|
|
387
|
+
const response = await davFetch(remoteUrlFor(settings, rel), {
|
|
388
|
+
method: 'PUT',
|
|
389
|
+
headers: { ...shareHeaders(settings), 'Content-Type': 'application/octet-stream' },
|
|
390
|
+
body: bytes,
|
|
391
|
+
}, signal);
|
|
392
|
+
if (response.status !== 200 && response.status !== 201 && response.status !== 204) {
|
|
393
|
+
throw Object.assign(new Error(`上传失败 ${rel}:HTTP ${String(response.status)}`), { code: 'webdav-put-failed' });
|
|
394
|
+
}
|
|
395
|
+
return response.status;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Delete one remote file; a missing file counts as already deleted. */
|
|
399
|
+
export async function deleteRemoteFile(settings, rel, signal) {
|
|
400
|
+
const response = await davFetch(remoteUrlFor(settings, rel), { method: 'DELETE', headers: shareHeaders(settings) }, signal);
|
|
401
|
+
if (response.status === 200 || response.status === 202 || response.status === 204) return 'deleted';
|
|
402
|
+
if (response.status === 404) return 'missing';
|
|
403
|
+
throw Object.assign(new Error(`删除失败 ${rel}:HTTP ${String(response.status)}`), { code: 'webdav-delete-failed' });
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Delete one remote directory, but only after proving it holds nothing.
|
|
408
|
+
* DAV DELETE on a collection is recursive, so an unchecked call could wipe a
|
|
409
|
+
* whole subtree.
|
|
410
|
+
*/
|
|
411
|
+
export async function deleteEmptyRemoteDir(settings, rel, signal) {
|
|
412
|
+
const url = remoteUrlFor(settings, rel);
|
|
413
|
+
const headers = shareHeaders(settings);
|
|
414
|
+
const listing = await davFetch(url, { method: 'PROPFIND', headers: { ...headers, Depth: '1' }, body: PROPFIND_BODY }, signal);
|
|
415
|
+
if (listing.status === 404) return 'missing';
|
|
416
|
+
if (listing.status !== 207 && listing.status !== 200) return 'skipped';
|
|
417
|
+
const own = decodeURIComponent(new URL(url).pathname).replace(/\/+$/u, '');
|
|
418
|
+
const children = parseMultistatus(await listing.text())
|
|
419
|
+
.filter((entry) => entry.href.replace(/\/+$/u, '') !== own);
|
|
420
|
+
if (children.length > 0) return 'not-empty';
|
|
421
|
+
const removed = await davFetch(url, { method: 'DELETE', headers }, signal);
|
|
422
|
+
return removed.status === 200 || removed.status === 202 || removed.status === 204 ? 'deleted' : 'failed';
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Write the remote manifest so the next run can take the fast path. */
|
|
426
|
+
export async function writeRemoteManifest(settings, files, ensured, signal) {
|
|
427
|
+
const body = JSON.stringify({ version: 1, updatedAt: new Date().toISOString(), files }, null, 0);
|
|
428
|
+
return uploadRemoteFile(settings, '_sync-manifest.json', new TextEncoder().encode(body), ensured, signal);
|
|
429
|
+
}
|
package/icon.svg
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1794208814836" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="28594" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><linearGradient id="dshe-whale" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#4176E6"/><stop offset="0.55" stop-color="#4C7FE8"/><stop offset="1" stop-color="#7AA2F7"/></linearGradient></defs><g transform="translate(17 49)"><path fill="url(#dshe-whale)" d="M983.04 1003.52a139.8784 139.8784 0 0 1-57.9584-12.73856 142.19264 142.19264 0 0 0-59.8016-13.45536 140.63616 140.63616 0 0 0-59.8016 13.45536 140.55424 140.55424 0 0 1-57.93792 12.73856 140.75904 140.75904 0 0 1-58.18368-12.73856 140.77952 140.77952 0 0 0-59.8016-13.45536 140.4928 140.4928 0 0 0-59.5968 13.45536 140.5952 140.5952 0 0 1-58.1632 12.73856c-20.64384 0-40.3456-4.7104-57.93792-12.73856a140.53376 140.53376 0 0 0-59.76064-13.45536 142.21312 142.21312 0 0 0-59.82208 13.45536 139.40736 139.40736 0 0 1-57.81504 12.73856c-20.64384 0-40.3456-4.7104-57.93792-12.73856a140.63616 140.63616 0 0 0-59.8016-13.45536 142.19264 142.19264 0 0 0-59.8016 13.45536A139.79648 139.79648 0 0 1 40.96 1003.52v-87.57248c20.64384 0 40.3456-4.73088 57.93792-12.8a146.55488 146.55488 0 0 1 59.8016-13.18912c21.34016 0 41.75872 4.95616 59.8016 13.18912a139.01824 139.01824 0 0 0 57.93792 12.8 138.97728 138.97728 0 0 0 57.83552-12.8 146.49344 146.49344 0 0 1 59.82208-13.18912c21.34016 0 41.6768 4.95616 59.76064 13.18912a139.01824 139.01824 0 0 0 57.93792 12.8 140.14464 140.14464 0 0 0 58.1632-12.8 144.71168 144.71168 0 0 1 59.5968-13.18912c21.31968 0 41.71776 4.95616 59.8016 13.18912a140.0832 140.0832 0 0 0 58.18368 12.8c20.3776 0 40.3456-4.73088 57.93792-12.8a144.85504 144.85504 0 0 1 59.8016-13.18912c21.11488 0 41.51296 4.95616 59.8016 13.18912a139.264 139.264 0 0 0 57.9584 12.8V1003.52z m-380.47744-180.8384a129.76128 129.76128 0 0 1 26.99264-2.82624c21.31968 0 41.71776 4.93568 59.8016 13.18912a140.0832 140.0832 0 0 0 58.18368 12.77952c20.3776 0 40.3456-4.7104 57.93792-12.77952 12.43136-5.61152 25.8048-10.1376 40.12032-12.02176C837.8368 586.05568 594.35008 376.4224 582.88128 365.568c-11.96032-10.87488-22.99904-34.69312-15.23712-62.81216l58.14272-193.59744c10.3424-30.0032 5.18144-70.12352-9.1136-82.16576-8.21248-6.61504-25.57952-11.34592-37.33504 2.12992l-157.32736 179.65056c-34.48832 36.84352-5.61152 76.26752-6.30784 76.04224-53.51424-19.37408-116.34688-6.38976-154.46016 9.4208L131.2768 360.61184c-12.9024 5.4272-18.51392 21.93408-11.71456 33.03424 21.58592 34.73408 93.12256 34.95936 242.176 18.65728C602.56256 386.31424 602.80832 774.7584 602.56256 822.6816z" p-id="28595"></path></g></svg>
|