| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- /**
- * 文件
- * ====
- * Web 版没有"老师的桌面",所有产物都落在该老师自己的工作区里,通过浏览器下载。
- * 页面函数投递需要"页面自己去取字节",所以另有一条**短时 token** 的读取地址:
- *
- * /_cc/blob/<token> —— 只对 token 里的那一个文件有效,60 秒过期,CORS 放开
- *
- * 为什么不在页面里直接塞 base64:PPT 动辄几十 MB,Runtime.evaluate 的参数体积
- * 会被 CDP 和内联脚本上限卡住,而且 base64 要占 1.33 倍内存。
- */
- import fs from 'node:fs'
- import fsp from 'node:fs/promises'
- import path from 'node:path'
- import crypto from 'node:crypto'
- const MAX_UPLOAD = 512 * 1024 * 1024
- const BLOB_TTL = 60_000
- export class Files {
- /** @param {{roots:string[]}} options 允许读写的根目录 */
- constructor (options) {
- this.roots = options.roots.filter(Boolean).map((r) => path.resolve(r))
- this.blobs = new Map()
- this.sweeper = setInterval(() => {
- const now = Date.now()
- for (const [token, entry] of this.blobs) if (entry.expires < now) this.blobs.delete(token)
- }, 30_000)
- this.sweeper.unref?.()
- }
- /** 把用户给的路径钉在允许的根里;越界返回 null,绝不返回一个"看起来对"的路径 */
- resolve (input) {
- const raw = String(input || '').trim()
- if (!raw) return null
- const abs = path.resolve(this.roots[0], raw)
- for (const root of this.roots) {
- const rel = path.relative(root, abs)
- if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) return abs
- if (abs === root) return abs
- }
- return null
- }
- async saveUpload (name, stream, maxBytes = MAX_UPLOAD) {
- const safeName = path.basename(String(name || 'upload.bin')).replace(/[\\/:*?"<>|]/g, '_').slice(0, 120)
- const dir = path.join(this.roots[0], 'uploads')
- await fsp.mkdir(dir, { recursive: true })
- const target = path.join(dir, `${Date.now()}-${safeName}`)
- let size = 0
- await new Promise((resolve, reject) => {
- const out = fs.createWriteStream(target)
- stream.on('data', (chunk) => {
- size += chunk.length
- if (size > maxBytes) {
- stream.destroy()
- out.destroy()
- fsp.unlink(target).catch(() => {})
- reject(Object.assign(new Error('文件超过 512MB 上限'), { code: 'too_large' }))
- }
- })
- stream.pipe(out)
- out.on('finish', resolve)
- out.on('error', reject)
- stream.on('error', reject)
- })
- return { path: target, size, name: safeName }
- }
- /** 给页面用的短时地址:只映射一个文件,过期自动失效 */
- blobUrl (filePath, publicBase) {
- const abs = this.resolve(filePath)
- if (!abs) return ''
- const token = crypto.randomBytes(24).toString('base64url')
- this.blobs.set(token, { path: abs, expires: Date.now() + BLOB_TTL })
- return `${publicBase}/_cc/blob/${token}`
- }
- takeBlob (token) {
- const entry = this.blobs.get(String(token || ''))
- if (!entry) return null
- if (entry.expires < Date.now()) {
- this.blobs.delete(token)
- return null
- }
- return entry.path
- }
- async stat (filePath) {
- return fsp.stat(filePath).catch(() => null)
- }
- /** 目录树:只列两层,够老师找产物;再深让他下载整包 */
- async list (dir, depth = 2) {
- const root = this.resolve(dir || this.roots[0])
- if (!root) return null
- const out = []
- const walk = async (current, level) => {
- let entries = []
- try { entries = await fsp.readdir(current, { withFileTypes: true }) } catch { return }
- for (const entry of entries) {
- if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
- const full = path.join(current, entry.name)
- const rel = path.relative(this.roots[0], full)
- if (entry.isDirectory()) {
- out.push({ type: 'dir', path: rel, name: entry.name })
- if (level > 1) await walk(full, level - 1)
- } else if (entry.isFile()) {
- const info = await this.stat(full)
- out.push({ type: 'file', path: rel, name: entry.name, size: info ? info.size : 0, mtime: info ? info.mtimeMs : 0 })
- }
- if (out.length > 2000) return
- }
- }
- await walk(root, depth)
- return out
- }
- async readSmall (filePath, limit = 512 * 1024) {
- const abs = this.resolve(filePath)
- if (!abs) return null
- const info = await this.stat(abs)
- if (!info || !info.isFile() || info.size > limit) return null
- return fsp.readFile(abs)
- }
- dispose () {
- clearInterval(this.sweeper)
- this.blobs.clear()
- }
- }
|