// DevBox 创作者模块:视频/音乐解析、转码、网盘直链。依赖系统 yt-dlp + ffmpeg。
import { spawn } from 'node:child_process'
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createHmac, randomUUID, randomBytes } from 'node:crypto'
export const UA =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
const YTDLP = process.env.DEVBOX_YTDLP || 'yt-dlp'
const FFMPEG = process.env.DEVBOX_FFMPEG || 'ffmpeg'
const MAX_RESOLVE_MS = 60_000
const MAX_CONVERT_MS = 15 * 60_000
/* ---------------- 通用执行 ---------------- */
function run(cmd, args, { input, timeout = MAX_RESOLVE_MS, maxBuffer = 64 << 20 } = {}) {
return new Promise((resolve) => {
const p = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'] })
const out = []
const err = []
let size = 0
let killed = false
const timer = setTimeout(() => {
killed = true
p.kill('SIGKILL')
}, timeout)
p.stdout.on('data', (c) => {
size += c.length
if (size > maxBuffer) {
killed = true
p.kill('SIGKILL')
return
}
out.push(c)
})
p.stderr.on('data', (c) => err.push(c))
p.on('error', (e) => {
clearTimeout(timer)
resolve({ code: -1, stdout: '', stderr: String(e.message || e), killed })
})
p.on('close', (code) => {
clearTimeout(timer)
resolve({
code,
stdout: Buffer.concat(out).toString('utf8'),
stderr: Buffer.concat(err).toString('utf8').slice(-4000),
killed
})
})
if (input) p.stdin.end(input)
else p.stdin.end()
})
}
export function isHttpUrl(u) {
try {
const x = new URL(String(u))
return x.protocol === 'http:' || x.protocol === 'https:'
} catch {
return false
}
}
function withCookieFile(cookie, fn) {
if (!cookie) return fn(null)
const dir = mkdtempSync(join(tmpdir(), 'devbox-ck-'))
const file = join(dir, 'cookies.txt')
const body = /^# Netscape|^# HTTP Cookie/i.test(cookie)
? cookie
: ['# Netscape HTTP Cookie File', ...String(cookie).split(/\r?\n/).filter(Boolean)].join('\n') + '\n'
writeFileSync(file, body)
return Promise.resolve(fn(file)).finally(() => {
try {
rmSync(dir, { recursive: true, force: true })
} catch {}
})
}
function baseArgs(cookieFile) {
const a = [YTDLP, '--no-warnings', '--no-playlist', '--socket-timeout', '20', '--user-agent', UA]
if (cookieFile) a.push('--cookies', cookieFile)
return a
}
/* ---------------- 解析 ---------------- */
export async function resolveMedia(url, { cookie = '', audioOnly = false } = {}) {
if (!isHttpUrl(url)) throw new Error('请填 http(s) 开头的链接')
const out = await withCookieFile(cookie, async (ck) => {
const a = baseArgs(ck)
a.push('-J')
if (audioOnly) a.push('-f', 'ba/b')
a.push(url)
return run(a[0], a.slice(1), { timeout: MAX_RESOLVE_MS })
})
if (out.code === 0 && out.stdout.trim().startsWith('{')) {
const info = JSON.parse(out.stdout)
return normalize(info)
}
const fallback = await scrape(url)
if (fallback.title || fallback.video.length || fallback.audio.length) {
fallback.note = briefErr(out.stderr)
return fallback
}
throw new Error('解析失败:' + (briefErr(out.stderr) || '站点可能需要 Cookie 或本机访问不到'))
}
function briefErr(s) {
const line = String(s || '')
.split('\n')
.reverse()
.find((l) => /ERROR|error/i.test(l))
return (line || String(s || '')).replace(/^ERROR:\s*/, '').slice(0, 300)
}
function normalize(info) {
let fmts = Array.isArray(info.formats) ? info.formats : []
if (!fmts.length && info.url) {
fmts = [{ format_id: info.format_id || 'src', ext: info.ext || 'mp4', url: info.url, filesize: info.filesize, format_note: info.format_note || '原始文件', vcodec: info.vcodec, acodec: info.acodec, height: info.height, width: info.width, abr: info.abr, fps: info.fps }]
}
const video = []
const audio = []
for (const f of fmts) {
if (!f.url) continue
const item = {
id: f.format_id,
ext: f.ext || '',
url: f.url,
size: f.filesize || f.filesize_approx || 0,
note: f.format_note || f.format || ''
}
if (f.vcodec && f.vcodec !== 'none' && f.height) {
video.push({ ...item, quality: f.height + 'p', width: f.width, height: f.height, fps: f.fps || 0, vcodec: f.vcodec, acodec: f.acodec })
} else if ((!f.vcodec || f.vcodec === 'none') && f.acodec && f.acodec !== 'none') {
audio.push({ ...item, abr: f.abr || 0, acodec: f.acodec })
} else if (!f.height) {
video.push({ ...item, quality: '原始', vcodec: f.vcodec || 'unknown', acodec: f.acodec || 'unknown' })
}
}
video.sort((a, b) => (b.height || 0) - (a.height || 0) || (b.size || 0) - (a.size || 0))
audio.sort((a, b) => (b.abr || 0) - (a.abr || 0))
const seen = new Set()
const uniq = (list) => list.filter((x) => (seen.has(x.url) ? false : (seen.add(x.url), true)))
return {
ok: true,
source: info.extractor_key || info.extractor || 'yt-dlp',
title: info.title || '',
uploader: info.uploader || info.channel || '',
duration: info.duration || 0,
thumbnail: info.thumbnail || '',
webpage: info.webpage_url || '',
video: uniq(video).slice(0, 40),
audio: uniq(audio).slice(0, 20)
}
}
async function scrape(url) {
const res = await fetch(url, { headers: { 'user-agent': UA, referer: url }, redirect: 'follow' }).catch(() => null)
const html = res ? await res.text().catch(() => '') : ''
const pick = (re) => (html.match(re) || [])[1] || ''
const title = pick(/]+property=["']og:title["'][^>]+content=["']([^"']+)/i) || pick(/
([^<]+)/i)
const img = pick(/]+property=["']og:image["'][^>]+content=["']([^"']+)/i)
const vids = []
const mp4 = pick(/