@andy.ian/dsh-homing 2.3.1 → 2.3.3
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/index.js +79 -14
- package/lib/files-page.mjs +59 -7
- package/lib/files-preview.js +40 -0
- package/lib/files.mjs +68 -0
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -45,7 +45,7 @@ import { probeVnc } from './lib/vnc-probe.mjs';
|
|
|
45
45
|
import { WebSocketServer } from './lib/vendor/ws/wrapper.mjs';
|
|
46
46
|
import { renderVncPage } from './lib/vnc-page.mjs';
|
|
47
47
|
import { customShells, detectShells, resolveShell, DEFAULT_SHELL } from './lib/shells.mjs';
|
|
48
|
-
import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage } from './lib/files-page.mjs';
|
|
48
|
+
import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage, renderWallPage } from './lib/files-page.mjs';
|
|
49
49
|
import { checkUnsafeOrigin, checkOwnPageWrite } from './lib/csrf.mjs';
|
|
50
50
|
import { validateOpenPath } from './lib/guard.mjs';
|
|
51
51
|
import { opensslExe, sshExe } from './lib/exec-path.mjs';
|
|
@@ -1757,6 +1757,14 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1757
1757
|
return;
|
|
1758
1758
|
}
|
|
1759
1759
|
|
|
1760
|
+
// 图片预览页的手势脚本(左右滑动切换上一张/下一张)
|
|
1761
|
+
if (url.pathname === '/dsh_homing/files-preview.js' && req.method === 'GET') {
|
|
1762
|
+
const js = fs.readFileSync(new URL('./lib/files-preview.js', import.meta.url), 'utf8');
|
|
1763
|
+
res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
|
1764
|
+
res.end(js);
|
|
1765
|
+
return;
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1760
1768
|
// 开机自启:页面上的"启用 / 以后再说"
|
|
1761
1769
|
if (url.pathname === '/dsh_homing/autostart' && req.method === 'POST') {
|
|
1762
1770
|
const form = new URLSearchParams(await readBody(req, 4096));
|
|
@@ -2164,6 +2172,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2164
2172
|
// 必须在未登录时也能加载与上报
|
|
2165
2173
|
|| url.pathname === '/dsh_homing/auth-state' || url.pathname === '/dsh_homing/auth-guard.js'
|
|
2166
2174
|
|| url.pathname === '/dsh_homing/idb-fallback.js'
|
|
2175
|
+
|| url.pathname === '/dsh_homing/files-preview.js'
|
|
2167
2176
|
|| url.pathname === '/dsh_homing/client-report.js' || url.pathname === '/dsh_homing/client-error'
|
|
2168
2177
|
// 图标与 manifest 是浏览器自动抓的,挡掉只会让登录页看起来坏掉、并在审计里刷噪音
|
|
2169
2178
|
|| url.pathname === '/manifest.webmanifest' || url.pathname === '/apple-touch-icon.png'
|
|
@@ -3051,7 +3060,7 @@ a{color:#8ab4f8}
|
|
|
3051
3060
|
return;
|
|
3052
3061
|
}
|
|
3053
3062
|
|
|
3054
|
-
if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/pdf' || url.pathname === '/files/download' || url.pathname === '/files/raw' || url.pathname === '/files/compress' || url.pathname === '/files/run'
|
|
3063
|
+
if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/wall' || url.pathname === '/files/pdf' || url.pathname === '/files/download' || url.pathname === '/files/raw' || url.pathname === '/files/compress' || url.pathname === '/files/run'
|
|
3055
3064
|
|| url.pathname === '/files/rename'
|
|
3056
3065
|
|| url.pathname === '/files/delete' || url.pathname === '/files/paste'
|
|
3057
3066
|
|| url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
|
|
@@ -3160,20 +3169,12 @@ a{color:#8ab4f8}
|
|
|
3160
3169
|
return;
|
|
3161
3170
|
}
|
|
3162
3171
|
|
|
3163
|
-
// Markdown
|
|
3172
|
+
// 图片内联返回(Markdown 相对图片 + 文件页图片预览都用它)。
|
|
3173
|
+
// 白名单与 MIME 由 lib/files.mjs 统一维护;SVG 故意不收(同源内联会执行脚本)。
|
|
3164
3174
|
if (url.pathname === '/files/raw' && req.method === 'GET') {
|
|
3165
3175
|
const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
|
|
3166
|
-
const
|
|
3167
|
-
|
|
3168
|
-
'.jpg': 'image/jpeg',
|
|
3169
|
-
'.jpeg': 'image/jpeg',
|
|
3170
|
-
'.gif': 'image/gif',
|
|
3171
|
-
'.webp': 'image/webp',
|
|
3172
|
-
'.bmp': 'image/bmp',
|
|
3173
|
-
};
|
|
3174
|
-
const ext = path.extname(target).toLowerCase();
|
|
3175
|
-
const contentType = typeByExt[ext];
|
|
3176
|
-
if (contentType === undefined) {
|
|
3176
|
+
const contentType = filebrowse.imageMimeOf(target);
|
|
3177
|
+
if (contentType === null) {
|
|
3177
3178
|
res.writeHead(415, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
3178
3179
|
res.end('不支持的图片格式\n');
|
|
3179
3180
|
return;
|
|
@@ -3252,6 +3253,43 @@ a{color:#8ab4f8}
|
|
|
3252
3253
|
return;
|
|
3253
3254
|
}
|
|
3254
3255
|
|
|
3256
|
+
// 图片墙:把某目录(递归)里的图片铺成缩略图网格。
|
|
3257
|
+
// 支持 ?path=目录;也支持 ?session=<会话 id>,由插件映射到该会话所属工作区目录,
|
|
3258
|
+
// 方便从 DSH 会话菜单一键进来(手机上看截图/设计稿更顺手)。
|
|
3259
|
+
if (url.pathname === '/files/wall' && req.method === 'GET') {
|
|
3260
|
+
const dshHome = path.resolve(dataDir(), '..', '..');
|
|
3261
|
+
const session = url.searchParams.get('session') ?? '';
|
|
3262
|
+
const askedPath = url.searchParams.get('path') ?? '';
|
|
3263
|
+
let dir = askedPath === '' ? '' : filebrowse.resolvePath(askedPath);
|
|
3264
|
+
if (dir === '' && session !== '') {
|
|
3265
|
+
dir = filebrowse.workspacePathForSessionId(dshHome, session) ?? filebrowse.sessionCwdById(dshHome, session) ?? '';
|
|
3266
|
+
}
|
|
3267
|
+
if (dir === '') dir = filebrowse.workspaceIndex(dshHome).defaultPath ?? '';
|
|
3268
|
+
if (dir === '') {
|
|
3269
|
+
// 没有任何可定位的目录:不递归扫 HOME(那里图片太多、还可能很慢),给出明确提示
|
|
3270
|
+
appendAudit(dir, 'file-wall', { path: '', images: 0, ok: false });
|
|
3271
|
+
sendHtml(renderWallPage({
|
|
3272
|
+
dir: '',
|
|
3273
|
+
images: [],
|
|
3274
|
+
message: '没有找到可浏览的工作区目录。请从文件页(含目录路径)或会话菜单进入。',
|
|
3275
|
+
isError: true,
|
|
3276
|
+
session,
|
|
3277
|
+
}));
|
|
3278
|
+
return;
|
|
3279
|
+
}
|
|
3280
|
+
const listed = filebrowse.listImages(dir);
|
|
3281
|
+
appendAudit(dir, 'file-wall', { path: dir, images: listed.ok ? listed.images.length : 0, ok: listed.ok });
|
|
3282
|
+
sendHtml(renderWallPage({
|
|
3283
|
+
dir: listed.ok ? listed.dir : dir,
|
|
3284
|
+
images: listed.ok ? listed.images : [],
|
|
3285
|
+
truncated: listed.ok && listed.truncated === true,
|
|
3286
|
+
message: listed.ok ? '' : String(listed.error),
|
|
3287
|
+
isError: !listed.ok,
|
|
3288
|
+
session,
|
|
3289
|
+
}));
|
|
3290
|
+
return;
|
|
3291
|
+
}
|
|
3292
|
+
|
|
3255
3293
|
if (url.pathname === '/files/view' && req.method === 'GET') {
|
|
3256
3294
|
const asked = url.searchParams.get('path') ?? '';
|
|
3257
3295
|
if (office.isOfficeFile(asked) || office.isPdfFile(asked)) {
|
|
@@ -3259,6 +3297,33 @@ a{color:#8ab4f8}
|
|
|
3259
3297
|
res.end();
|
|
3260
3298
|
return;
|
|
3261
3299
|
}
|
|
3300
|
+
// 图片:直接渲染预览页(文件列表里点图片名就走这里);字节由 /files/raw 内联返回,
|
|
3301
|
+
// 并把同目录的上一张/下一张一起算好,配合 files-preview.js 支持左右滑动切换。
|
|
3302
|
+
if (filebrowse.isImageFile(asked)) {
|
|
3303
|
+
const target = filebrowse.resolvePath(asked);
|
|
3304
|
+
let stat = null;
|
|
3305
|
+
try { stat = fs.statSync(target); } catch { stat = null; }
|
|
3306
|
+
let info = stat !== null && stat.isFile()
|
|
3307
|
+
? { path: target, sizeText: filebrowse.fmtSize(stat.size), mtime: filebrowse.fmtTime(stat.mtime), image: true }
|
|
3308
|
+
: { path: target, error: '文件不存在' };
|
|
3309
|
+
if (info.image === true) {
|
|
3310
|
+
// 目录一定存在(target 是刚 stat 成功的文件),listImages 失败时返回空数组
|
|
3311
|
+
const siblings = filebrowse.listImages(path.dirname(target));
|
|
3312
|
+
const images = siblings.images;
|
|
3313
|
+
const index = images.findIndex((item) => item.path === target);
|
|
3314
|
+
if (index >= 0) {
|
|
3315
|
+
info = {
|
|
3316
|
+
...info,
|
|
3317
|
+
position: `${index + 1} / ${images.length}`,
|
|
3318
|
+
prevHref: index > 0 ? '/files/view?path=' + encodeURIComponent(images[index - 1].path) : '',
|
|
3319
|
+
nextHref: index < images.length - 1 ? '/files/view?path=' + encodeURIComponent(images[index + 1].path) : '',
|
|
3320
|
+
};
|
|
3321
|
+
}
|
|
3322
|
+
}
|
|
3323
|
+
appendAudit(dir, 'file-view', { path: target, kind: 'image', ok: info.image === true });
|
|
3324
|
+
sendHtml(renderFileView({ info }));
|
|
3325
|
+
return;
|
|
3326
|
+
}
|
|
3262
3327
|
const info = filebrowse.readTextFile(asked);
|
|
3263
3328
|
const raw = url.searchParams.get('raw') === '1';
|
|
3264
3329
|
if (!raw && info.text !== undefined && markdown.isMarkdownFile(info.path)) {
|
package/lib/files-page.mjs
CHANGED
|
@@ -263,6 +263,37 @@ const MENU_JS = `<script>
|
|
|
263
263
|
|
|
264
264
|
const TEXT_FILE_RE = /\.(txt|md|markdown|json|jsonc|js|mjs|cjs|ts|tsx|jsx|css|scss|less|html|htm|xml|yml|yaml|toml|ini|conf|cfg|log|csv|tsv|sh|bash|ps1|bat|cmd|py|rb|go|rs|java|c|h|cpp|hpp|cs|php|sql|env)$/iu
|
|
265
265
|
|
|
266
|
+
/** 图片墙:把目录(递归)里的图片铺成缩略图网格,点开进预览页,可左右滑动切换。 */
|
|
267
|
+
export function renderWallPage({ dir = '', images = [], truncated = false, message = '', isError = false, session = '' }) {
|
|
268
|
+
const backHref = session === ''
|
|
269
|
+
? '/files' + (dir === '' ? '' : '?path=' + encodeURIComponent(dir))
|
|
270
|
+
: '/files?session=' + encodeURIComponent(session)
|
|
271
|
+
const items = images.map((item) => {
|
|
272
|
+
const label = item.rel || item.name
|
|
273
|
+
return `<a class="wallitem" href="/files/view?path=${encodeURIComponent(item.path)}" title="${escapeHtml(label)}">
|
|
274
|
+
<img src="/files/raw?path=${encodeURIComponent(item.path)}" loading="lazy" decoding="async" alt="${escapeHtml(label)}">
|
|
275
|
+
<span>${escapeHtml(label)}</span></a>`
|
|
276
|
+
}).join('')
|
|
277
|
+
const body = `
|
|
278
|
+
<div class="bar">
|
|
279
|
+
<h1>图片墙</h1>
|
|
280
|
+
<div class="path">${escapeHtml(dir)}</div>
|
|
281
|
+
<div class="chips"><a class="chip" href="${backHref}">返回文件</a><span class="chip" style="background:transparent;color:#9aa3b2">${images.length} 张</span></div>
|
|
282
|
+
</div>
|
|
283
|
+
${message ? `<div class="msg${isError ? ' err' : ''}">${escapeHtml(message)}</div>` : ''}
|
|
284
|
+
${truncated ? '<div class="msg">图片太多,只显示最新的一部分</div>' : ''}
|
|
285
|
+
${images.length === 0
|
|
286
|
+
? '<div class="empty" style="padding:24px 4px;color:#9aa3b2">这个目录下没有可预览的图片(支持 png/jpg/jpeg/gif/webp/bmp)。</div>'
|
|
287
|
+
: `<div class="wall">${items}</div>`}
|
|
288
|
+
<style>
|
|
289
|
+
.wall{display:grid;grid-template-columns:repeat(auto-fill,minmax(110px,1fr));gap:8px;margin-top:12px}
|
|
290
|
+
.wallitem{display:block;text-decoration:none;color:inherit;min-width:0}
|
|
291
|
+
.wallitem img{width:100%;aspect-ratio:1/1;object-fit:cover;border-radius:8px;background:#0f1319;border:1px solid #262b36}
|
|
292
|
+
.wallitem span{display:block;font-size:11px;color:#9aa3b2;margin-top:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
293
|
+
</style>`
|
|
294
|
+
return layout({ title: '图片墙 · DSH', body, current: '/files' })
|
|
295
|
+
}
|
|
296
|
+
|
|
266
297
|
/** 文件页渲染 */
|
|
267
298
|
export function renderListing({ info, message, isError, home, dataDir, workspaces = [] }) {
|
|
268
299
|
const menuFor = (entry) => `<span class="mm">
|
|
@@ -320,6 +351,7 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
|
|
|
320
351
|
<div style="flex:1 1 auto;display:flex;align-items:center;justify-content:flex-end;gap:4px;flex-wrap:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none">
|
|
321
352
|
<a class="btn ghost" href="/files?path=${encodeURIComponent(home)}" style="${navStyle}">HOME</a>
|
|
322
353
|
<a class="btn ghost" href="/files?path=${encodeURIComponent(dataDir)}" style="${navStyle}">配置</a>
|
|
354
|
+
<a class="btn ghost" href="/files/wall?path=${encodeURIComponent(info.path)}" style="${navStyle}">图片墙</a>
|
|
323
355
|
${parent}
|
|
324
356
|
</div>
|
|
325
357
|
</div>
|
|
@@ -422,25 +454,45 @@ export function renderCompressPage({ target, archive, message, isError, done = f
|
|
|
422
454
|
return layout({ title: '加密压缩 · ' + name, body })
|
|
423
455
|
}
|
|
424
456
|
|
|
425
|
-
/** 文件内容页(text=源码;rendered=Markdown
|
|
457
|
+
/** 文件内容页(text=源码;rendered=Markdown 渲染结果;image=图片预览) */
|
|
426
458
|
export function renderFile({ info, message, isError, rendered = null }) {
|
|
427
459
|
const isMarkdown = /\.(?:md|markdown|mdown|mkd)$/iu.test(info.path)
|
|
460
|
+
const isImage = info.image === true
|
|
428
461
|
const sourceHref = '/files/view?path=' + encodeURIComponent(info.path) + '&raw=1'
|
|
429
462
|
const renderedHref = '/files/view?path=' + encodeURIComponent(info.path)
|
|
430
|
-
const
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
463
|
+
const rawHref = '/files/raw?path=' + encodeURIComponent(info.path)
|
|
464
|
+
const downloadHref = '/files/download?path=' + encodeURIComponent(info.path)
|
|
465
|
+
// 图片:同目录内的上一张/下一张(由路由算好放进 info),配合 files-preview.js 的左右滑动
|
|
466
|
+
const imageNav = isImage && info.error === undefined
|
|
467
|
+
? `<div class="chips" style="align-items:center">
|
|
468
|
+
${info.prevHref ? `<a class="chip" id="img-prev" href="${info.prevHref}">← 上一张</a>` : ''}
|
|
469
|
+
${info.position ? `<span class="chip" style="background:transparent;color:#9aa3b2">${escapeHtml(info.position)}</span>` : ''}
|
|
470
|
+
${info.nextHref ? `<a class="chip" id="img-next" href="${info.nextHref}">下一张 →</a>` : ''}
|
|
471
|
+
</div>`
|
|
472
|
+
: ''
|
|
473
|
+
const toggle = isImage
|
|
474
|
+
? `<div class="chips"><a class="chip" href="${rawHref}" target="_blank" rel="noopener noreferrer">查看原图</a><a class="chip" href="${downloadHref}">下载</a></div>`
|
|
475
|
+
: rendered
|
|
476
|
+
? `<div class="chips"><a class="chip" href="${sourceHref}">查看源码</a></div>`
|
|
477
|
+
: (isMarkdown && info.error === undefined
|
|
478
|
+
? `<div class="chips"><a class="chip" href="${renderedHref}">渲染 Markdown</a></div>`
|
|
479
|
+
: '')
|
|
435
480
|
const body = `
|
|
436
481
|
<div class="bar">
|
|
437
482
|
<h1>${escapeHtml(info.path.split(/[\\/]/u).pop())}</h1>
|
|
438
483
|
<div class="path">${escapeHtml(info.path)}</div>
|
|
439
484
|
${toggle}
|
|
485
|
+
${imageNav}
|
|
440
486
|
</div>
|
|
441
487
|
${messageHtml(message, isError)}
|
|
442
488
|
${info.error ? `<div class="msg err">${escapeHtml(info.error)}</div>` : ''}
|
|
443
|
-
${
|
|
489
|
+
${isImage && info.error === undefined
|
|
490
|
+
? `<div style="margin:10px 0;padding:10px;border-radius:10px;background:#0f1319;text-align:center">
|
|
491
|
+
<a href="${rawHref}" target="_blank" rel="noopener noreferrer"><img src="${rawHref}" alt="${escapeHtml(info.path.split(/[\\/]/u).pop())}" style="max-width:100%;height:auto;display:block;margin:0 auto;border-radius:6px"></a>
|
|
492
|
+
<p class="crumbs" style="margin-top:8px">左右滑动可切换上一张 / 下一张${info.sizeText ? ` · ${escapeHtml(info.sizeText)}` : ''}</p>
|
|
493
|
+
</div>
|
|
494
|
+
<script src="/dsh_homing/files-preview.js"></script>`
|
|
495
|
+
: (rendered ? `<article class="md-body">${rendered.html}</article>` : (info.text !== undefined ? `<pre>${escapeHtml(info.text)}</pre>` : ''))}
|
|
444
496
|
<div class="row">
|
|
445
497
|
<a class="btn ghost" href="/files?path=${encodeURIComponent(info.path.replace(/[\\/][^\\/]*$/u, '') || '/')}"
|
|
446
498
|
style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">返回目录</a>
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 图片预览页的手势脚本(外部文件:页面 CSP 是 script-src 'self',不能内联)。
|
|
3
|
+
*
|
|
4
|
+
* 作用:在图片预览页左右滑动切换上一张/下一张(桌面端也支持 ←/→ 键)。
|
|
5
|
+
* 链接由服务端渲染在 #img-prev / #img-next 上;任一方向没有相邻图时对应链接不存在。
|
|
6
|
+
*/
|
|
7
|
+
(() => {
|
|
8
|
+
const prev = document.getElementById('img-prev')
|
|
9
|
+
const next = document.getElementById('img-next')
|
|
10
|
+
if (prev === null && next === null) return
|
|
11
|
+
|
|
12
|
+
const go = (node) => {
|
|
13
|
+
if (node !== null) window.location.href = node.getAttribute('href')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
let startX = 0
|
|
17
|
+
let startY = 0
|
|
18
|
+
let tracking = false
|
|
19
|
+
window.addEventListener('touchstart', (event) => {
|
|
20
|
+
if (event.touches.length !== 1) { tracking = false; return }
|
|
21
|
+
tracking = true
|
|
22
|
+
startX = event.touches[0].clientX
|
|
23
|
+
startY = event.touches[0].clientY
|
|
24
|
+
}, { passive: true })
|
|
25
|
+
window.addEventListener('touchend', (event) => {
|
|
26
|
+
if (!tracking) return
|
|
27
|
+
tracking = false
|
|
28
|
+
const touch = event.changedTouches && event.changedTouches[0]
|
|
29
|
+
if (!touch) return
|
|
30
|
+
const dx = touch.clientX - startX
|
|
31
|
+
const dy = touch.clientY - startY
|
|
32
|
+
// 只认明显的水平滑动,避免把页面上下滚动误判成切换
|
|
33
|
+
if (Math.abs(dx) < 60 || Math.abs(dx) < Math.abs(dy)) return
|
|
34
|
+
go(dx > 0 ? prev : next)
|
|
35
|
+
}, { passive: true })
|
|
36
|
+
window.addEventListener('keydown', (event) => {
|
|
37
|
+
if (event.key === 'ArrowLeft') go(prev)
|
|
38
|
+
else if (event.key === 'ArrowRight') go(next)
|
|
39
|
+
})
|
|
40
|
+
})()
|
package/lib/files.mjs
CHANGED
|
@@ -275,6 +275,74 @@ export function runnableKind(file) {
|
|
|
275
275
|
return null
|
|
276
276
|
}
|
|
277
277
|
|
|
278
|
+
/**
|
|
279
|
+
* 可在线预览的图片类型(白名单)。
|
|
280
|
+
* 只收浏览器原生能渲染、且不执行脚本的格式:SVG 故意不收
|
|
281
|
+
* (直接同源打开 SVG 里的脚本会执行,而 /files/raw 是内联返回)。
|
|
282
|
+
*/
|
|
283
|
+
const IMAGE_MIME = new Map([
|
|
284
|
+
['.png', 'image/png'],
|
|
285
|
+
['.jpg', 'image/jpeg'],
|
|
286
|
+
['.jpeg', 'image/jpeg'],
|
|
287
|
+
['.gif', 'image/gif'],
|
|
288
|
+
['.webp', 'image/webp'],
|
|
289
|
+
['.bmp', 'image/bmp'],
|
|
290
|
+
])
|
|
291
|
+
|
|
292
|
+
/** 是不是可在线预览的图片文件 */
|
|
293
|
+
export const isImageFile = (name) => IMAGE_MIME.has(path.extname(String(name ?? '')).toLowerCase())
|
|
294
|
+
|
|
295
|
+
/** 图片 MIME;不是白名单图片格式返回 null */
|
|
296
|
+
export const imageMimeOf = (name) => IMAGE_MIME.get(path.extname(String(name ?? '')).toLowerCase()) ?? null
|
|
297
|
+
|
|
298
|
+
/** 图片墙/相册:递归收集目录下的可预览图片(有深度与数量上限,跳过隐藏目录与依赖目录)。 */
|
|
299
|
+
const SKIP_DIRS = new Set(['node_modules', '.git'])
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* @param {string} dirPath
|
|
303
|
+
* @param {{ maxFiles?: number, maxDepth?: number }} [options]
|
|
304
|
+
* @returns {{ ok: boolean, dir?: string, images?: Array, truncated?: boolean, error?: string }}
|
|
305
|
+
*/
|
|
306
|
+
export function listImages(dirPath, { maxFiles = 300, maxDepth = 4 } = {}) {
|
|
307
|
+
const root = resolvePath(dirPath)
|
|
308
|
+
let rootStat = null
|
|
309
|
+
try { rootStat = fs.statSync(root) } catch { rootStat = null }
|
|
310
|
+
if (!rootStat || !rootStat.isDirectory()) return { ok: false, images: [], error: '这不是目录或目录不存在' }
|
|
311
|
+
|
|
312
|
+
const images = []
|
|
313
|
+
let truncated = false
|
|
314
|
+
const walk = (dir, depth) => {
|
|
315
|
+
let names = []
|
|
316
|
+
try { names = fs.readdirSync(dir) } catch { return }
|
|
317
|
+
for (const name of names) {
|
|
318
|
+
if (truncated) return
|
|
319
|
+
if (name.startsWith('.')) continue
|
|
320
|
+
const full = path.join(dir, name)
|
|
321
|
+
let stat = null
|
|
322
|
+
try { stat = fs.statSync(full) } catch { continue }
|
|
323
|
+
if (stat.isDirectory()) {
|
|
324
|
+
if (depth >= maxDepth || SKIP_DIRS.has(name)) continue
|
|
325
|
+
walk(full, depth + 1)
|
|
326
|
+
continue
|
|
327
|
+
}
|
|
328
|
+
if (!isImageFile(name)) continue
|
|
329
|
+
images.push({
|
|
330
|
+
name,
|
|
331
|
+
rel: path.relative(root, full).split(path.sep).join('/'),
|
|
332
|
+
path: full,
|
|
333
|
+
size: stat.size,
|
|
334
|
+
sizeText: fmtSize(stat.size),
|
|
335
|
+
mtimeMs: stat.mtimeMs,
|
|
336
|
+
mtime: fmtTime(stat.mtime),
|
|
337
|
+
})
|
|
338
|
+
if (images.length >= maxFiles) { truncated = true; return }
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
walk(root, 0)
|
|
342
|
+
images.sort((a, b) => b.mtimeMs - a.mtimeMs || a.rel.localeCompare(b.rel, 'zh'))
|
|
343
|
+
return { ok: true, dir: root, images, truncated }
|
|
344
|
+
}
|
|
345
|
+
|
|
278
346
|
/** 读文本文件;二进制或过大时不返回正文。 */
|
|
279
347
|
export function readTextFile(absPath, limit = MAX_READ) {
|
|
280
348
|
const target = resolvePath(absPath)
|