dsh-gallery 0.11.2 → 0.12.1
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 +233 -0
- package/README.md +43 -10
- package/client.js +179 -52
- package/host/classify.js +70 -0
- package/host/constants.js +133 -0
- package/host/fsutil.js +136 -0
- package/host/groups.js +92 -0
- package/host/http.js +785 -0
- package/host/media.js +122 -0
- package/host/protocol.js +25 -0
- package/host/scan.js +531 -0
- package/host/session-index.js +187 -0
- package/host/session.js +192 -0
- package/host/settings.js +232 -0
- package/index.js +23 -1813
- package/package.json +8 -2
- package/session-index.js +7 -187
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话索引 —— 把「所有会话产出了哪些文件」建成一张表。
|
|
3
|
+
*
|
|
4
|
+
* 用途:让「全局资产」能按对话分组展示,而不是一堆乱七八糟的文件。
|
|
5
|
+
*
|
|
6
|
+
* 为什么需要缓存:
|
|
7
|
+
* 全量扫描 108 个会话日志(80 MB)实测耗时 1639 ms,
|
|
8
|
+
* 而画廊每 5 秒刷新一次 → 不可能每次都全量解压。
|
|
9
|
+
* 用「目录 mtime + 会话数」做键,没事就不重扫。
|
|
10
|
+
*
|
|
11
|
+
* 为什么用目录 mtime 而不是逐个文件:
|
|
12
|
+
* 108 个文件各 stat 一次也有开销;会话目录增多或日志追加时,
|
|
13
|
+
* 目录 mtime 会变,足够触发重扫。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { promises as fsp } from 'node:fs'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
|
|
19
|
+
/** 会话索引缓存:键是 sessionsDir,值是 { key, index }。 */
|
|
20
|
+
const sessionIndexCache = new Map()
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 扫出一个会话目录里的全部会话(含子会话)。
|
|
24
|
+
* @param sessionsDir - 会话根目录。
|
|
25
|
+
* @returns 会话目录信息数组。
|
|
26
|
+
*/
|
|
27
|
+
async function listSessionDirs(sessionsDir) {
|
|
28
|
+
const dirs = []
|
|
29
|
+
let groups
|
|
30
|
+
try {
|
|
31
|
+
groups = await fsp.readdir(sessionsDir, { withFileTypes: true })
|
|
32
|
+
} catch {
|
|
33
|
+
return dirs
|
|
34
|
+
}
|
|
35
|
+
for (const group of groups) {
|
|
36
|
+
if (!group.isDirectory()) continue
|
|
37
|
+
const gdir = path.join(sessionsDir, String(group.name))
|
|
38
|
+
let sessions
|
|
39
|
+
try {
|
|
40
|
+
sessions = await fsp.readdir(gdir, { withFileTypes: true })
|
|
41
|
+
} catch {
|
|
42
|
+
continue
|
|
43
|
+
}
|
|
44
|
+
for (const s of sessions) {
|
|
45
|
+
if (!s.isDirectory()) continue
|
|
46
|
+
const sdir = path.join(gdir, String(s.name))
|
|
47
|
+
const logPath = path.join(sdir, 'session.v4.jsonl.zstd')
|
|
48
|
+
try {
|
|
49
|
+
const st = await fsp.stat(logPath)
|
|
50
|
+
if (!st.isFile()) continue
|
|
51
|
+
dirs.push({
|
|
52
|
+
sessionId: String(s.name),
|
|
53
|
+
group: String(group.name),
|
|
54
|
+
sessionDir: sdir,
|
|
55
|
+
logPath,
|
|
56
|
+
logMtime: st.mtimeMs,
|
|
57
|
+
logSize: st.size,
|
|
58
|
+
})
|
|
59
|
+
} catch {
|
|
60
|
+
// 没有日志就跳过
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return dirs
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 从会话日志里提取标题。DSH 会写 `session/title` 事件。
|
|
69
|
+
* @param logText - 解压后的日志文本。
|
|
70
|
+
* @returns 标题字符串;没有则空串。
|
|
71
|
+
*/
|
|
72
|
+
function extractSessionTitle(logText) {
|
|
73
|
+
if (typeof logText !== 'string' || logText === '') return ''
|
|
74
|
+
// 取最后一个 title(用户可能改过标题)
|
|
75
|
+
let title = ''
|
|
76
|
+
for (const line of logText.split('\n')) {
|
|
77
|
+
if (!line.includes('session/title')) continue
|
|
78
|
+
let o
|
|
79
|
+
try { o = JSON.parse(line) } catch { continue }
|
|
80
|
+
if (o?.type !== 'session/title') continue
|
|
81
|
+
const t = o?.data?.title
|
|
82
|
+
if (typeof t === 'string' && t.trim() !== '') title = t.trim()
|
|
83
|
+
}
|
|
84
|
+
return title
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 从会话日志首行读元信息(创建时间、cwd、父会话)。
|
|
89
|
+
* @param logText - 解压后的日志文本。
|
|
90
|
+
* @returns { createdAt, cwd, parentSession }
|
|
91
|
+
*/
|
|
92
|
+
function extractSessionMeta(logText) {
|
|
93
|
+
const fallback = { createdAt: 0, cwd: '', parentSession: '' }
|
|
94
|
+
if (typeof logText !== 'string' || logText === '') return fallback
|
|
95
|
+
const firstLine = logText.split('\n')[0]
|
|
96
|
+
let o
|
|
97
|
+
try { o = JSON.parse(firstLine) } catch { return fallback }
|
|
98
|
+
return {
|
|
99
|
+
createdAt: typeof o?.createdAt === 'number' ? o.createdAt : 0,
|
|
100
|
+
cwd: typeof o?.cwd === 'string' ? o.cwd : '',
|
|
101
|
+
parentSession: typeof o?.parentSession === 'string' ? o.parentSession : '',
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 建立(或复用)会话索引。
|
|
107
|
+
*
|
|
108
|
+
* @param sessionsDir - 会话根目录。
|
|
109
|
+
* @param opts - resolveOptions 的结果(要用到 roots / readSessionLogText / extractAssetInfo)。
|
|
110
|
+
* @param deps - 依赖注入 { readSessionLogText, extractAssetInfo }。
|
|
111
|
+
* @returns Map<sessionId, { sessionId, title, createdAt, cwd, parentSession, files: Map<abs, category>, maxMtime }>
|
|
112
|
+
*/
|
|
113
|
+
export async function buildSessionIndex(sessionsDir, opts, deps) {
|
|
114
|
+
const { readSessionLogText, extractAssetInfo } = deps
|
|
115
|
+
|
|
116
|
+
// 缓存键:会话目录的 mtime + 当前会话数
|
|
117
|
+
let dirKey
|
|
118
|
+
try {
|
|
119
|
+
const allDirs = await listSessionDirs(sessionsDir)
|
|
120
|
+
dirKey = `${allDirs.length}|${allDirs.reduce((a, d) => Math.max(a, d.logMtime), 0)}`
|
|
121
|
+
const cached = sessionIndexCache.get(sessionsDir)
|
|
122
|
+
if (cached !== undefined && cached.key === dirKey) return cached.index
|
|
123
|
+
|
|
124
|
+
const index = new Map()
|
|
125
|
+
|
|
126
|
+
for (const d of allDirs) {
|
|
127
|
+
const logText = await readSessionLogText(d.logPath)
|
|
128
|
+
if (logText === '') continue
|
|
129
|
+
|
|
130
|
+
const meta = extractSessionMeta(logText)
|
|
131
|
+
const title = extractSessionTitle(logText)
|
|
132
|
+
// 传会话开始时间:用于区分「用户素材」和「会话期间产出」的分类
|
|
133
|
+
const assets = extractAssetInfo(logText, meta.createdAt)
|
|
134
|
+
|
|
135
|
+
// 只看落在扫描目录内的路径
|
|
136
|
+
const files = new Map()
|
|
137
|
+
let maxMtime = meta.createdAt
|
|
138
|
+
for (const [abs, info] of assets) {
|
|
139
|
+
let ownerRoot = null
|
|
140
|
+
for (const r of opts.roots) {
|
|
141
|
+
if (isInsidePath(r, abs)) { ownerRoot = r; break }
|
|
142
|
+
}
|
|
143
|
+
if (ownerRoot === null) continue
|
|
144
|
+
files.set(abs, info.category)
|
|
145
|
+
try {
|
|
146
|
+
const st = await fsp.stat(abs)
|
|
147
|
+
if (st.mtimeMs > maxMtime) maxMtime = st.mtimeMs
|
|
148
|
+
} catch {
|
|
149
|
+
// 文件已删除就跳过
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (files.size === 0) continue
|
|
154
|
+
|
|
155
|
+
index.set(d.sessionId, {
|
|
156
|
+
sessionId: d.sessionId,
|
|
157
|
+
title,
|
|
158
|
+
createdAt: meta.createdAt,
|
|
159
|
+
cwd: meta.cwd,
|
|
160
|
+
parentSession: meta.parentSession,
|
|
161
|
+
files,
|
|
162
|
+
maxMtime,
|
|
163
|
+
logMtime: d.logMtime,
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
sessionIndexCache.set(sessionsDir, { key: dirKey, index })
|
|
168
|
+
return index
|
|
169
|
+
} catch {
|
|
170
|
+
return new Map()
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** 路径是否在 root 内(避免循环依赖,这里内联一份最小实现)。 */
|
|
175
|
+
function isInsidePath(root, abs) {
|
|
176
|
+
const r = path.resolve(root)
|
|
177
|
+
const a = path.resolve(abs)
|
|
178
|
+
if (a === r) return true
|
|
179
|
+
return a.startsWith(r + path.sep)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 清空会话索引缓存(配置变化时调用)。
|
|
184
|
+
*/
|
|
185
|
+
export function clearSessionIndexCache() {
|
|
186
|
+
sessionIndexCache.clear()
|
|
187
|
+
}
|
package/host/session.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话日志读取:zstd 多帧、会话目录定位、子会话发现、路径收集。
|
|
3
|
+
*
|
|
4
|
+
* S1 拆分自 index.js(行为零变化)。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { promises as fsp, readFileSync, statSync, createReadStream } from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import { zstdDecompressSync } from 'node:zlib'
|
|
10
|
+
import { ZSTD_MAGIC } from './constants.js'
|
|
11
|
+
|
|
12
|
+
export const sessionLogCache = new Map()
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 解压一个会话日志。
|
|
16
|
+
* DSH 的 session.v4.jsonl.zstd 是「多帧 zstd 拼接」(每次追加写一帧),
|
|
17
|
+
* 单次 zstdDecompressSync 只能解第一帧,所以必须按魔数切开逐帧解。
|
|
18
|
+
* @param fullPath - 日志文件绝对路径。
|
|
19
|
+
* @returns 解压后的完整文本;失败返回空串。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export async function readSessionLogText(fullPath) {
|
|
23
|
+
let stat
|
|
24
|
+
let buf
|
|
25
|
+
try {
|
|
26
|
+
stat = await fsp.stat(fullPath)
|
|
27
|
+
const cacheKey = `${fullPath}|${stat.mtimeMs}|${stat.size}`
|
|
28
|
+
const cached = sessionLogCache.get(fullPath)
|
|
29
|
+
if (cached !== undefined && cached.key === cacheKey) return cached.text
|
|
30
|
+
buf = await fsp.readFile(fullPath)
|
|
31
|
+
} catch {
|
|
32
|
+
return ''
|
|
33
|
+
}
|
|
34
|
+
const offsets = []
|
|
35
|
+
let cursor = 0
|
|
36
|
+
while (cursor < buf.length) {
|
|
37
|
+
const hit = buf.indexOf(ZSTD_MAGIC, cursor)
|
|
38
|
+
if (hit < 0) break
|
|
39
|
+
offsets.push(hit)
|
|
40
|
+
cursor = hit + ZSTD_MAGIC.length
|
|
41
|
+
}
|
|
42
|
+
if (offsets.length === 0) return ''
|
|
43
|
+
const parts = []
|
|
44
|
+
for (const offset of offsets) {
|
|
45
|
+
try {
|
|
46
|
+
parts.push(zstdDecompressSync(buf.subarray(offset)))
|
|
47
|
+
} catch {
|
|
48
|
+
// 单帧损坏就跳过,不影响其余帧
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const text = Buffer.concat(parts).toString('utf8')
|
|
52
|
+
sessionLogCache.set(fullPath, { key: `${fullPath}|${stat.mtimeMs}|${stat.size}`, text })
|
|
53
|
+
// 缓存只留最近若干条,避免长跑后堆积
|
|
54
|
+
if (sessionLogCache.size > 8) {
|
|
55
|
+
const oldest = sessionLogCache.keys().next().value
|
|
56
|
+
if (oldest !== undefined) sessionLogCache.delete(oldest)
|
|
57
|
+
}
|
|
58
|
+
return text
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 在 ~/.dsh/sessions/<工作区分组>/<sessionId>/ 里定位某个会话目录。 */
|
|
62
|
+
|
|
63
|
+
export async function locateSessionDir(sessionsDir, sessionId) {
|
|
64
|
+
if (typeof sessionId !== 'string' || sessionId === '') return null
|
|
65
|
+
// 防御:会话 id 只可能是 [A-Za-z0-9._-],不许出现路径分隔符
|
|
66
|
+
if (/[\\/]/.test(sessionId) || sessionId.includes('..')) return null
|
|
67
|
+
let groups
|
|
68
|
+
try {
|
|
69
|
+
groups = await fsp.readdir(sessionsDir, { withFileTypes: true })
|
|
70
|
+
} catch {
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
for (const group of groups) {
|
|
74
|
+
if (!group.isDirectory()) continue
|
|
75
|
+
const candidate = path.join(sessionsDir, String(group.name), sessionId)
|
|
76
|
+
try {
|
|
77
|
+
const stat = await fsp.stat(candidate)
|
|
78
|
+
if (stat.isDirectory()) return candidate
|
|
79
|
+
} catch {
|
|
80
|
+
// 继续找下一个分组
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 找出某个会话的全部**子会话**目录(子智能体)。
|
|
88
|
+
*
|
|
89
|
+
* 修法 C:DSH 里子智能体是独立会话,有自己的 session 日志目录,
|
|
90
|
+
* 它的 write/present 调用**不出现在主会话日志里**。
|
|
91
|
+
* 所以「当前对话」必须把子会话的产出也算进去。
|
|
92
|
+
*
|
|
93
|
+
* 判定依据:子会话日志首行的 `parentSession` 字段指向主会话 id。
|
|
94
|
+
*
|
|
95
|
+
* @param sessionsDir - 会话根目录。
|
|
96
|
+
* @param parentSessionId - 主会话 id。
|
|
97
|
+
* @returns 子会话日志的绝对路径数组。
|
|
98
|
+
*/
|
|
99
|
+
|
|
100
|
+
export async function findSubSessionLogs(sessionsDir, parentSessionId) {
|
|
101
|
+
const result = []
|
|
102
|
+
if (typeof parentSessionId !== 'string' || parentSessionId === '') return result
|
|
103
|
+
let groups
|
|
104
|
+
try {
|
|
105
|
+
groups = await fsp.readdir(sessionsDir, { withFileTypes: true })
|
|
106
|
+
} catch {
|
|
107
|
+
return result
|
|
108
|
+
}
|
|
109
|
+
for (const group of groups) {
|
|
110
|
+
if (!group.isDirectory()) continue
|
|
111
|
+
let sessions
|
|
112
|
+
try {
|
|
113
|
+
sessions = await fsp.readdir(path.join(sessionsDir, String(group.name)), { withFileTypes: true })
|
|
114
|
+
} catch {
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
for (const s of sessions) {
|
|
118
|
+
if (!s.isDirectory()) continue
|
|
119
|
+
const logPath = path.join(sessionsDir, String(group.name), String(s.name), 'session.v4.jsonl.zstd')
|
|
120
|
+
try {
|
|
121
|
+
const st = await fsp.stat(logPath)
|
|
122
|
+
if (!st.isFile()) continue
|
|
123
|
+
} catch {
|
|
124
|
+
continue
|
|
125
|
+
}
|
|
126
|
+
// 读首行判断 parentSession;日志可能很大,只解第一帧就够(首行一定在第一帧)
|
|
127
|
+
const headText = await readSessionLogHead(logPath)
|
|
128
|
+
if (headText === '') continue
|
|
129
|
+
try {
|
|
130
|
+
const first = JSON.parse(headText.split('\n')[0])
|
|
131
|
+
if (first?.type === 'session' && first?.parentSession === parentSessionId) {
|
|
132
|
+
result.push(logPath)
|
|
133
|
+
}
|
|
134
|
+
} catch {
|
|
135
|
+
// 首行解析失败就跳过
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return result
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 只解压会话日志的第一帧,取首行(判断 parentSession 用,避免读整个 9MB 日志)。
|
|
144
|
+
* @param fullPath - 日志路径。
|
|
145
|
+
* @returns 首帧解出的文本;失败返回空串。
|
|
146
|
+
*/
|
|
147
|
+
|
|
148
|
+
export async function readSessionLogHead(fullPath) {
|
|
149
|
+
let buf
|
|
150
|
+
try {
|
|
151
|
+
buf = await fsp.readFile(fullPath)
|
|
152
|
+
} catch {
|
|
153
|
+
return ''
|
|
154
|
+
}
|
|
155
|
+
const hit = buf.indexOf(ZSTD_MAGIC, 0)
|
|
156
|
+
if (hit < 0) return ''
|
|
157
|
+
try {
|
|
158
|
+
return zstdDecompressSync(buf.subarray(hit)).toString('utf8')
|
|
159
|
+
} catch {
|
|
160
|
+
return ''
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 递归收集 JSON 节点里所有以盘符开头的字符串(工具的 path 参数)。 */
|
|
165
|
+
|
|
166
|
+
export function collectAbsolutePaths(node, sink) {
|
|
167
|
+
if (typeof node === 'string') {
|
|
168
|
+
if (/^[A-Za-z]:[\\/]/.test(node)) sink.push(node)
|
|
169
|
+
return
|
|
170
|
+
}
|
|
171
|
+
if (Array.isArray(node)) {
|
|
172
|
+
for (const entry of node) collectAbsolutePaths(entry, sink)
|
|
173
|
+
return
|
|
174
|
+
}
|
|
175
|
+
if (node !== null && typeof node === 'object') {
|
|
176
|
+
for (const key of Object.keys(node)) collectAbsolutePaths(node[key], sink)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 资产分类常量。
|
|
182
|
+
*
|
|
183
|
+
* 分类判据(按优先级,从高到低):
|
|
184
|
+
* 1. 被 `present` 声明过 → **最终资产**(正式交付物)
|
|
185
|
+
* 2. 只被 `read_image` 看过、从未被写入 → **输入资产**(用户给的参考图/资料)
|
|
186
|
+
* 3. 其余(write/edit/脚本产出/bash 提到) → **中间资产**
|
|
187
|
+
* 4. 会话日志里查不到任何记录 → **未归类**(历史文件,不能冒充「输入」)
|
|
188
|
+
*
|
|
189
|
+
* 为什么要有 UNKNOWN:早先版本把查不到归属的文件兜底成 input,
|
|
190
|
+
* 结果 4995 个历史文件全被标成「输入」,把真正的输入资产淹没了。
|
|
191
|
+
* 「不知道」就老老实实说不知道,不要瞎猜。
|
|
192
|
+
*/
|
package/host/settings.js
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 设置读写、根目录探测与校验、配置解析。
|
|
3
|
+
*
|
|
4
|
+
* S1 拆分自 index.js(行为零变化)。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { promises as fsp, readFileSync, statSync, createReadStream } from 'node:fs'
|
|
8
|
+
import os from 'node:os'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { DEFAULTS, DEFAULT_SETTINGS_FILE } from './constants.js'
|
|
11
|
+
import { arrayOfStrings, numberOr } from './fsutil.js'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* detectDefaultRoot 的探测结果缓存。
|
|
15
|
+
* 拆分注意点:这是模块级可变状态,必须与使用它的函数放在同一模块,
|
|
16
|
+
* 否则会报 `xxx is not defined`(S1 首次实测就踩了这个)。
|
|
17
|
+
*/
|
|
18
|
+
let defaultRootCache = null
|
|
19
|
+
|
|
20
|
+
export function detectDefaultRoot() {
|
|
21
|
+
if (defaultRootCache !== null) return defaultRootCache
|
|
22
|
+
|
|
23
|
+
const home = os.homedir()
|
|
24
|
+
const candidates = [
|
|
25
|
+
// 1. 用户主目录下
|
|
26
|
+
path.join(home, 'DSH产出'),
|
|
27
|
+
path.join(home, 'DSH-outputs'),
|
|
28
|
+
// 2. 文档下
|
|
29
|
+
path.join(home, 'Documents', 'DSH产出'),
|
|
30
|
+
path.join(home, 'Documents', 'DSH-outputs'),
|
|
31
|
+
// 3. 桌面下
|
|
32
|
+
path.join(home, 'Desktop', 'DSH产出'),
|
|
33
|
+
// 4. 下载目录下
|
|
34
|
+
path.join(home, 'Downloads', 'DSH产出'),
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
// 5. 遍历可用盘符(Windows):C:\DSH产出、D:\DSH产出 …… 不写死任何字母
|
|
38
|
+
if (process.platform === 'win32') {
|
|
39
|
+
for (let code = 67; code <= 90; code += 1) { // C(67) → Z(90)
|
|
40
|
+
const drive = String.fromCharCode(code) + ':'
|
|
41
|
+
candidates.push(path.join(drive + path.sep, 'DSH产出'))
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
for (const candidate of candidates) {
|
|
46
|
+
try {
|
|
47
|
+
if (statSync(candidate).isDirectory()) {
|
|
48
|
+
defaultRootCache = candidate
|
|
49
|
+
return candidate
|
|
50
|
+
}
|
|
51
|
+
} catch {
|
|
52
|
+
// 不存在就试下一个
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// 全都不存在:返回第一个候选,让面板显示「目录不存在」并给出修改入口
|
|
57
|
+
defaultRootCache = candidates[0]
|
|
58
|
+
return defaultRootCache
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 视频扩展名(与 DEFAULTS.mediaExtensions 里的音频部分相对)。 */
|
|
62
|
+
|
|
63
|
+
export function readSettingsFile(file) {
|
|
64
|
+
try {
|
|
65
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
66
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
|
|
67
|
+
} catch {
|
|
68
|
+
return {}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 读取「已隐藏」的相对路径集合。
|
|
74
|
+
* 隐藏只记录路径,不移动/删除文件;列表扫描时按此过滤。
|
|
75
|
+
* @param settingsFile - 配置文件路径。
|
|
76
|
+
* @returns 规范化(正斜杠)后的相对路径数组。
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
export async function readHiddenList(settingsFile) {
|
|
80
|
+
const stored = readSettingsFile(settingsFile)
|
|
81
|
+
if (!Array.isArray(stored.hidden)) return []
|
|
82
|
+
return stored.hidden
|
|
83
|
+
.filter((p) => typeof p === 'string' && p !== '')
|
|
84
|
+
.map((p) => p.replace(/\\/g, '/'))
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 解析最终配置。扫描目录(roots)的优先级(高 → 低):
|
|
89
|
+
* 1. 运行时配置文件的 roots 数组(面板内可加多个目录)
|
|
90
|
+
* 2. 运行时配置文件的 root(旧版单目录写法,兼容保留)
|
|
91
|
+
* 3. cordis.patch.yml 里配的 root / roots
|
|
92
|
+
* 4. 自动探测(detectDefaultRoot)
|
|
93
|
+
*
|
|
94
|
+
* 为什么支持多目录:DSH 一个会话一个 cwd,产出可能写在任意工作区下
|
|
95
|
+
* (例如 G:\DSH任务文件\xxx),不一定落在 G:\DSH产出。只配一个目录必然漏。
|
|
96
|
+
*/
|
|
97
|
+
|
|
98
|
+
export function resolveOptions(config) {
|
|
99
|
+
const merged = { ...DEFAULTS, ...(config ?? {}) }
|
|
100
|
+
const settingsFile = String(merged.settingsFile ?? DEFAULT_SETTINGS_FILE)
|
|
101
|
+
const stored = readSettingsFile(settingsFile)
|
|
102
|
+
|
|
103
|
+
// 收集所有候选目录
|
|
104
|
+
const collected = []
|
|
105
|
+
const pushRoot = (value) => {
|
|
106
|
+
if (typeof value === 'string' && value.trim() !== '') collected.push(value.trim())
|
|
107
|
+
}
|
|
108
|
+
const pushList = (value) => {
|
|
109
|
+
if (Array.isArray(value)) for (const v of value) pushRoot(v)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
pushList(stored.roots) // 1. 设置里的多目录
|
|
113
|
+
pushRoot(stored.root) // 2. 设置里的单目录(旧格式)
|
|
114
|
+
pushList(merged.roots) // 3. YAML 多目录
|
|
115
|
+
pushRoot(merged.root) // 4. YAML 单目录
|
|
116
|
+
|
|
117
|
+
// 去重(Windows 路径大小写不敏感)
|
|
118
|
+
const deduped = []
|
|
119
|
+
const seenRoots = new Set()
|
|
120
|
+
const candidates = collected.length > 0 ? collected : [detectDefaultRoot()]
|
|
121
|
+
for (const r of candidates) {
|
|
122
|
+
const abs = path.resolve(r)
|
|
123
|
+
const key = abs.toLowerCase()
|
|
124
|
+
if (seenRoots.has(key)) continue
|
|
125
|
+
seenRoots.add(key)
|
|
126
|
+
deduped.push(abs)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const resolvedRoots = deduped.length > 0 ? deduped : [path.resolve(detectDefaultRoot())]
|
|
130
|
+
const rootSource = collected.length === 0
|
|
131
|
+
? 'auto-detect'
|
|
132
|
+
: (typeof stored.root === 'string' || (Array.isArray(stored.roots) && stored.roots.length > 0) ? 'settings' : 'config')
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
root: resolvedRoots[0],
|
|
136
|
+
roots: resolvedRoots,
|
|
137
|
+
rootSource,
|
|
138
|
+
settingsFile,
|
|
139
|
+
windowHours: numberOr(merged.windowHours, DEFAULTS.windowHours, 1, 24 * 366),
|
|
140
|
+
maxItems: numberOr(merged.maxItems, DEFAULTS.maxItems, 1, 500),
|
|
141
|
+
maxDepth: numberOr(merged.maxDepth, DEFAULTS.maxDepth, 0, 8),
|
|
142
|
+
extensions: arrayOfStrings(merged.extensions, DEFAULTS.extensions).map((e) => e.toLowerCase()),
|
|
143
|
+
fileExtensions: arrayOfStrings(merged.fileExtensions, DEFAULTS.fileExtensions).map((e) => e.toLowerCase()),
|
|
144
|
+
mediaExtensions: arrayOfStrings(merged.mediaExtensions, DEFAULTS.mediaExtensions).map((e) => e.toLowerCase()),
|
|
145
|
+
skipDirs: arrayOfStrings(merged.skipDirs, DEFAULTS.skipDirs).map((e) => e.toLowerCase()),
|
|
146
|
+
maxDirectories: numberOr(merged.maxDirectories, DEFAULTS.maxDirectories, 1, 200000),
|
|
147
|
+
maxEntries: numberOr(merged.maxEntries, DEFAULTS.maxEntries, 1, 1000000),
|
|
148
|
+
maxImageBytes: numberOr(merged.maxImageBytes, DEFAULTS.maxImageBytes, 1, 512 * 1024 * 1024),
|
|
149
|
+
maxMediaBytes: numberOr(merged.maxMediaBytes, DEFAULTS.maxMediaBytes, 1, 1024 * 1024 * 1024),
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function validateRootCandidate(candidate) {
|
|
154
|
+
if (typeof candidate !== 'string' || candidate.trim() === '') {
|
|
155
|
+
return { ok: false, reason: 'empty' }
|
|
156
|
+
}
|
|
157
|
+
const raw = candidate.trim()
|
|
158
|
+
// 只接受绝对路径(盘符或 UNC),相对路径无法确定含义
|
|
159
|
+
if (!path.isAbsolute(raw)) return { ok: false, reason: 'not-absolute' }
|
|
160
|
+
const resolved = path.resolve(raw)
|
|
161
|
+
try {
|
|
162
|
+
const st = await fsp.stat(resolved)
|
|
163
|
+
if (!st.isDirectory()) return { ok: false, reason: 'not-directory' }
|
|
164
|
+
} catch {
|
|
165
|
+
return { ok: false, reason: 'not-found' }
|
|
166
|
+
}
|
|
167
|
+
return { ok: true, root: resolved }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 把设置写进运行时配置文件。
|
|
172
|
+
* 只覆盖传入的字段,其余保留——避免把 windowHours 之类顺手清掉。
|
|
173
|
+
* @param settingsFile - 配置文件路径。
|
|
174
|
+
* @param patch - 要合并进去的部分设置。
|
|
175
|
+
*/
|
|
176
|
+
|
|
177
|
+
export async function writeSettingsFile(settingsFile, patch) {
|
|
178
|
+
const current = readSettingsFile(settingsFile)
|
|
179
|
+
const next = { ...current, ...patch }
|
|
180
|
+
await fsp.mkdir(path.dirname(settingsFile), { recursive: true })
|
|
181
|
+
await fsp.writeFile(settingsFile, JSON.stringify(next, null, 2), 'utf8')
|
|
182
|
+
return next
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* 返回设置面板需要的全部信息。
|
|
187
|
+
* @param config - 插件配置。
|
|
188
|
+
*/
|
|
189
|
+
|
|
190
|
+
export async function readSettingsPayload(config) {
|
|
191
|
+
const opts = resolveOptions(config)
|
|
192
|
+
// 逐个检查每个 root 是否存在
|
|
193
|
+
const rootsInfo = []
|
|
194
|
+
for (const r of opts.roots) {
|
|
195
|
+
let exists = false
|
|
196
|
+
try {
|
|
197
|
+
exists = (await fsp.stat(r)).isDirectory()
|
|
198
|
+
} catch {
|
|
199
|
+
exists = false
|
|
200
|
+
}
|
|
201
|
+
rootsInfo.push({ path: r, exists })
|
|
202
|
+
}
|
|
203
|
+
const exists = rootsInfo.length > 0 ? rootsInfo[0].exists : false
|
|
204
|
+
// 已隐藏条数:供设置面板显示「已隐藏 N 个 · 全部恢复」
|
|
205
|
+
const hidden = await readHiddenList(opts.settingsFile)
|
|
206
|
+
return {
|
|
207
|
+
root: opts.root,
|
|
208
|
+
roots: opts.roots,
|
|
209
|
+
rootsInfo,
|
|
210
|
+
rootSource: opts.rootSource,
|
|
211
|
+
rootExists: exists,
|
|
212
|
+
settingsFile: opts.settingsFile,
|
|
213
|
+
windowHours: opts.windowHours,
|
|
214
|
+
maxItems: opts.maxItems,
|
|
215
|
+
maxDepth: opts.maxDepth,
|
|
216
|
+
hiddenCount: hidden.length,
|
|
217
|
+
// 前若干条隐藏项,供面板预览(不返回全部,避免配置很大时拖慢)
|
|
218
|
+
hiddenSample: hidden.slice(0, 10),
|
|
219
|
+
defaults: {
|
|
220
|
+
// 给前端「恢复默认」用:自动探测的结果
|
|
221
|
+
root: path.resolve(detectDefaultRoot()),
|
|
222
|
+
},
|
|
223
|
+
home: os.homedir(),
|
|
224
|
+
platform: process.platform,
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 会话日志解压结果的缓存。
|
|
230
|
+
* 自动刷新每 5 秒一次,而一个活跃会话的日志解压后有 9MB 以上;
|
|
231
|
+
* 用「路径 + mtime + size」做键,日志没变就复用上次的解析结果。
|
|
232
|
+
*/
|