@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-10
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 +92 -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 +150 -0
- package/host/engine/atomic.js +27 -0
- package/host/engine/attachments.js +102 -0
- package/host/engine/config.js +214 -0
- package/host/engine/index.js +355 -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 +315 -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 +376 -0
- package/locale/en.json +68 -0
- package/locale/zh.json +68 -0
- package/package.json +79 -4
package/host/sync.js
ADDED
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sync runner for DSH增强 — JavaScript engine only.
|
|
3
|
+
*
|
|
4
|
+
* One run is: resolve the target, verify this machine's identity, (WebDAV) pull
|
|
5
|
+
* the mirror down, run the engine, sync the recycle bin, (WebDAV) push the mirror
|
|
6
|
+
* back, then record the outcome. The PowerShell engine and its zstd helper are
|
|
7
|
+
* gone; everything below the transport layer lives in `host/engine/`.
|
|
8
|
+
*/
|
|
9
|
+
import { promises as fsp } from 'node:fs';
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import os from 'node:os';
|
|
13
|
+
import { runSyncJs } from './engine/index.js';
|
|
14
|
+
import { syncTrash } from './trashsync.js';
|
|
15
|
+
import { measureMirror, pullMirror, pullMirrorFast, pushMirror } from './mirror.js';
|
|
16
|
+
|
|
17
|
+
const TAIL_LINES = 400;
|
|
18
|
+
const HISTORY_CAP = 1000;
|
|
19
|
+
|
|
20
|
+
async function readJson(file) {
|
|
21
|
+
try {
|
|
22
|
+
return JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
23
|
+
} catch {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function writeJson(file, value) {
|
|
29
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
30
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
31
|
+
await fsp.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
32
|
+
await fsp.rename(temporary, file).catch(async () => {
|
|
33
|
+
await fsp.rm(file, { force: true }).catch(() => {});
|
|
34
|
+
await fsp.rename(temporary, file);
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function tailLines(text, limit = TAIL_LINES) {
|
|
39
|
+
const lines = String(text).split(/\r?\n/u);
|
|
40
|
+
return lines.slice(Math.max(0, lines.length - limit));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Read (or create) the per-installation id used to detect id collisions. */
|
|
44
|
+
async function readInstanceId(baseDir) {
|
|
45
|
+
const file = path.join(baseDir, 'instance-id.txt');
|
|
46
|
+
try {
|
|
47
|
+
const text = await fsp.readFile(file, 'utf8');
|
|
48
|
+
if (text.trim() !== '') return text.trim();
|
|
49
|
+
} catch {
|
|
50
|
+
// First run on this installation.
|
|
51
|
+
}
|
|
52
|
+
const id = randomUUID();
|
|
53
|
+
await fsp.mkdir(baseDir, { recursive: true }).catch(() => {});
|
|
54
|
+
await fsp.writeFile(file, id, 'utf8').catch(() => {});
|
|
55
|
+
return id;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Refuse to sync when this machine id is already claimed by a different
|
|
60
|
+
* installation: two devices with one id overwrite each other's baseline and
|
|
61
|
+
* tombstone each other's sessions.
|
|
62
|
+
*/
|
|
63
|
+
export async function checkIdentity(shareDir, machineId, baseDir) {
|
|
64
|
+
const stateDir = path.join(shareDir, 'config', 'sync-state');
|
|
65
|
+
const file = path.join(stateDir, 'instances.json');
|
|
66
|
+
const registry = (await readJson(file)) ?? {};
|
|
67
|
+
const machines = registry.machines !== null && typeof registry.machines === 'object' ? registry.machines : {};
|
|
68
|
+
const instanceId = await readInstanceId(baseDir);
|
|
69
|
+
const existing = machines[machineId];
|
|
70
|
+
if (typeof existing === 'string' && existing !== instanceId) {
|
|
71
|
+
return { ok: false, machines: Object.keys(machines).sort() };
|
|
72
|
+
}
|
|
73
|
+
machines[machineId] = instanceId;
|
|
74
|
+
await writeJson(file, { version: 1, updatedAt: new Date().toISOString(), machines }).catch(() => {});
|
|
75
|
+
return { ok: true, machines: Object.keys(machines).sort() };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The folder the engine reads and writes for the active mode. */
|
|
79
|
+
export function effectiveShareDir(settings) {
|
|
80
|
+
const mode = settings.syncMode === 'webdav' ? 'webdav' : 'local';
|
|
81
|
+
const raw = mode === 'webdav' ? settings.mirrorDir : settings.syncDir;
|
|
82
|
+
return typeof raw === 'string' ? raw.trim() : '';
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Resolve the share root and identity for one run. */
|
|
86
|
+
export function resolveSyncTarget(paths, settings) {
|
|
87
|
+
const mode = settings.syncMode === 'webdav' ? 'webdav' : 'local';
|
|
88
|
+
const syncDir = effectiveShareDir(settings);
|
|
89
|
+
const machineId = (typeof settings.syncMachineId === 'string' && settings.syncMachineId.trim() !== '')
|
|
90
|
+
? settings.syncMachineId.trim()
|
|
91
|
+
: path.basename(process.env.USERPROFILE ?? '') || os.userInfo().username;
|
|
92
|
+
const profile = process.env.DSH_PROFILE ?? 'desktop';
|
|
93
|
+
return {
|
|
94
|
+
mode,
|
|
95
|
+
syncDir,
|
|
96
|
+
machineId,
|
|
97
|
+
profile,
|
|
98
|
+
stateFile: path.join(paths.base, 'sync-state.json'),
|
|
99
|
+
logFile: path.join(paths.base, 'sync-last.log'),
|
|
100
|
+
historyFile: path.join(paths.base, 'sync-history.json'),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Session id -> title, read from the mirrored projection shards. */
|
|
105
|
+
async function readTitles(syncDir) {
|
|
106
|
+
const titles = new Map();
|
|
107
|
+
const dir = path.join(syncDir, 'config', 'storages', 'session_projcache', 'sessions');
|
|
108
|
+
let names = [];
|
|
109
|
+
try {
|
|
110
|
+
names = await fsp.readdir(dir);
|
|
111
|
+
} catch {
|
|
112
|
+
return titles;
|
|
113
|
+
}
|
|
114
|
+
for (const name of names) {
|
|
115
|
+
if (!name.endsWith('.json')) continue;
|
|
116
|
+
const id = name.slice(0, -5);
|
|
117
|
+
try {
|
|
118
|
+
const doc = JSON.parse(await fsp.readFile(path.join(dir, name), 'utf8'));
|
|
119
|
+
const value = doc?.record?.rows?.title?.val;
|
|
120
|
+
if (typeof value === 'string' && value.trim() !== '') titles.set(id, value.trim());
|
|
121
|
+
} catch {
|
|
122
|
+
// An unreadable shard simply has no title.
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return titles;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Group paths by session: the log first, then its projection shard. */
|
|
129
|
+
function sessionRels(list) {
|
|
130
|
+
const of = (rel) => {
|
|
131
|
+
const match = /session-([0-9a-f-]{8,})/iu.exec(rel);
|
|
132
|
+
return match === null ? '' : match[1];
|
|
133
|
+
};
|
|
134
|
+
const rank = (rel) => (rel.startsWith('sessions/') ? 0 : (rel.includes('session_projcache') ? 1 : 2));
|
|
135
|
+
return [...list].sort((left, right) => {
|
|
136
|
+
const a = of(left);
|
|
137
|
+
const b = of(right);
|
|
138
|
+
if (a !== '' && b !== '' && a === b) return rank(left) - rank(right) || left.localeCompare(right);
|
|
139
|
+
if (a === '' && b === '') return left.localeCompare(right);
|
|
140
|
+
if (a === '') return -1;
|
|
141
|
+
if (b === '') return 1;
|
|
142
|
+
return a.localeCompare(b) || rank(left) - rank(right);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Name one path: session files carry the session title in front of the path. */
|
|
147
|
+
function describePath(rel, titleMap) {
|
|
148
|
+
const match = /(^|\/)session-([^/]+)\//u.exec(rel) ?? /session-(.+)\.json$/u.exec(rel);
|
|
149
|
+
const id = match === null ? '' : `session-${match[2] ?? match[1]}`;
|
|
150
|
+
const title = id === '' ? '' : titleMap.get(id);
|
|
151
|
+
return title === undefined || title === '' ? rel : `${title} · ${rel}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Badge numbers for ⬆ / ⬇ / 🗑: session files only.
|
|
156
|
+
*
|
|
157
|
+
* The transport moves more than sessions (title shards under
|
|
158
|
+
* config/storages/session_projcache, config, attachments, trash), but the badge
|
|
159
|
+
* answers "how many sessions moved", so only the `sessions/` bucket is counted.
|
|
160
|
+
* Other categories still show up in the log lines and their own category line.
|
|
161
|
+
*/
|
|
162
|
+
export function sessionBadgeCounts(transport, summary) {
|
|
163
|
+
const uploaded = Number(transport?.pushed?.uploaded) || 0;
|
|
164
|
+
const downloaded = Number(transport?.pulled?.downloaded) || 0;
|
|
165
|
+
const sessionUploaded = Number(transport?.pushed?.categories?.sessions) || 0;
|
|
166
|
+
const sessionDownloaded = Number(transport?.pulled?.categories?.sessions) || 0;
|
|
167
|
+
const sessionDeleted = Number(transport?.pushed?.deletedCategories?.sessions) || 0;
|
|
168
|
+
return {
|
|
169
|
+
up: uploaded > 0 ? sessionUploaded : Number(summary?.sessions?.pushed) || 0,
|
|
170
|
+
down: downloaded > 0 ? sessionDownloaded : Number(summary?.sessions?.pulled) || 0,
|
|
171
|
+
del: sessionDeleted,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Human-readable summary lines for the settings page. */
|
|
176
|
+
function logLines(summary, transport, titleMap = new Map()) {
|
|
177
|
+
const counts = (value) => String(Number(value) || 0);
|
|
178
|
+
const pushed = Number(summary.sessions?.pushed) || 0;
|
|
179
|
+
const pulled = Number(summary.sessions?.pulled) || 0;
|
|
180
|
+
const configCopied = Number(summary.config?.copied) || 0;
|
|
181
|
+
const attachCopied = Number(summary.attachments?.copied) || 0;
|
|
182
|
+
const prunedLocal = Number(summary.prune?.quarantined) || 0;
|
|
183
|
+
const prunedCloud = Number(summary.prune?.sharedDeleted) || 0;
|
|
184
|
+
const prunedKept = Number(summary.prune?.kept) || 0;
|
|
185
|
+
const titles = Number(summary.titleMerge?.updated) || 0;
|
|
186
|
+
const localGroups = Number(summary.workspace?.local) || 0;
|
|
187
|
+
const sharedGroups = Number(summary.workspace?.shared) || 0;
|
|
188
|
+
|
|
189
|
+
const entries = [];
|
|
190
|
+
const push = (line, files) => entries.push({ line, files: Array.isArray(files) ? files.slice(0, 300) : [] });
|
|
191
|
+
push(pushed === 0 && pulled === 0
|
|
192
|
+
? '会话:双端一致,无传输'
|
|
193
|
+
: `会话:云端推送 ${counts(pushed)} 个,云端取回 ${counts(pulled)} 个`,
|
|
194
|
+
[
|
|
195
|
+
...(summary.sessions?.pushedIds ?? []).map((id) => `推送上云:${titleMap.get(id) ?? id}`),
|
|
196
|
+
...(summary.sessions?.pulledIds ?? []).map((id) => `从云取回:${titleMap.get(id) ?? id}`),
|
|
197
|
+
]);
|
|
198
|
+
const guardSkipped = Number(summary.blankGuard?.skipped) || 0;
|
|
199
|
+
const guardRepaired = Number(summary.blankGuard?.repaired) || 0;
|
|
200
|
+
if (guardSkipped > 0 || guardRepaired > 0) {
|
|
201
|
+
const repaired = guardRepaired > 0 ? `,修复过期缓存 ${counts(guardRepaired)} 个` : '';
|
|
202
|
+
push(`空白会话:跳过 ${counts(guardSkipped)} 个${repaired}`);
|
|
203
|
+
}
|
|
204
|
+
push(configCopied === 0 && attachCopied === 0
|
|
205
|
+
? '配置附件:双端一致,无更新'
|
|
206
|
+
: `配置附件:更新配置 ${counts(configCopied)} 个、附件 ${counts(attachCopied)} 个`,
|
|
207
|
+
(summary.configDetails ?? []).map((item) => `${item.action === 'push' ? '上云' : '下载'}:${item.rel}`));
|
|
208
|
+
push(`工作区:本机 ${counts(localGroups)} 个、云端 ${counts(sharedGroups)} 个${titles > 0 ? `,对齐会话标题 ${counts(titles)} 个` : ''}`);
|
|
209
|
+
push(prunedLocal === 0 && prunedCloud === 0 && prunedKept === 0
|
|
210
|
+
? '失效清理:无需清理'
|
|
211
|
+
: `失效清理:移入隔离区 ${counts(prunedLocal)} 个、云端删除 ${counts(prunedCloud)} 个、保留 ${counts(prunedKept)} 个`,
|
|
212
|
+
(summary.prune?.sharedDeletedRels ?? []).map((rel) => `云端删除:${rel}`));
|
|
213
|
+
push(Number(summary.plugins) === 0
|
|
214
|
+
? '插件清单:无需更新'
|
|
215
|
+
: `插件清单:本机 ${counts(summary.plugins)} 个,已推送云端`,
|
|
216
|
+
Number(summary.plugins) > 0 ? ['config/plugin-list.txt'] : []);
|
|
217
|
+
if (Number(summary.archive?.released) > 0) {
|
|
218
|
+
push(`会话归档:从云端解除会话归档 ${counts(summary.archive.released)} 个`);
|
|
219
|
+
}
|
|
220
|
+
if (transport !== null && transport !== undefined) {
|
|
221
|
+
const uploaded = Number(transport.pushed?.uploaded) || 0;
|
|
222
|
+
const downloaded = Number(transport.pulled?.downloaded) || 0;
|
|
223
|
+
if (uploaded > 0 || downloaded > 0) {
|
|
224
|
+
push(`云端传输:上传 ${counts(uploaded)} 个、下载 ${counts(downloaded)} 个文件`,
|
|
225
|
+
[
|
|
226
|
+
...sessionRels(transport.pushed?.uploadedRels ?? []).map((rel) => `上传:${describePath(rel, titleMap)}`),
|
|
227
|
+
...sessionRels(transport.pushed?.deletedRels ?? []).map((rel) => `云端删除:${describePath(rel, titleMap)}`),
|
|
228
|
+
...sessionRels(transport.pulled?.downloadedRels ?? []).map((rel) => `下载:${describePath(rel, titleMap)}`),
|
|
229
|
+
]);
|
|
230
|
+
const parts = [];
|
|
231
|
+
const categories = transport.pushed?.categories ?? {};
|
|
232
|
+
const labels = { sessions: '会话文件', config: '配置文件', titles: '标题文件', trash: '回收站文件', attachments: '附件', other: '其他文件' };
|
|
233
|
+
for (const [key, label] of Object.entries(labels)) {
|
|
234
|
+
const value = Number(categories[key]) || 0;
|
|
235
|
+
if (value > 0) parts.push(`${label} ${counts(value)} 个`);
|
|
236
|
+
}
|
|
237
|
+
if (parts.length > 0) push(` 其中上传:${parts.join('、')}`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
for (const item of (summary.configDetails ?? []).slice(0, 10)) {
|
|
241
|
+
const delta = item.deltaMs === null
|
|
242
|
+
? '只有一侧存在'
|
|
243
|
+
: (Math.abs(item.deltaMs) >= 3_600_000
|
|
244
|
+
? `相差 ${counts(Math.round(Math.abs(item.deltaMs) / 3_600_000))} 小时`
|
|
245
|
+
: (Math.abs(item.deltaMs) >= 60_000
|
|
246
|
+
? `相差 ${counts(Math.round(Math.abs(item.deltaMs) / 60_000))} 分钟`
|
|
247
|
+
: `相差 ${counts(Math.max(1, Math.round(Math.abs(item.deltaMs) / 1000)))} 秒`));
|
|
248
|
+
push(`更新配置:${item.rel}(${item.action === 'push' ? '本机较新' : (item.action === 'staged' ? '云端较新,重启应用后生效' : '云端较新')},${delta})`, [`${item.action === 'push' ? '上云' : '下载'}:${item.rel}`]);
|
|
249
|
+
}
|
|
250
|
+
if (Array.isArray(summary.phases) && summary.ok === false) {
|
|
251
|
+
push(`中止:阶段 ${summary.failed?.phase ?? '未知'},${summary.failed?.error ?? ''}`);
|
|
252
|
+
}
|
|
253
|
+
const kept = entries.slice(Math.max(0, entries.length - TAIL_LINES));
|
|
254
|
+
return { lines: kept.map((entry) => entry.line), details: kept.map((entry) => entry.files) };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Map a failure to a short diagnosis and an actionable hint. */
|
|
258
|
+
export function diagnose(error) {
|
|
259
|
+
const code = String(error?.code ?? '');
|
|
260
|
+
const message = String(error?.message ?? error);
|
|
261
|
+
const cause = String(error?.cause?.code ?? '');
|
|
262
|
+
const network = ['ENOTFOUND', 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', 'EHOSTUNREACH'];
|
|
263
|
+
if (network.includes(cause) || network.includes(code) || message.includes('fetch failed') || message.includes('无法连接')) {
|
|
264
|
+
return { summary: '网络不可达', hint: '检查网络、代理或 VPN;确认 WebDAV 地址可访问。' };
|
|
265
|
+
}
|
|
266
|
+
if (code === 'webdav-pull-failed' || message.includes('503') || message.includes('429')) {
|
|
267
|
+
return { summary: '云端限流或暂时不可用', hint: '等待 10 分钟后重试;连续出现时降低同步频率。' };
|
|
268
|
+
}
|
|
269
|
+
if (message.includes('401') || message.includes('403')) {
|
|
270
|
+
return { summary: '云端认证失败', hint: '检查 WebDAV 账号与应用密码(坚果云需用应用密码)。' };
|
|
271
|
+
}
|
|
272
|
+
if (message.includes('404')) {
|
|
273
|
+
return { summary: '远程目录不存在', hint: '确认远程根目录写法正确,或打开“自动创建远程目录”。' };
|
|
274
|
+
}
|
|
275
|
+
if (code === 'machine-id-conflict') {
|
|
276
|
+
return { summary: '机器标识冲突', hint: '在设置里换一个未被占用的机器标识。' };
|
|
277
|
+
}
|
|
278
|
+
if (code === 'sync-dir-missing') {
|
|
279
|
+
return { summary: '未配置同步目录', hint: '填写共享目录(本地模式)或本地镜像目录(WebDAV 模式)。' };
|
|
280
|
+
}
|
|
281
|
+
if (code === 'sessions-root-missing') {
|
|
282
|
+
return { summary: '会话目录不可读', hint: '检查 DSH 主目录是否被移动或权限不足。' };
|
|
283
|
+
}
|
|
284
|
+
if (code === 'tombstone-corrupt') {
|
|
285
|
+
return { summary: '删除记录文件损坏', hint: '先备份并移走 deleted-sessions.json,再重新同步。' };
|
|
286
|
+
}
|
|
287
|
+
if (code === 'sync-busy') {
|
|
288
|
+
return { summary: '已有同步正在进行', hint: '等上一轮结束再试。' };
|
|
289
|
+
}
|
|
290
|
+
if (code === 'webdav-throttled') {
|
|
291
|
+
return { summary: '云端处于限流冷却期', hint: '等冷却结束(约 10 分钟)后自动恢复。' };
|
|
292
|
+
}
|
|
293
|
+
if (code === 'phase-failed' || error?.phase !== undefined) {
|
|
294
|
+
return { summary: `同步在阶段“${String(error?.phase ?? '未知')}”失败`, hint: '查看下方日志定位具体文件;下一次同步会自动续做。' };
|
|
295
|
+
}
|
|
296
|
+
return { summary: '同步未完成', hint: '查看下方原因;必要时运行“环境检测”。' };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Record a failed run so the log panel is not silently empty. */
|
|
300
|
+
async function recordFailure(deps, error, startedAt, probe) {
|
|
301
|
+
try {
|
|
302
|
+
const target = resolveSyncTarget(deps.paths, deps.settings);
|
|
303
|
+
const diagnosis = diagnose(error);
|
|
304
|
+
const record = {
|
|
305
|
+
at: new Date().toISOString(),
|
|
306
|
+
probe: probe === true,
|
|
307
|
+
engine: 'js',
|
|
308
|
+
ok: false,
|
|
309
|
+
durationMs: Date.now() - startedAt,
|
|
310
|
+
summary: { ok: false, failed: { phase: error?.phase ?? null, error: String(error?.message ?? error) } },
|
|
311
|
+
transport: null,
|
|
312
|
+
syncDir: target.syncDir,
|
|
313
|
+
machineId: target.machineId,
|
|
314
|
+
error: String(error?.message ?? error),
|
|
315
|
+
diagnosis,
|
|
316
|
+
log: [
|
|
317
|
+
`同步失败:${diagnosis.summary}`,
|
|
318
|
+
`原因:${String(error?.message ?? error)}`,
|
|
319
|
+
`建议:${diagnosis.hint}`,
|
|
320
|
+
],
|
|
321
|
+
details: [[], [], []],
|
|
322
|
+
};
|
|
323
|
+
await writeJson(target.stateFile, record).catch(() => {});
|
|
324
|
+
await appendHistory(target.historyFile, record).catch(() => {});
|
|
325
|
+
} catch {
|
|
326
|
+
// Recording a failure must never mask the original error.
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Run one sync: transport, engine, recycle bin, transport back, record. */
|
|
331
|
+
export async function runSync(deps, options = {}) {
|
|
332
|
+
const startedAt = Date.now();
|
|
333
|
+
try {
|
|
334
|
+
return await runSyncInner(deps, options, startedAt);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
await recordFailure(deps, error, startedAt, options.probe);
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function runSyncInner(deps, options, startedAt) {
|
|
342
|
+
const { paths, settings } = deps;
|
|
343
|
+
const probe = options.probe === true;
|
|
344
|
+
const target = resolveSyncTarget(paths, settings);
|
|
345
|
+
|
|
346
|
+
if (target.syncDir === '') {
|
|
347
|
+
throw Object.assign(new Error('请先在设置里填写共享目录。'), { code: 'sync-dir-missing' });
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
let pulled = null;
|
|
351
|
+
if (!probe && target.mode === 'webdav') {
|
|
352
|
+
try {
|
|
353
|
+
// The manifest is a complete index of the share, so the common case needs one
|
|
354
|
+
// GET instead of a PROPFIND tour. A full scan runs when the manifest is
|
|
355
|
+
// missing and after the freshness window, catching outside changes.
|
|
356
|
+
const scanFile = path.join(paths.base, 'mirror-scan.json');
|
|
357
|
+
const scan = await readJson(scanFile, { lastFullScan: 0 });
|
|
358
|
+
const fresh = Number(scan?.lastFullScan) > 0 && Date.now() - Number(scan.lastFullScan) < 30 * 60 * 1000;
|
|
359
|
+
pulled = fresh ? await pullMirrorFast({ settings, paths }) : null;
|
|
360
|
+
if (pulled === null) {
|
|
361
|
+
pulled = await pullMirror({ settings, paths });
|
|
362
|
+
await writeJson(scanFile, { lastFullScan: Date.now() }).catch(() => {});
|
|
363
|
+
}
|
|
364
|
+
} catch (error) {
|
|
365
|
+
throw Object.assign(new Error(`下载云端失败:${String(error?.message ?? error)}`), { code: 'webdav-pull-failed' });
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (!probe) {
|
|
370
|
+
const identity = await checkIdentity(target.syncDir, target.machineId, paths.base);
|
|
371
|
+
if (identity.ok !== true) {
|
|
372
|
+
throw Object.assign(
|
|
373
|
+
new Error(`机器标识“${target.machineId}”已被另一台设备使用(共享中现有:${identity.machines.join('、')})。请在设置里换一个不同的标识后重试。`),
|
|
374
|
+
{ code: 'machine-id-conflict', machines: identity.machines },
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
let summary;
|
|
380
|
+
try {
|
|
381
|
+
summary = await runSyncJs({
|
|
382
|
+
dshHome: paths.home,
|
|
383
|
+
syncDir: target.syncDir,
|
|
384
|
+
machineId: target.machineId,
|
|
385
|
+
user: target.machineId,
|
|
386
|
+
profile: target.profile,
|
|
387
|
+
apply: !probe,
|
|
388
|
+
now: startedAt,
|
|
389
|
+
skipAttachments: settings.syncSkipAttachments === true,
|
|
390
|
+
});
|
|
391
|
+
} catch (error) {
|
|
392
|
+
summary = {
|
|
393
|
+
ok: false,
|
|
394
|
+
failed: { phase: error?.phase ?? null, error: String(error?.message ?? error) },
|
|
395
|
+
phases: [],
|
|
396
|
+
sessions: { pushed: 0, pulled: 0, skipped: 0 },
|
|
397
|
+
config: { copied: 0, skipped: 0 },
|
|
398
|
+
attachments: { copied: 0, skipped: 0 },
|
|
399
|
+
prune: {},
|
|
400
|
+
workspace: {},
|
|
401
|
+
titleMerge: {},
|
|
402
|
+
plugins: 0,
|
|
403
|
+
archive: {},
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
let trash = null;
|
|
408
|
+
if (!probe && summary.ok !== false) {
|
|
409
|
+
try {
|
|
410
|
+
trash = await syncTrash({ paths, settings, machineId: target.machineId, syncDir: target.syncDir });
|
|
411
|
+
} catch (error) {
|
|
412
|
+
trash = { error: String(error?.message ?? error) };
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
let pushed = null;
|
|
417
|
+
if (!probe && summary.ok !== false && target.mode === 'webdav') {
|
|
418
|
+
try {
|
|
419
|
+
pushed = await pushMirror({ settings, paths, useManifestIndex: pulled?.fast === true });
|
|
420
|
+
} catch (error) {
|
|
421
|
+
pushed = { ok: false, error: String(error?.message ?? error) };
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const transport = !probe && target.mode === 'webdav' ? { pulled, pushed } : null;
|
|
426
|
+
const titles = await readTitles(target.syncDir).catch(() => new Map());
|
|
427
|
+
const logOutput = logLines(summary, transport, titles);
|
|
428
|
+
// The tooltip must explain exactly the number shown, so the list and the count
|
|
429
|
+
// come from the same source: transport files when there is a transport, else
|
|
430
|
+
// the session ids of the engine phase.
|
|
431
|
+
const uploaded = Number(transport?.pushed?.uploaded) || 0;
|
|
432
|
+
const downloaded = Number(transport?.pulled?.downloaded) || 0;
|
|
433
|
+
// The badge counts session files only (see sessionBadgeCounts); the lists below
|
|
434
|
+
// are filtered the same way so the tooltip explains exactly the number shown.
|
|
435
|
+
const sessionRels = (list) => (Array.isArray(list) ? list : [])
|
|
436
|
+
.filter((rel) => typeof rel === 'string' && rel.startsWith('sessions/'));
|
|
437
|
+
const upList = uploaded > 0
|
|
438
|
+
? sessionRels(transport?.pushed?.uploadedRels).map((rel) => describePath(rel, titles))
|
|
439
|
+
: (summary.sessions?.pushedIds ?? []).map((id) => `会话:${titles.get(id) ?? id}`);
|
|
440
|
+
const downList = downloaded > 0
|
|
441
|
+
? sessionRels(transport?.pulled?.downloadedRels).map((rel) => describePath(rel, titles))
|
|
442
|
+
: (summary.sessions?.pulledIds ?? []).map((id) => `会话:${titles.get(id) ?? id}`);
|
|
443
|
+
const delList = sessionRels(transport?.pushed?.deletedRels).map((rel) => describePath(rel, titles));
|
|
444
|
+
const counts = sessionBadgeCounts(transport, summary);
|
|
445
|
+
const countDetails = {
|
|
446
|
+
up: upList.slice(0, 60),
|
|
447
|
+
down: downList.slice(0, 60),
|
|
448
|
+
del: delList.slice(0, 60),
|
|
449
|
+
};
|
|
450
|
+
const record = {
|
|
451
|
+
at: new Date().toISOString(),
|
|
452
|
+
probe,
|
|
453
|
+
engine: 'js',
|
|
454
|
+
targetLabel: describeTarget(settings, target),
|
|
455
|
+
ok: summary.ok !== false && (pushed === null || pushed.ok !== false),
|
|
456
|
+
durationMs: Date.now() - startedAt,
|
|
457
|
+
summary,
|
|
458
|
+
trash,
|
|
459
|
+
transport,
|
|
460
|
+
syncDir: target.syncDir,
|
|
461
|
+
machineId: target.machineId,
|
|
462
|
+
log: logOutput.lines,
|
|
463
|
+
details: logOutput.details,
|
|
464
|
+
counts,
|
|
465
|
+
countDetails,
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
await writeJson(target.stateFile, record).catch(() => {});
|
|
469
|
+
await fsp.writeFile(target.logFile, record.log.join('\n'), 'utf8').catch(() => {});
|
|
470
|
+
await appendHistory(target.historyFile, record).catch(() => {});
|
|
471
|
+
return record;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** A short, user-chosen name for where this run sent its data. */
|
|
475
|
+
function describeTarget(settings, target) {
|
|
476
|
+
if (target.mode !== 'webdav') return '本地目录';
|
|
477
|
+
const url = typeof settings.webdavUrl === 'string' ? settings.webdavUrl.trim().replace(/\/+$/u, '') : '';
|
|
478
|
+
const rootPath = typeof settings.webdavRoot === 'string' ? settings.webdavRoot.trim() : '';
|
|
479
|
+
const presets = Array.isArray(settings.webdavProfiles) ? settings.webdavProfiles : [];
|
|
480
|
+
const match = presets.find((item) => item.url.replace(/\/+$/u, '') === url
|
|
481
|
+
&& (item.root ?? '').replace(/\/+$/u, '') === rootPath.replace(/\/+$/u, ''));
|
|
482
|
+
// Only a name the user chose is worth showing; the generated one is too long.
|
|
483
|
+
if (match !== undefined && match.custom === true && match.name.trim() !== '') return match.name;
|
|
484
|
+
return '';
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Keep the last 10 runs, newest first, each with a short log slice. */
|
|
488
|
+
async function appendHistory(file, record) {
|
|
489
|
+
const previous = (await readJson(file)) ?? [];
|
|
490
|
+
const list = Array.isArray(previous) ? previous : [];
|
|
491
|
+
if (list[0] !== undefined && list[0].at === record.at) list.shift();
|
|
492
|
+
list.unshift({
|
|
493
|
+
at: record.at,
|
|
494
|
+
targetLabel: record.targetLabel ?? '',
|
|
495
|
+
ok: record.ok,
|
|
496
|
+
probe: record.probe,
|
|
497
|
+
engine: 'js',
|
|
498
|
+
durationMs: record.durationMs,
|
|
499
|
+
trashPurged: record.trashPurged ?? 0,
|
|
500
|
+
pushed: record.summary?.sessions?.pushed ?? 0,
|
|
501
|
+
pulled: record.summary?.sessions?.pulled ?? 0,
|
|
502
|
+
uploaded: record.transport?.pushed?.uploaded ?? 0,
|
|
503
|
+
downloaded: record.transport?.pulled?.downloaded ?? 0,
|
|
504
|
+
deleted: record.transport?.pushed?.deleted ?? record.summary?.prune?.sharedDeleted ?? 0,
|
|
505
|
+
failed: (record.transport?.pushed?.failed?.length ?? 0) + (record.transport?.pulled?.failed?.length ?? 0),
|
|
506
|
+
paths: record.summary?.paths ?? null,
|
|
507
|
+
missing: record.summary?.missing ?? null,
|
|
508
|
+
log: Array.isArray(record.log) ? record.log.slice(-60) : [],
|
|
509
|
+
// File lists per log line, bounded so the history file stays small.
|
|
510
|
+
details: Array.isArray(record.details)
|
|
511
|
+
? record.details.map((files) => (Array.isArray(files) ? files.slice(0, 40) : []))
|
|
512
|
+
: [],
|
|
513
|
+
});
|
|
514
|
+
// Only the newest runs keep their file lists; older rows stay text-only.
|
|
515
|
+
const DETAIL_KEEP = 20;
|
|
516
|
+
for (let i = DETAIL_KEEP; i < list.length; i += 1) {
|
|
517
|
+
if (Object.prototype.hasOwnProperty.call(list[i], 'details')) delete list[i].details;
|
|
518
|
+
}
|
|
519
|
+
await writeJson(file, pruneHistory(list));
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** Keep the newest `HISTORY_CAP` runs; older ones are dropped. */
|
|
523
|
+
function pruneHistory(list) {
|
|
524
|
+
const kept = [];
|
|
525
|
+
for (const entry of list) {
|
|
526
|
+
if (!Number.isFinite(Date.parse(entry?.at ?? ''))) continue;
|
|
527
|
+
kept.push(entry);
|
|
528
|
+
if (kept.length >= HISTORY_CAP) break;
|
|
529
|
+
}
|
|
530
|
+
return kept;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** Recent runs, newest first. */
|
|
534
|
+
/**
|
|
535
|
+
* Record a one-way overwrite so it shows up in the log panel like a normal run.
|
|
536
|
+
*
|
|
537
|
+
* @param deps - resolved paths and settings.
|
|
538
|
+
* @param info - counters and log lines of the finished overwrite.
|
|
539
|
+
* @returns the record that was written.
|
|
540
|
+
*/
|
|
541
|
+
export async function recordOverwrite(deps, info) {
|
|
542
|
+
const { paths, settings } = deps;
|
|
543
|
+
const target = resolveSyncTarget(paths, settings);
|
|
544
|
+
const record = {
|
|
545
|
+
at: new Date().toISOString(),
|
|
546
|
+
kind: 'overwrite',
|
|
547
|
+
direction: info.direction,
|
|
548
|
+
ok: info.ok !== false,
|
|
549
|
+
durationMs: info.durationMs ?? 0,
|
|
550
|
+
pushed: Number(info.uploaded ?? 0),
|
|
551
|
+
pulled: Number(info.localized ?? 0),
|
|
552
|
+
deleted: Number(info.deleted ?? 0),
|
|
553
|
+
summary: {
|
|
554
|
+
ok: info.ok !== false,
|
|
555
|
+
kind: 'overwrite',
|
|
556
|
+
direction: info.direction,
|
|
557
|
+
sessions: { pushed: Number(info.uploaded ?? 0), pulled: 0 },
|
|
558
|
+
config: { copied: Number(info.copied ?? 0) },
|
|
559
|
+
transport: { uploaded: Number(info.uploaded ?? 0), deleted: Number(info.deleted ?? 0) },
|
|
560
|
+
},
|
|
561
|
+
log: Array.isArray(info.log) ? info.log : [],
|
|
562
|
+
};
|
|
563
|
+
await writeJson(target.stateFile, record).catch(() => {});
|
|
564
|
+
await appendHistory(target.historyFile, record).catch(() => {});
|
|
565
|
+
return record;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
export async function readSyncHistory(deps) {
|
|
569
|
+
const target = resolveSyncTarget(deps.paths, deps.settings);
|
|
570
|
+
const list = (await readJson(target.historyFile)) ?? [];
|
|
571
|
+
return Array.isArray(list) ? list : [];
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** Last recorded run, or null before the first one. */
|
|
575
|
+
export async function readSyncState(deps) {
|
|
576
|
+
const target = resolveSyncTarget(deps.paths, deps.settings);
|
|
577
|
+
return (await readJson(target.stateFile)) ?? null;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** Target description for the settings page. */
|
|
581
|
+
export async function inspectSyncTarget(deps) {
|
|
582
|
+
const target = resolveSyncTarget(deps.paths, deps.settings);
|
|
583
|
+
let syncDirExists = false;
|
|
584
|
+
if (target.syncDir !== '') {
|
|
585
|
+
try {
|
|
586
|
+
syncDirExists = (await fsp.stat(target.syncDir)).isDirectory();
|
|
587
|
+
} catch {
|
|
588
|
+
syncDirExists = false;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
let usage = null;
|
|
592
|
+
if (target.syncDir !== '' && syncDirExists) {
|
|
593
|
+
usage = await measureMirror(target.syncDir).catch(() => null);
|
|
594
|
+
}
|
|
595
|
+
return {
|
|
596
|
+
mode: target.mode,
|
|
597
|
+
engine: 'js',
|
|
598
|
+
usage,
|
|
599
|
+
script: 'js-engine',
|
|
600
|
+
scriptExists: true,
|
|
601
|
+
syncDir: target.syncDir,
|
|
602
|
+
machineId: target.machineId,
|
|
603
|
+
profile: target.profile,
|
|
604
|
+
syncDirExists,
|
|
605
|
+
syncDirConfigured: target.syncDir !== '',
|
|
606
|
+
enabled: deps.settings.syncEnabled === true,
|
|
607
|
+
};
|
|
608
|
+
}
|