dsh-gallery 0.15.0 → 0.16.2

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.
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Windows 系统剪贴板「文件列表」(CF_HDROP / FileDropList)读写。
3
+ *
4
+ * 为什么需要:Chromium 的 paste 事件对「资源管理器里 Ctrl+C 的文件」**不给
5
+ * file item**(浏览器安全限制,文件只能来自拖放或 <input type=file>),所以
6
+ * 纯前端永远粘不到音视频 / DWG / ZIP 等任意文件。而 PowerShell 5.1 自带
7
+ * Get-Clipboard -Format FileDropList / Set-Clipboard -LiteralPath
8
+ * 能直接读写系统剪贴板的文件列表,且不需要 Add-Type 动态编译 .NET。
9
+ *
10
+ * 编码约定(实测踩坑):
11
+ * · 命令一律走 -EncodedCommand(UTF-16LE base64),避免命令行里的中文/引号被拆;
12
+ * · 路径列表经 **UTF-8 临时文件** 往返,绝不从 stdout 取中文路径
13
+ * (PowerShell 控制台默认 OEM/GBK 代码页,中文会乱码);
14
+ * · 单次调用 9 秒超时,任何异常都降级为「插件内部剪贴板」,不让功能整体失败。
15
+ *
16
+ * 非 Windows 平台不调 PowerShell,直接使用内部剪贴板(复制→粘贴仍闭环)。
17
+ */
18
+
19
+ import { spawn } from 'node:child_process'
20
+ import { promises as fsp } from 'node:fs'
21
+ import os from 'node:os'
22
+ import path from 'node:path'
23
+
24
+ import { bumpName } from './derive.js'
25
+
26
+ const PS_TIMEOUT_MS = 9000
27
+
28
+ /**
29
+ * 系统剪贴板不可用时的进程内兜底;同一 DSH 实例下所有对话共享。
30
+ * 带时间戳:只在写入后 10 分钟内有效,避免之后复制了纯文本却「幽灵粘贴」旧资产。
31
+ */
32
+ const INTERNAL_TTL_MS = 10 * 60 * 1000
33
+ let internalClipboard = { paths: [], at: 0 }
34
+
35
+ /** PowerShell 单引号字符串字面量(单引号加倍即可转义)。 */
36
+ function psQuote(value) {
37
+ return "'" + String(value).replace(/'/g, "''") + "'"
38
+ }
39
+
40
+ function encodedCommand(script) {
41
+ // PowerShell -EncodedCommand 要求 UTF-16LE 的 base64
42
+ return Buffer.from(script, 'utf16le').toString('base64')
43
+ }
44
+
45
+ function runPowerShell(script) {
46
+ return new Promise((resolve, reject) => {
47
+ let out = ''
48
+ let err = ''
49
+ let settled = false
50
+ let child
51
+ try {
52
+ child = spawn('powershell.exe', [
53
+ '-NoProfile', '-NonInteractive', '-STA',
54
+ '-EncodedCommand', encodedCommand(script),
55
+ ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
56
+ } catch (error) {
57
+ reject(error)
58
+ return
59
+ }
60
+ const finish = (fn, value) => {
61
+ if (settled) return
62
+ settled = true
63
+ fn(value)
64
+ }
65
+ const timer = setTimeout(() => {
66
+ try { child.kill() } catch { /* 已退出 */ }
67
+ finish(reject, new Error('PowerShell 调用超时(9s)'))
68
+ }, PS_TIMEOUT_MS)
69
+ child.stdout?.on('data', (chunk) => { out += String(chunk) })
70
+ child.stderr?.on('data', (chunk) => { err += String(chunk) })
71
+ child.on('error', (error) => {
72
+ clearTimeout(timer)
73
+ finish(reject, error)
74
+ })
75
+ child.on('close', (code) => {
76
+ clearTimeout(timer)
77
+ if (code === 0) finish(resolve, out)
78
+ else finish(reject, new Error('PowerShell exit ' + code + ': ' + err.slice(-600)))
79
+ })
80
+ })
81
+ }
82
+
83
+ function tmpFile(tag) {
84
+ return path.join(
85
+ os.tmpdir(),
86
+ 'dsh-gallery-' + tag + '-' + process.pid + '-' +
87
+ Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 7) + '.txt',
88
+ )
89
+ }
90
+
91
+ /**
92
+ * 读系统剪贴板里的文件绝对路径列表。
93
+ * 剪贴板没有文件列表 / PowerShell 不可用时返回 [](不抛)。
94
+ * @returns {Promise<string[]>}
95
+ */
96
+ export async function readClipboardFilePaths() {
97
+ if (process.platform !== 'win32') return []
98
+ const outFile = tmpFile('clipread')
99
+ const script = [
100
+ "$ErrorActionPreference = 'Stop'",
101
+ '$items = @()',
102
+ 'try {',
103
+ // 🔴 不能用 `Get-Clipboard | ForEach-Object`:cmdlet 把整个 List<PSObject>
104
+ // 作为**单个**管道对象输出,[string] 转换会把多路径空格拼成一行。
105
+ // 先接住集合再 foreach 逐项展开,才是真的多文件。
106
+ ' $raw = Get-Clipboard -Format FileDropList -ErrorAction Stop',
107
+ ' if ($null -ne $raw) { foreach ($x in $raw) { $items += [string]$x } }',
108
+ '} catch { $items = @() }',
109
+ '[System.IO.File]::WriteAllLines(' + psQuote(outFile) + ', [string[]]$items, (New-Object System.Text.UTF8Encoding($false)))',
110
+ ].join('\n')
111
+ try {
112
+ await runPowerShell(script)
113
+ const text = await fsp.readFile(outFile, 'utf8')
114
+ const lines = text.split(/\r?\n/).map((s) => s.trim()).filter((s) => s !== '')
115
+ return [...new Set(lines)]
116
+ } catch {
117
+ return []
118
+ } finally {
119
+ try { await fsp.rm(outFile, { force: true }) } catch { /* 忽略 */ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * 把文件绝对路径列表写入系统剪贴板(可在资源管理器 / 其它应用 Ctrl+V)。
125
+ * 失败时退化为插件内部剪贴板,保证「复制 → 粘贴」仍然闭环。
126
+ * @param {string[]} paths
127
+ * @returns {Promise<{ ok: boolean, count: number, mode: string }>}
128
+ */
129
+ export async function writeClipboardFilePaths(paths) {
130
+ const cleaned = [...new Set((Array.isArray(paths) ? paths : [])
131
+ .map((p) => String(p ?? '').trim()).filter((p) => p !== ''))]
132
+ if (cleaned.length === 0) return { ok: false, count: 0, mode: 'none' }
133
+
134
+ // 无论系统剪贴板是否成功,都写一份内部兜底
135
+ internalClipboard = { paths: cleaned, at: Date.now() }
136
+ if (process.platform !== 'win32') {
137
+ return { ok: true, count: cleaned.length, mode: 'internal' }
138
+ }
139
+
140
+ const inFile = tmpFile('clipwrite')
141
+ const script = [
142
+ "$ErrorActionPreference = 'Stop'",
143
+ '$lines = @([System.IO.File]::ReadAllLines(' + psQuote(inFile) + ', [System.Text.Encoding]::UTF8) | Where-Object { $_ -ne \'\' })',
144
+ "if ($lines.Count -eq 0) { exit 3 }",
145
+ 'Set-Clipboard -LiteralPath $lines -ErrorAction Stop',
146
+ "Write-Output 'OK'",
147
+ ].join('\n')
148
+ try {
149
+ await fsp.writeFile(inFile, cleaned.join('\n'), 'utf8')
150
+ await runPowerShell(script)
151
+ return { ok: true, count: cleaned.length, mode: 'system' }
152
+ } catch {
153
+ return { ok: true, count: cleaned.length, mode: 'internal' }
154
+ } finally {
155
+ try { await fsp.rm(inFile, { force: true }) } catch { /* 忽略 */ }
156
+ }
157
+ }
158
+
159
+ /** 内部剪贴板(系统剪贴板读不到文件列表时的兜底,10 分钟内有效)。 */
160
+ export function internalClipboardPaths() {
161
+ if (Date.now() - internalClipboard.at > INTERNAL_TTL_MS) return []
162
+ return internalClipboard.paths.slice()
163
+ }
164
+
165
+ /**
166
+ * 把剪贴板里的文件批量复制进目标目录(当前对话目录)。
167
+ *
168
+ * 口径与 http.js 的 `pasteFile` 单文件版完全一致:2GB 上限、只收文件、
169
+ * 重名时 `<名>-n.<扩展名>` 自增(**绝不覆盖已有文件**)、返回 roots 相对路径。
170
+ * 抽成独立模块是为了能用真实临时目录做端到端测试(http.js 的 op 路由不便直调)。
171
+ *
172
+ * @param {string[]} srcPaths 源文件绝对路径
173
+ * @param {string} dir 目标目录(当前对话目录)
174
+ * @param {string} root 扫描根目录,用于算 relPath;可为空
175
+ * @returns {Promise<{ files: {name:string, absPath:string, relPath:string}[], failed: {path:string, message:string}[] }>}
176
+ */
177
+ export async function pasteFilesIntoDir(srcPaths, dir, root = '') {
178
+ const okFiles = []
179
+ const failed = []
180
+ try { await fsp.mkdir(dir, { recursive: true }) } catch { /* 下面 copyFile 会给真实错误 */ }
181
+ const list = Array.isArray(srcPaths) ? srcPaths.slice(0, 200) : []
182
+ for (const raw of list) {
183
+ const srcAbs = path.resolve(String(raw ?? '').replace(/\\/g, '/'))
184
+ try {
185
+ const st = await fsp.stat(srcAbs)
186
+ if (!st.isFile()) throw new Error('源路径不是文件')
187
+ if (st.size > 2 * 1024 * 1024 * 1024) throw new Error('文件超过 2 GB,粘贴被拒绝')
188
+ const base = path.basename(srcAbs).replace(/[\\/:*?"<>|\r\n\t]/g, '_').trim() || 'file'
189
+ // 重名自增(与 http.js 内联的 uniqueName 同口径)
190
+ let name = base
191
+ let abs = path.join(dir, name)
192
+ for (let n = 2; n <= 999; n += 1) {
193
+ let exists = true
194
+ try { await fsp.access(abs) } catch { exists = false }
195
+ if (!exists) break
196
+ name = bumpName(base, n)
197
+ abs = path.join(dir, name)
198
+ }
199
+ await fsp.copyFile(srcAbs, abs)
200
+ // 🔴 Windows 的 CopyFile 会**保留源文件 mtime**(Linux 不会)。画廊 global 视图按
201
+ // mtime 时间窗过滤,保留旧 mtime 会让「刚粘进来的旧素材」在全局视图里根本看不到。
202
+ // 粘贴语义是「现在进入本对话」,所以统一把落盘文件的时间戳刷成当前时间。
203
+ try { const now = new Date(); await fsp.utimes(abs, now, now) } catch { /* 时间戳失败不影响粘贴 */ }
204
+ const relPath = root === '' ? '' : path.relative(root, abs).split(path.sep).join('/')
205
+ okFiles.push({ name, absPath: abs, relPath })
206
+ } catch (error) {
207
+ failed.push({ path: srcAbs, message: String(error?.message ?? error) })
208
+ }
209
+ }
210
+ return { files: okFiles, failed }
211
+ }
package/host/derive.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * v0.16.0 派生资产相关的纯函数(无副作用、可单测)。
3
+ * 粘贴 / 裁剪产出的文件名与 PNG 校验都走这里,避免逻辑散落。
4
+ */
5
+
6
+ /**
7
+ * 派生资产命名:`<前缀>_<时间戳>[-n].<ext>`。
8
+ * 时间戳用本地可读串(非冒号,避免 Windows 文件名非法),重复时加 -n 由调用方决定。
9
+ * @param {string} prefix 前缀(如「粘贴」「裁剪-原图名」)
10
+ * @param {string} ext 扩展名(不含点)
11
+ * @param {string} suffix 重名后缀(如 `-2`)
12
+ */
13
+ export function makeDerivedName(prefix, ext, suffix = '') {
14
+ const safe = String(prefix).replace(/[\\/:*?"<>|\r\n\t]/g, '_').replace(/\s+/g, ' ').trim().slice(0, 60) || 'asset'
15
+ const d = new Date()
16
+ const pad = (n) => String(n).padStart(2, '0')
17
+ const ts = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
18
+ const e = String(ext || 'png').replace(/[^a-z0-9]/gi, '').toLowerCase().slice(0, 6) || 'png'
19
+ return `${safe}_${ts}${suffix}.${e}`
20
+ }
21
+
22
+ /**
23
+ * 文件名重名时的自增:在 stem 后追加 `-2 / -3 …`,保留扩展名。
24
+ * @param {string} base 原始文件名
25
+ * @param {number} n 自增序号(>=2)
26
+ */
27
+ export function bumpName(base, n) {
28
+ const dot = base.lastIndexOf('.')
29
+ const stem = dot > 0 ? base.slice(0, dot) : base
30
+ const ext = dot > 0 ? base.slice(dot) : ''
31
+ return `${stem}-${n}${ext}`
32
+ }
33
+
34
+ /**
35
+ * 原子写用的临时路径:**必须保留扩展名**。
36
+ *
37
+ * 🔴 ffmpeg 靠扩展名推断输出容器。写成 `xxx.mp4.tmp-123` 会直接报
38
+ * "Unable to choose an output format" → HTTP 500(2026-11-13 12:15 真机实测,
39
+ * 视频和音频同时失败)。随机串必须放在扩展名**之前**:`xxx.tmp-123.mp4`。
40
+ *
41
+ * @param {string} abs 最终绝对路径
42
+ * @param {string} tag 区分并发的标记(默认 pid-时间戳)
43
+ */
44
+ export function tmpPathFor(abs, tag = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`) {
45
+ const s = String(abs)
46
+ const dot = s.lastIndexOf('.')
47
+ const slash = Math.max(s.lastIndexOf('/'), s.lastIndexOf('\\'))
48
+ // 点必须在最后一个路径分隔符之后才算扩展名,否则目录名里的点会误判
49
+ if (dot <= slash + 1) return `${s}.tmp-${tag}`
50
+ return `${s.slice(0, dot)}.tmp-${tag}${s.slice(dot)}`
51
+ }
52
+
53
+ /**
54
+ * PNG 合法性校验 + base64 解码;非法(空 / 超 24MB / 非 PNG 魔数)返回 null。
55
+ * @param {string} data base64 字符串
56
+ */
57
+ export function pngBufferFrom(data) {
58
+ const buf = Buffer.from(data, 'base64')
59
+ if (buf.length < 8 || buf.length > 24 * 1024 * 1024) return null
60
+ if (!(buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47)) return null
61
+ return buf
62
+ }