Files
devbox/js/cat-file.js
T
dsh-go 5eff203741 同步 devbox 源码
由 dsh-go 自动上传 · 2026/11/20 15:20:41
2026-11-20 15:20:41 +08:00

189 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(function () {
const { el, panelTitle, copy, toast, bytes, download } = DB
const pane = (t, ...k) => { const p = el('div', { class: 'panel' }); if (t) p.append(panelTitle(t)); p.append(...k.filter(Boolean)); return p }
const btn = (l, f, c = '') => el('button', { class: 'btn ' + c, text: l, onclick: f })
const readFile = (f, how = 'buf') => new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = rej; how === 'buf' ? r.readAsArrayBuffer(f) : r.readAsText(f) })
const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')
const picker = (multi, cb, accept) => { const i = el('input', { type: 'file', class: 'inp', multiple: multi || false }); if (accept) i.accept = accept; i.addEventListener('change', () => cb([...i.files])); return i }
/* MD5(自带实现,避免没 subtle 的环境) */
function md5(buf) {
const s = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
const K = new Int32Array(64); for (let i = 0; i < 64; i++) K[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) | 0
const bytes = new Uint8Array(buf); const len = bytes.length
const total = (((len + 8) >> 6) + 1) * 64
const m = new Uint8Array(total); m.set(bytes); m[len] = 0x80
const dv = new DataView(m.buffer); dv.setUint32(total - 8, (len * 8) >>> 0, true); dv.setUint32(total - 4, Math.floor(len / 536870912), true)
let a0 = 0x67452301, b0 = 0xefcdab89 | 0, c0 = 0x98badcfe | 0, d0 = 0x10325476
for (let off = 0; off < total; off += 64) {
const M = new Int32Array(16); for (let i = 0; i < 16; i++) M[i] = dv.getInt32(off + i * 4, true)
let A = a0, B = b0, C = c0, D = d0
for (let i = 0; i < 64; i++) {
let F, g
if (i < 16) { F = (B & C) | (~B & D); g = i } else if (i < 32) { F = (D & B) | (~D & C); g = (5 * i + 1) % 16 } else if (i < 48) { F = B ^ C ^ D; g = (3 * i + 5) % 16 } else { F = C ^ (B | ~D); g = (7 * i) % 16 }
const tmp = D; D = C; C = B; B = (B + ((A + F + K[i] + M[g]) | 0) << 0) | 0
A = tmp
const rot = s[i]; B = ((B << rot) | (B >>> (32 - rot))) | 0
}
a0 = (a0 + A) | 0; b0 = (b0 + B) | 0; c0 = (c0 + C) | 0; d0 = (d0 + D) | 0
}
const out = new Uint8Array(16); const o = new DataView(out.buffer)
;[a0, b0, c0, d0].forEach((v, i) => o.setInt32(i * 4, v, true))
return [...out].map((b) => b.toString(16).padStart(2, '0')).join('')
}
const sha = async (buf, alg) => hex(await crypto.subtle.digest(alg, buf))
/* 文件哈希 */
DB.tool({ id: 'file-hash', name: '文件哈希', group: 'crypto', icon: 'hash', desc: '算 MD5 / SHA-1 / SHA-256 / SHA-512', keywords: ['哈希', 'md5', 'sha', '校验'],
mount(root) {
const out = el('div', { class: 'kv-out', text: '' })
const run = async (files) => { if (!files[0]) return; const f = files[0]; out.textContent = '计算中…'
const buf = await readFile(f)
const r = { MD5: md5(buf), 'SHA-1': await sha(buf, 'SHA-1'), 'SHA-256': await sha(buf, 'SHA-256'), 'SHA-512': await sha(buf, 'SHA-512') }
out.textContent = `${f.name}(${bytes(f.size)})\n` + Object.entries(r).map(([k, v]) => `${k}: ${v}`).join('\n')
}
root.append(pane('文件哈希'), picker(false, run), out)
} })
/* 文件信息 */
DB.tool({ id: 'file-info', name: '文件信息', group: 'web', icon: 'info', desc: '大小、类型、文件头、修改时间', keywords: ['文件', '信息', 'magic'],
mount(root) {
const out = el('div', { class: 'kv-out', text: '' })
const run = async (files) => { if (!files[0]) return; const f = files[0]; const buf = await readFile(f)
const head = hex(buf.slice(0, 16))
const magic = head.startsWith('89504e47') ? 'PNG 图片' : head.startsWith('ffd8ff') ? 'JPEG 图片' : head.startsWith('47494638') ? 'GIF 图片' : head.startsWith('25504446') ? 'PDF 文档' : head.startsWith('504b0304') ? 'ZIP / Office 文档' : head.startsWith('7f454c46') ? 'ELF 可执行' : /^4d5a|^5a4d/.test(head) ? 'PE 可执行' : head.startsWith('1f8b') ? 'GZIP 压缩' : head.startsWith('52494646') ? 'RIFF(WAV/WebP/AVI)' : head.startsWith('00000018') ? 'MP4 / MOV' : '未知'
out.textContent = [`名称:${f.name}`, `大小:${bytes(f.size)}(${f.size} 字节)`, `类型:${f.type || '未知'}`, `识别:${magic}`, `头部:${head}`, `修改:${new Date(f.lastModified).toLocaleString()}`].join('\n') }
root.append(pane('文件信息'), picker(false, run), out)
} })
/* 文件比对 */
DB.tool({ id: 'file-compare', name: '文件比对', group: 'text', icon: 'diff', desc: '两个文件逐字节比,或按行比文本', keywords: ['比对', '对比', 'diff', '文件'],
mount(root) {
const out = el('div', { class: 'kv-out', text: '' })
const run = async (files) => {
if (files.length < 2) { out.textContent = '选两个文件'; return }
const [a, b] = await Promise.all(files.slice(0, 2).map((f) => readFile(f)))
const A = new Uint8Array(a), B = new Uint8Array(b)
if (A.length !== B.length) out.textContent = `大小不同:${A.length} vs ${B.length} 字节`
else { let i = A.findIndex((v, k) => v !== B[k]); out.textContent = i < 0 ? '完全一致 ✓' : `第 ${i} 字节开始不同:${A[i].toString(16)} vs ${B[i].toString(16)}` }
}
root.append(pane('文件比对'), picker(true, run), out)
} })
/* 批量重命名 */
DB.tool({ id: 'file-rename', name: '批量重命名', group: 'text', icon: 'edit', desc: '按规则生成新文件名清单,再手动改', keywords: ['重命名', '批量', '改名'],
mount(root) {
const list = el('textarea', { class: 'ta', rows: 5, placeholder: '每行一个原文件名' })
const pat = el('input', { class: 'inp', value: '前缀_{n}{ext}', placeholder: '模板:{n} 序号,{name} 原名,{ext} 扩展名' })
const out = el('textarea', { class: 'ta', rows: 8, readonly: true })
const go = () => {
const pad = (n, w) => String(n).padStart(w, '0')
out.value = list.value.split('\n').filter((x) => x.trim()).map((line, i) => {
const name = line.trim(); const m = name.match(/\.[^.]+$/)
const ext = m ? m[0] : '', base = m ? name.slice(0, -m[0].length) : name
return pat.value.replace(/\{n\}/g, pad(i + 1, 3)).replace(/\{name\}/g, base).replace(/\{ext\}/g, ext)
}).join('\n')
}
list.addEventListener('input', go); pat.addEventListener('input', go)
root.append(pane('批量重命名'), list, pat, out, btn('复制新名字', () => copy(out.value)))
} })
/* 编码转换 */
DB.tool({ id: 'file-encoding-convert', name: '文本编码转换', group: 'encode', icon: 'abc', desc: 'UTF-8 / UTF-16 / Base64 / Hex 互转,自动识别 BOM', keywords: ['编码', 'utf8', 'utf16', 'bom'],
mount(root) {
const out = el('div', { class: 'kv-out', text: '' })
const run = async (files) => { if (!files[0]) return; const f = files[0]; const buf = await readFile(f); const u8 = new Uint8Array(buf)
const bom = u8[0] === 0xef && u8[1] === 0xbb && u8[2] === 0xbf ? 'UTF-8 BOM' : u8[0] === 0xff && u8[1] === 0xfe ? 'UTF-16LE' : u8[0] === 0xfe && u8[1] === 0xff ? 'UTF-16BE' : '无 BOM'
let text = ''
try { text = new TextDecoder(bom === 'UTF-16LE' ? 'utf-16le' : bom === 'UTF-16BE' ? 'utf-16be' : 'utf-8', { fatal: false }).decode(u8) } catch (e) { text = new TextDecoder().decode(u8) }
const ctrl = [...text.slice(0, 2000)].filter((c) => c.charCodeAt(0) < 9).length
out.textContent = `BOM:${bom}\n疑似二进制/乱码字符:${ctrl}\n\n前 500 字:\n${text.slice(0, 500)}`
}
root.append(pane('文本编码转换'), picker(false, run), out)
} })
/* 文件加密 / 解密(AES-GCM) */
const enc = new TextEncoder(), dec = new TextDecoder()
async function aesKey(pass) {
const base = await crypto.subtle.importKey('raw', enc.encode(pass), 'PBKDF2', false, ['deriveKey'])
return crypto.subtle.deriveKey({ name: 'PBKDF2', salt: enc.encode('devbox-salt'), iterations: 120000, hash: 'SHA-256' }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
}
DB.tool({ id: 'file-encrypt', name: '文件加密', group: 'crypto', icon: 'lock', desc: 'AES-GCM 加密任意文件,口令自己记住', keywords: ['加密', 'aes', '文件'],
mount(root) {
const pass = el('input', { class: 'inp', type: 'password', placeholder: '口令(至少 4 位)' })
const st = el('div', { class: 'kv-out', text: '选文件后开始加密' })
let cur = null
const run = async (files) => { if (!files[0]) return; cur = files[0]; st.textContent = `${cur.name}(${bytes(cur.size)})已选择,点下面加密` }
const go = async () => {
if (!cur) return
if (pass.value.length < 4) { toast('口令太短', true); return }
const iv = crypto.getRandomValues(new Uint8Array(12))
const data = await readFile(cur)
const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await aesKey(pass.value), data)
const blob = new Blob([iv, new Uint8Array(ct)])
download(blob, cur.name + '.enc')
st.textContent = '已加密下载:' + cur.name + '.enc'
}
root.append(pane('文件加密(AES-GCM)'), pass, picker(false, run), st, btn('加密并下载', go))
} })
DB.tool({ id: 'secret-note', name: '加密便签', group: 'crypto', icon: 'lock', desc: '把一段文字用口令加密成乱码,可再解回来', keywords: ['便签', '加密', '文字'],
mount(root) {
const pass = el('input', { class: 'inp', type: 'password', placeholder: '口令' })
const inp = el('textarea', { class: 'ta', rows: 5, placeholder: '要加密的文字' })
const out = el('textarea', { class: 'ta', rows: 5, readonly: true })
const doEnc = async () => { if (!pass.value) return toast('先填口令', true)
const iv = crypto.getRandomValues(new Uint8Array(12)); const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, await aesKey(pass.value), enc.encode(inp.value))
out.value = btoa(String.fromCharCode(...iv)) + '.' + btoa(String.fromCharCode(...new Uint8Array(ct))) }
const doDec = async () => { try {
const [i6, c6] = out.value.trim().split('.'); const iv = Uint8Array.from(atob(i6), (c) => c.charCodeAt(0))
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, await aesKey(pass.value), Uint8Array.from(atob(c6), (c) => c.charCodeAt(0)))
inp.value = dec.decode(pt); toast('解密成功') } catch (e) { toast('口令不对或内容损坏', true) } }
root.append(pane('加密便签'), pass, inp, out, el('div', { class: 'row' }, btn('加密', doEnc), btn('解密', doDec, 'ghost'), btn('复制', () => copy(out.value), 'ghost')))
} })
/* 查重 */
DB.tool({ id: 'duplicate-file-finder', name: '重复文件检测', group: 'web', icon: 'search', desc: '多选文件,按内容哈希找出重复', keywords: ['查重', '重复文件', 'duplicate'],
mount(root) {
const out = el('div', { class: 'kv-out', text: '' })
const run = async (files) => {
if (!files.length) return
out.textContent = '计算中…'
const map = {}
for (const f of files) { const h = md5(await readFile(f)); (map[h] = map[h] || []).push(f.name + '(' + bytes(f.size) + ')') }
const dup = Object.values(map).filter((v) => v.length > 1)
out.textContent = dup.length ? '重复组:\n' + dup.map((g, i) => `第 ${i + 1} 组:` + g.join('、')).join('\n') : '没有发现重复文件 ✓'
}
root.append(pane('重复文件检测'), picker(true, run), out)
} })
/* 文档字数 */
DB.tool({ id: 'doc-word-count', name: '文档字数统计', group: 'text', icon: 'edit', desc: '丢文件进来统计字数、行数、段落', keywords: ['字数', '统计', '文档'],
mount(root) {
const out = el('div', { class: 'kv-out', text: '' })
const run = async (files) => { if (!files[0]) return; const t = await readFile(files[0], 'text')
const han = (t.match(/[\u4e00-\u9fff]/g) || []).length
const words = (t.match(/[A-Za-z][A-Za-z'-]*/g) || []).length
const nums = (t.match(/\d+/g) || []).length
const paras = t.split(/\n\s*\n/).filter((x) => x.trim()).length
out.textContent = `字符 ${t.length} 汉字 ${han} 英文词 ${words} 数字 ${nums}\n行数 ${t.split('\n').length} 段落 ${paras} 预计朗读 ${Math.ceil((han + words) / 4)} 秒` }
root.append(pane('文档字数统计'), picker(false, run), out)
} })
/* 错别字检查(常见混淆) */
const TYPO = [['的得地'], ['在再'], ['做作'], ['帐账'], ['Secret', '']]
DB.tool({ id: 'typo-check', name: '常见错字提示', group: 'text', icon: 'edit', desc: '标出「的地得」「在再」「做作」这类易错用法', keywords: ['错别字', '校对'],
mount(root) {
const inp = el('textarea', { class: 'ta', rows: 6, placeholder: '粘贴文章…' })
const out = el('div', { class: 'kv-out', text: '' })
const rules = [[/的(good|well)/g, ''], [/在(次|见)/g, '「在」多指位置,「再」指重复'], [/[帐]/g, '与钱有关多用「账」'], [/地(说道)/g, ''], [/(做)(好|完)/g, '「做」偏具体动作,「作」偏抽象']]
const go = () => { const t = inp.value; const hits = []
if (/[的地得]/.test(t)) hits.push('出现「的/地/得」:动词前用「地」,形容词后修饰名词用「的」,补充说明用「得」')
if (/再[次]/.test(t)) hits.push('「再次」正确;「在次」是错字')
if (/帐/.test(t)) hits.push('「帐」多用于帐篷,账目用「账」')
if (/即[使]/.test(t) && /既使/.test(t)) hits.push('「即使」不是「既使」')
out.textContent = hits.length ? hits.map((x, i) => `${i + 1}. ${x}`).join('\n') : '没发现问题(只能查常见混淆)' }
inp.addEventListener('input', go)
root.append(pane('常见错字提示'), inp, out)
} })
})()