// 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(/<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)/i) const vids = [] const mp4 = pick(/<video[^>]+src=["']([^"']+)["']/i) || pick(/<meta[^>]+property=["']og:video(?::url|:secure_url)?["'][^>]+content=["']([^"']+)/i) if (mp4) vids.push({ id: 'direct', ext: (mp4.split('?')[0].split('.').pop() || 'mp4').slice(0, 5), url: abs(mp4, url), size: 0, note: '页面内嵌', quality: '未知' }) for (const m of html.matchAll(/https?:\\?\/\\?\/[^\s"']+?\.m3u8[^\s"']*/g)) { const u = m[0].replace(/\\\//g, '/') vids.push({ id: 'm3u8', ext: 'm3u8', url: u, size: 0, note: 'HLS 流', quality: '自动' }) if (vids.length > 6) break } return { ok: true, source: 'generic', title, uploader: '', duration: 0, thumbnail: img, webpage: url, video: vids, audio: [], note: '通用抓取(非 yt-dlp 站点)' } } function abs(u, base) { try { return new URL(u, base).toString() } catch { return u } } /* ---------------- 转码任务 ---------------- */ const jobs = new Map() const JOB_TTL = 30 * 60_000 const VIDEO_FMT = { mp4: { ext: 'mp4', args: ['-c:v', 'mpeg4', '-q:v', '3', '-c:a', 'aac', '-b:a', '160k', '-movflags', 'frag_keyframe+empty_moov'], mime: 'video/mp4' }, mkv: { ext: 'mkv', args: ['-c:v', 'mpeg4', '-q:v', '3', '-c:a', 'aac', '-b:a', '160k'], mime: 'video/x-matroska' }, webm: { ext: 'webm', args: ['-c:v', 'libvpx-vp9', '-b:v', '0', '-crf', '34', '-c:a', 'libopus', '-b:a', '128k'], mime: 'video/webm' }, gif: { ext: 'gif', args: ['-an', '-vf', 'fps=12,scale=480:-1:flags=lanczos'], mime: 'image/gif' }, mp3: { ext: 'mp3', args: ['-vn', '-c:a', 'libmp3lame', '-b:a', '192k'], mime: 'audio/mpeg' } } const AUDIO_FMT = { mp3: { ext: 'mp3', args: ['-vn', '-c:a', 'libmp3lame', '-b:a', '192k'], mime: 'audio/mpeg' }, m4a: { ext: 'm4a', args: ['-vn', '-c:a', 'aac', '-b:a', '192k', '-movflags', 'frag_keyframe+empty_moov'], mime: 'audio/mp4' }, wav: { ext: 'wav', args: ['-vn', '-c:a', 'pcm_s16le'], mime: 'audio/wav' }, flac: { ext: 'flac', args: ['-vn', '-c:a', 'flac'], mime: 'audio/flac' }, ogg: { ext: 'ogg', args: ['-vn', '-c:a', 'libopus', '-b:a', '160k'], mime: 'audio/ogg' }, aac: { ext: 'aac', args: ['-vn', '-c:a', 'aac', '-b:a', '192k'], mime: 'audio/aac' } } export function formatTable() { return { video: Object.keys(VIDEO_FMT), audio: Object.keys(AUDIO_FMT) } } export async function prepareConvert({ url, kind, format, cookie = '', title = '', start = 0, duration = 0 }) { if (!isHttpUrl(url)) throw new Error('链接不对') const table = kind === 'audio' ? AUDIO_FMT : VIDEO_FMT const fmt = table[String(format || '').toLowerCase()] if (!fmt) throw new Error('不支持的格式:' + format) const token = randomBytes(16).toString('hex') const name = safeName(title || 'devbox-' + Date.now()) + '.' + fmt.ext jobs.set(token, { url, kind, args: fmt.args, mime: fmt.mime, ext: fmt.ext, cookie, name, start, duration, at: Date.now() }) return { token, name, format: fmt.ext, mime: fmt.mime } } function safeName(s) { return String(s) .replace(/[\\/:*?"<>|\r\n\t]+/g, '_') .trim() .slice(0, 70) || 'output' } export function getJob(token) { const j = jobs.get(token) if (!j) return null if (Date.now() - j.at > JOB_TTL) { jobs.delete(token) return null } return j } async function directUrl(job) { const ext = job.url.split('?')[0].toLowerCase() if (/\.(mp4|webm|mkv|m4a|mp3|aac|flac|wav|ogg|m3u8|mov|flv)$/.test(ext)) return job.url const out = await withCookieFile(job.cookie, async (ck) => { const a = baseArgs(ck) a.push('-g', '-f', job.kind === 'audio' ? 'ba/b' : 'bv*+ba/b', job.url) return run(a[0], a.slice(1), { timeout: 90_000 }) }) const first = String(out.stdout || '').split('\n').map((s) => s.trim()).filter(Boolean) if (!first.length) throw new Error('取直链失败:' + (briefErr(out.stderr) || '未知原因')) return first.join('|') } export async function streamConvert(job, res) { let src try { src = await directUrl(job) } catch (e) { res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' }) res.end('转码失败:' + (e.message || e)) return } const inArgs = ['-user_agent', UA, '-headers', `Referer: ${new URL(job.url).origin}\r\n`, '-protocol_whitelist', 'file,http,https,tcp,tls,crypto'] if (job.start) inArgs.push('-ss', String(job.start)) if (job.duration) inArgs.push('-t', String(job.duration)) const inputs = [] if (src.includes('|')) { const [v, a] = src.split('|') inputs.push(...inArgs, '-i', v) if (a) inputs.push(...inArgs, '-i', a) } else { inputs.push(...inArgs, '-i', src) } const mapArgs = src.includes('|') && job.kind !== 'audio' ? ['-map', '0:v:0', '-map', '1:a:0?'] : [] const args = [ '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', ...inputs, ...mapArgs, ...job.args, '-f', job.ext === 'm4a' ? 'mp4' : job.ext, 'pipe:1' ] const p = spawn(FFMPEG, args, { stdio: ['ignore', 'pipe', 'pipe'] }) let errText = '' let started = false const timer = setTimeout(() => p.kill('SIGKILL'), MAX_CONVERT_MS) const head = { 'content-type': job.mime, 'content-disposition': `attachment; filename="${encodeURIComponent(job.name)}"; filename*=UTF-8''${encodeURIComponent(job.name)}`, 'cache-control': 'no-store' } p.stderr.on('data', (c) => (errText = (errText + c.toString()).slice(-2000))) p.stdout.on('data', (chunk) => { if (!started) { started = true res.writeHead(200, head) } res.write(chunk) }) p.on('close', (code) => { clearTimeout(timer) if (!started) { res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' }) res.end('转码失败(' + code + '):' + (errText.split('\n').filter(Boolean).slice(-3).join(' ') || '没有输出')) return } res.end() }) res.on('close', () => { clearTimeout(timer) p.kill('SIGKILL') }) } /* ---------------- 网盘直链 ---------------- */ function hostOf(u) { try { return new URL(u).hostname.toLowerCase() } catch { return '' } } export async function netdisk(url, { pwd = '', aliyunToken = '', baiduCookie = '' } = {}) { if (!isHttpUrl(url)) throw new Error('链接不对') const h = hostOf(url) if (/lanzou[a-z]?\.(com|cn)|lanzn\.com|lanzoui\.com|lanzoux\.com|lanzouw\.com/.test(h)) return lanzou(url, pwd) if (/aliyundrive\.com|alipan\.com/.test(h)) return aliyun(url, pwd, aliyunToken) if (/pan\.baidu\.com|yun\.baidu\.com/.test(h)) return baidu(url, pwd, baiduCookie) if (/123pan\.com|123684\.com/.test(h)) return simpleNote('123 云盘', '需要在设置里填 123pan 的 access_token 才能取直链(当前版本暂只做了蓝奏/阿里/百度)') if (/cloud\.189\.cn/.test(h)) return simpleNote('天翼云盘', '天翼云盘直链需要登录态,暂未接入') if (/weiyun\.com/.test(h)) return simpleNote('微云', '微云直链需要登录态,暂未接入') return simpleNote('未知网盘', '目前支持蓝奏云、阿里云盘、百度网盘;其它盘可以直接贴出下载页链接手动取') } function simpleNote(name, message) { return { ok: false, kind: name, message, links: [] } } async function lanzou(url, pwd) { const u = new URL(url) const res = await fetch(url, { headers: { 'user-agent': UA, referer: url } }).catch(() => null) if (!res || !res.ok) throw new Error('打不开蓝奏页面(可能被墙或链接失效)') const html = await res.text() const t = (html.match(/<title>([^<]*)</) || [])[1] || '' const name = t.replace(/\s*-\s*蓝奏云$/, '').trim() || '蓝奏文件' const ajaxPath = (html.match(/["'](ajaxm\.php\?file=\d+[^"']*)["']/) || [])[1] let sign = (html.match(/["']sign["']\s*:\s*["']([^"']+)["']/) || [])[1] || '' const kd = (html.match(/["']kd["']\s*:\s*(\d)/) || [])[1] || '1' if (!ajaxPath) { // 有些分享页把 iframe 地址放在 data 里 const ifr = (html.match(/<iframe[^>]+src=["']([^"']+)["']/i) || [])[1] if (ifr) return lanzou(abs(ifr, url), pwd) throw new Error('这个蓝奏页面没找到下载入口(可能是文件夹分享或需要提取码)') } const body = new URLSearchParams({ action: 'downprocess', sign, ves: '1', websignkey: '', kd, pwd }) const r2 = await fetch(new URL(ajaxPath, url).toString(), { method: 'POST', headers: { 'user-agent': UA, referer: url, 'content-type': 'application/x-www-form-urlencoded' }, body }) const txt = await r2.text() let j = {} try { j = JSON.parse(txt) } catch { throw new Error('蓝奏返回异常:' + txt.slice(0, 120)) } if (j.zt !== 1 && String(j.code) !== '200') throw new Error(j.inf || '蓝奏解析失败(可能需要提取码)') const dom = j.dom || u.origin const link = String(j.url || '').startsWith('http') ? j.url : dom + '/file/' + j.url return { ok: true, kind: '蓝奏云', name, links: [{ label: '直链下载', url: link, note: '带限速,需在浏览器打开' }] } } async function aliyun(url, pwd, refreshToken) { if (!refreshToken) return simpleNote('阿里云盘', '先在「解析设置」里填阿里云盘 refresh_token,再到官网个人中心可以拿到') const tr = await fetch('https://auth.aliyundrive.com/v2/account/token', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ refresh_token: refreshToken, grant_type: 'refresh_token' }) }).then((r) => r.json()) if (!tr.access_token) throw new Error('refresh_token 失效:' + (tr.message || tr.code || '')) const access = tr.access_token const shareId = (url.match(/\/s\/([A-Za-z0-9]+)/) || [])[1] if (!shareId) throw new Error('这不是分享链接') const post = (p, body, extra = {}) => fetch(p, { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + access, ...extra }, body: JSON.stringify(body) }).then((r) => r.json()) const st = await post('https://api.aliyundrive.com/v2/share_link/get_share_token', { share_id: shareId, share_pwd: pwd || '' }) const shareToken = st.share_token if (!shareToken) throw new Error('取分享令牌失败:' + (st.message || '')) const info = await post('https://api.aliyundrive.com/v2/file/list', { share_id: shareId, parent_file_id: 'root', limit: 100, order_by: 'name', order_direction: 'ASC' }, { 'x-share-token': shareToken }) const items = info.items || [] if (!items.length) throw new Error('分享是空的或需要提取码') const links = [] for (const it of items.slice(0, 20)) { if (it.type !== 'file') continue const d = await post('https://api.aliyundrive.com/v2/file/get_download_url', { share_id: shareId, file_id: it.file_id, drive_id: it.drive_id, expire_sec: 900 }, { 'x-share-token': shareToken }) if (d.url) links.push({ label: it.name, url: d.url, note: fmtSize(it.size) + ' · 15 分钟内有效' }) } if (!links.length) return simpleNote('阿里云盘', '没取到可下载文件(可能是文件夹,暂未递归)') return { ok: true, kind: '阿里云盘', name: items[0].name, links } } async function baidu(url, pwd, cookie) { if (!cookie) return simpleNote('百度网盘', '先在「解析设置」里填百度网盘 Cookie(含 BDUSS),直链需要登录态') const surl = (url.match(/\/s\/([A-Za-z0-9_-]+)/) || [])[1] if (!surl) throw new Error('这不是 /s/ 分享链接') const hdr = { 'user-agent': UA, cookie, referer: 'https://pan.baidu.com/' } const verify = await fetch(`https://pan.baidu.com/share/verify?surl=${surl}&t=${Date.now()}&channel=chunlei&web=1&app_id=250528&clienttype=0`, { method: 'POST', headers: { ...hdr, 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ pwd: pwd || '', vcode: '', vcode_str: '' }) }).then((r) => r.json()) if (verify.errno !== 0 && verify.errno !== undefined) throw new Error('提取码校验失败:' + (verify.err_msg || verify.errno)) const page = await fetch(url, { headers: hdr }).then((r) => r.text()) const yunData = page.match(/locals\.mset\((\{[\s\S]*?\})\)/) let fsIds = [] let shareid = (page.match(/"shareid":(\d+)/) || [])[1] let uk = (page.match(/"share_uk":"?(\d+)"?/) || [])[1] || (page.match(/"uk":(\d+)/) || [])[1] if (yunData) { try { const j = JSON.parse(yunData[1].replace(/\\'/g, "'")) shareid = j.shareid || shareid uk = j.share_uk || uk const list = j.file_list || [] fsIds = list.filter((x) => x.isdir === '0' || x.isdir === 0).map((x) => x.fs_id) } catch {} } if (!fsIds.length) fsIds = [...page.matchAll(/"fs_id":(\d+)/g)].map((m) => m[1]).slice(0, 20) if (!fsIds.length) throw new Error('没在分享页里找到文件列表') const metas = await fetch(`https://pan.baidu.com/api/filemetas?target=["dlink"]&fsids=[${fsIds.join(',')}]&dlink=1&web=5&app_id=250528&channel=chunlei&clienttype=0`, { headers: hdr }).then((r) => r.json()) const links = (metas.info || []) .filter((m) => m.dlink) .map((m) => ({ label: m.filename, url: m.dlink + (cookie.includes('BDUSS') ? '&access_token=' : ''), note: fmtSize(m.size) + ' · 需带 Cookie 访问' })) if (!links.length) return simpleNote('百度网盘', '取直链失败(百度对非会员限制直链,建议用官方客户端)') return { ok: true, kind: '百度网盘', name: links[0].label, links, note: '百度直链需带登录 Cookie 才能下载' } } function fmtSize(n) { if (!n) return '' const u = ['B', 'KB', 'MB', 'GB', 'TB'] let i = 0 let v = Number(n) while (v >= 1024 && i < u.length - 1) { v /= 1024 i++ } return v.toFixed(v < 10 ? 1 : 0) + u[i] } export function toolsStatus() { return { ytdlp: YTDLP, ffmpeg: FFMPEG, pick: ['lanzou', 'aliyun', 'baidu'] } }