// ==UserScript== // @name 抖音优化(画质调节+视频下载 合并版) // @namespace https://github.com/WhiteSevs/TamperMonkeyScript // @version 1.0.0 // @author WhiteSevs(合并改造) // @description 合并版:①固定视频清晰度(4K/2K/1080P/720P/540P/极速/智能)+ 解锁更高画质;②无水印视频/音乐/图文下载(播放器下载按钮 + 分享面板下载拦截,备用地址自动重试、进度显示可取消、一键下载最佳画质、自定义文件名模板),零外部依赖 // @match *://*.douyin.com/* // @match *://*.iesdouyin.com/* // @exclude *://creator.douyin.com/* // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant GM_download // @grant GM_xmlhttpRequest // @grant unsafeWindow // @connect douyin.com // @connect douyinvod.com // @connect douyinpic.com // @connect snssdk.com // @connect bytecdn.cn // @connect bdurl.net // @connect * // @run-at document-start // @noframes // @license MIT // ==/UserScript== /* * 合并说明: * - 模块一(画质调节):来自《抖音画质调节》,完整保留 —— 固定清晰度、解锁更高画质、悬浮面板、油猴菜单。 * - 模块二(视频下载):从《抖音优化》中提取"解析下载"功能并重写为自包含实现,去除全部 @require 外部依赖。 * 保留:播放器下载按钮、分享面板"下载"拦截(无视"该视频不支持下载")、多清晰度/音乐/图文解析、 * 自定义文件名模板(占位符与原版一致)、下载前重命名弹窗开关。 * 优化:修复原版 DOM 解析中备用地址永远为空的 bug;清晰度去重并按分辨率降序; * 下载失败自动切换备用地址;GM_download 不可用时自动降级 GM_xmlhttpRequest; * 下载进度提示 + 可取消;一键下载最佳画质;弹窗内容 HTML 转义。 */ (function () { "use strict"; /* ================================================================ * 模块一:画质调节 * ================================================================ */ (function () { "use strict"; /* ============================ 基础配置 ============================ */ var W = typeof unsafeWindow !== "undefined" ? unsafeWindow : window; // 抖音播放器读取的 sessionStorage 键(原脚本中选择清晰度的核心就是往这里写数据) var KEY_MANUAL = "MANUAL_SWITCH"; var CFG = { gear: "dy_quality_gear", unlock: "dy_quality_unlock", panel: "dy_quality_panel", pos: "dy_quality_pos", }; // 高码率清晰度映射(来自抖音播放器内部数据结构) var CLARITY_UHD = [ "adapt_lowest_4_1", "normal_1080_0", "adapt_lowest_1440_1", "low_720_0", "normal_720_0", "low_540_0", "normal_540_0", "adapt_lowest_1080_1", "lower_540_0", "adapt_low_540_0", "720_2_1", "540_2_1", "540_3_1", ]; var CLARITY_FHD = [ "normal_1080_0", "normal_1080_0", "normal_720_0", "low_720_0", "normal_540_0", "low_720_0", "low_540_0", "low_540_0", "lower_540_0", "adapt_low_540_0", "adapt_low_540_0", "adapt_lowest_1080_1", "720_2_1", "720_2_1", "720_3_1", "540_2_1", "720_3_1", "540_2_1", "720_4_1", "720_4_1", "540_3_1", "540_3_1", ]; var GEARS = [ { id: "4k", short: "4K", full: "超清 4K", payload: { done: 1, gearClarity: "20", qualityType: 72, gearName: "超清 4K", gearType: -2, clarityReal: CLARITY_UHD, }, }, { id: "2k", short: "2K", full: "超清 2K", payload: { done: 1, gearClarity: "10", qualityType: 7, gearName: "超清 2K", gearType: -1, clarityReal: CLARITY_UHD, }, }, { id: "1080", short: "1080P", full: "高清 1080P", payload: { done: 1, gearClarity: "5", gearName: "高清 1080P", gearType: 1, clarityReal: CLARITY_FHD, qualityType: 1, }, }, { id: "720", short: "720P", full: "高清 720P", payload: { done: 1, gearClarity: "4", gearName: "高清 720P", gearType: 2, clarityReal: CLARITY_FHD, qualityType: 10, }, }, { id: "540", short: "540P", full: "标清 540P", payload: { done: 1, gearClarity: "3", gearName: "标清 540P", gearType: 3, clarityReal: CLARITY_FHD, qualityType: 20, }, }, { id: "fast", short: "极速", full: "极速", payload: { done: 1, gearClarity: "2", gearName: "极速", gearType: 4, qualityType: 21, }, }, { id: "auto", short: "智能", full: "智能", payload: { done: 1, gearClarity: "0", gearName: "智能", gearType: 0, clarityReal: CLARITY_FHD, }, }, ]; /* ============================ 存储读写 ============================ */ var hasGM = typeof GM_getValue === "function" && typeof GM_setValue === "function"; function readCfg(key, fallback) { try { if (hasGM) { var v = GM_getValue(key, null); return v === null || v === undefined ? fallback : v; } var raw = localStorage.getItem(key); return raw === null ? fallback : JSON.parse(raw); } catch (e) { return fallback; } } function writeCfg(key, value) { try { if (hasGM) GM_setValue(key, value); else localStorage.setItem(key, JSON.stringify(value)); } catch (e) { /* ignore */ } } var state = { gear: readCfg(CFG.gear, "1080"), unlock: readCfg(CFG.unlock, true), panel: readCfg(CFG.panel, true), pos: readCfg(CFG.pos, null), }; if (state.gear !== "off" && !findGear(state.gear)) state.gear = "1080"; /* ============================ 画质控制 ============================ */ function findGear(id) { for (var i = 0; i < GEARS.length; i++) { if (GEARS[i].id === id) return GEARS[i]; } return null; } function labelOf(id) { if (id === "off") return "不干预"; var g = findGear(id); return g ? g.short : "1080P"; } function currentGear() { return findGear(state.gear); } // 优先使用页面上下文的 sessionStorage(沙箱环境下更保险) function pageSession() { try { return W.sessionStorage || sessionStorage; } catch (e) { return null; } } // 沙箱直写失败时,通过注入页面脚本兜底(防 unsafeWindow 受限) function writeViaPageScript(payloadStr) { try { var s = document.createElement("script"); s.textContent = 'try{sessionStorage.setItem("' + KEY_MANUAL + '",' + payloadStr + ')}catch(e){}'; (document.head || document.documentElement).appendChild(s); s.remove(); var ss = pageSession(); return !!(ss && ss.getItem(KEY_MANUAL) === payloadStr); } catch (e) { return false; } } var warnedWriteFail = false; // 单次写入:把选中的画质参数写进播放器的 sessionStorage // 增强:写入后读回校验,失败自动换注入方式重写,再失败给出可见提示 function writeOnce() { var gear = currentGear(); if (!gear) return; var payloadStr = JSON.stringify(gear.payload); var ss = pageSession(); var ok = false; if (ss) { try { var raw = ss.getItem(KEY_MANUAL); if (raw) { try { if (JSON.parse(raw).gearName === gear.payload.gearName) return true; } catch (e) { /* 旧值不是 JSON,直接覆盖 */ } } ss.setItem(KEY_MANUAL, payloadStr); ok = ss.getItem(KEY_MANUAL) === payloadStr; } catch (e) { /* ignore */ } } if (!ok) ok = writeViaPageScript(payloadStr); if (!ok && !warnedWriteFail) { warnedWriteFail = true; toast("画质写入失败,请检查脚本管理器权限"); } return ok; } // 连续写入一段时间,覆盖播放器初始化时机(原脚本为 200ms x 5s) var burstTimer = 0; var burstStop = 0; function applyQuality(duration) { if (!currentGear()) return; if (state.unlock) unlockHighQuality(); // 每次应用时补一次,兼顾页面后写入的 A/B 标记 writeOnce(); clearInterval(burstTimer); clearTimeout(burstStop); burstTimer = setInterval(writeOnce, 250); burstStop = setTimeout(function () { clearInterval(burstTimer); }, duration || 4000); } // 解锁更高画质:伪装设备性能 + 改写 A/B 实验标记(原脚本 hookVideoQuality 的同源做法) function unlockHighQuality() { try { Object.defineProperty(W.navigator, "hardwareConcurrency", { get: function () { return 16; }, configurable: true, }); Object.defineProperty(W.navigator, "deviceMemory", { get: function () { return 64; }, configurable: true, }); } catch (e) { /* ignore */ } try { var ls = W.localStorage; var keys = []; for (var i = 0; i < ls.length; i++) { var k = ls.key(i); if (k && k.indexOf("__tea_sdk_ab_version_") === 0) keys.push(k); } keys.forEach(function (key) { var data = JSON.parse(ls.getItem(key) || "{}"); if (!data || typeof data !== "object" || !data.data) return; data.data.exposure_defination = { val: 1, vid: "" }; data.data.has_2k = { val: 1, vid: "" }; data.data.has_hdr = { val: 1, vid: "" }; ls.setItem(key, JSON.stringify(data)); }); } catch (e) { /* ignore */ } } function setGear(id, silent) { state.gear = id; writeCfg(CFG.gear, id); if (id === "off") { try { var ss = pageSession(); if (ss) ss.removeItem(KEY_MANUAL); } catch (e) { /* ignore */ } if (!silent) toast("已恢复默认(不干预)"); } else { applyQuality(5000); if (!silent) toast("画质:" + labelOf(id)); } renderUI(); registerMenu(); } /* ============================ 触发时机 ============================ */ var lastHref = location.href; var lastSrc = ""; function startWatcher() { setInterval(function () { // 站内路由切换(SPA) if (location.href !== lastHref) { lastHref = location.href; applyQuality(3000); } // 视频源切换(上下滑 / 下一个视频) var video = document.querySelector("video"); var src = video ? video.currentSrc || video.src || "" : ""; if (src && src !== lastSrc) { lastSrc = src; applyQuality(3000); } // 常驻守护:MANUAL_SWITCH 被外部(其他脚本/页面)覆盖时立即恢复 if (state.gear !== "off") writeOnce(); }, 700); } /* ============================ 悬浮面板 ============================ */ var CSS = [ ".box{position:relative;display:flex;flex-direction:column;align-items:flex-start;", 'font:12px/1.45 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;', "color:#e9e9ee;user-select:none;}", ".pill{display:flex;align-items:center;gap:6px;height:28px;padding:0 11px;border-radius:14px;", "background:rgba(25,25,30,.82);border:1px solid rgba(255,255,255,.14);", "box-shadow:0 2px 12px rgba(0,0,0,.4);cursor:grab;white-space:nowrap;backdrop-filter:blur(8px);}", ".pill:active{cursor:grabbing;}", ".dot{width:6px;height:6px;border-radius:50%;background:#22d3a5;box-shadow:0 0 6px rgba(34,211,165,.8);}", ".pill.off .dot{background:#8a8a93;box-shadow:none;}", ".name{font-size:12px;font-weight:600;letter-spacing:.3px;}", ".menu{display:none;position:absolute;left:0;bottom:34px;width:180px;padding:6px;", "border-radius:12px;background:rgba(22,22,26,.94);border:1px solid rgba(255,255,255,.12);", "box-shadow:0 10px 28px rgba(0,0,0,.55);backdrop-filter:blur(10px);}", ".menu.open{display:block;}", ".menu.down{top:34px;bottom:auto;}", ".title{padding:4px 8px 6px;font-size:11px;color:#94949c;}", ".item{display:flex;align-items:center;justify-content:space-between;padding:6px 8px;", "border-radius:8px;cursor:pointer;}", ".item:hover{background:rgba(255,255,255,.08);}", ".item.active{background:rgba(254,44,85,.16);}", ".item .tick{font-size:11px;color:#fe2c55;visibility:hidden;}", ".item.active .tick{visibility:visible;}", ".sep{height:1px;margin:5px 6px;background:rgba(255,255,255,.08);}", ".row{display:flex;align-items:center;justify-content:space-between;padding:5px 8px;", "border-radius:8px;cursor:pointer;color:#c9c9d1;}", ".row:hover{background:rgba(255,255,255,.08);}", ".sw{position:relative;width:26px;height:14px;border-radius:7px;background:#3b3b44;", "transition:background .15s;}", ".sw i{position:absolute;top:2px;left:2px;width:10px;height:10px;border-radius:50%;", "background:#fff;transition:left .15s;}", ".sw.on{background:#fe2c55;}", ".sw.on i{left:14px;}", ".hint{padding:5px 8px 3px;font-size:10px;line-height:1.5;color:#77777f;}", ".toast{position:absolute;left:calc(100% + 8px);bottom:6px;padding:4px 9px;border-radius:7px;", "background:rgba(0,0,0,.85);color:#fff;font-size:11px;white-space:nowrap;opacity:0;", "transform:translateX(-4px);transition:opacity .18s,transform .18s;pointer-events:none;}", ".toast.show{opacity:1;transform:translateX(0);}", ].join(""); var host = null; var root = null; var pillEl = null; var nameEl = null; var menuEl = null; var toastEl = null; var swEl = null; var toastTimer = 0; function toast(text) { if (!toastEl) return; toastEl.textContent = text; toastEl.classList.add("show"); clearTimeout(toastTimer); toastTimer = setTimeout(function () { toastEl.classList.remove("show"); }, 1600); } function renderUI() { if (!root) return; nameEl.textContent = labelOf(state.gear); pillEl.classList.toggle("off", state.gear === "off"); Array.prototype.forEach.call(root.querySelectorAll("[data-gear]"), function (el) { el.classList.toggle("active", el.getAttribute("data-gear") === state.gear); }); swEl.classList.toggle("on", !!state.unlock); host.style.display = state.panel ? "" : "none"; } // 菜单靠近屏幕顶部时翻转到下方显示 function fitMenu() { if (!menuEl) return; menuEl.classList.remove("down"); if (!menuEl.classList.contains("open")) return; if (menuEl.getBoundingClientRect().top < 8) menuEl.classList.add("down"); } function ensureUI() { if (host || !document.body) return; host = document.createElement("div"); host.id = "dy-quality-host"; host.style.cssText = "position:fixed;left:16px;bottom:120px;z-index:2147483000;"; root = host.attachShadow({ mode: "open" }); var items = GEARS.map(function (g) { return '
' + g.full + '✓
'; }).join(""); root.innerHTML = "" + '
' + '" + '
--
' + '
' + "
"; pillEl = root.querySelector(".pill"); nameEl = root.querySelector(".name"); menuEl = root.querySelector(".menu"); toastEl = root.querySelector(".toast"); swEl = root.querySelector(".sw"); document.body.appendChild(host); // 恢复上次拖拽位置 if (state.pos && typeof state.pos.left === "number" && typeof state.pos.top === "number") { host.style.left = state.pos.left + "px"; host.style.top = state.pos.top + "px"; host.style.bottom = "auto"; } // 菜单点击 menuEl.addEventListener("click", function (e) { var item = e.target.closest ? e.target.closest("[data-gear]") : null; if (item) { setGear(item.getAttribute("data-gear")); menuEl.classList.remove("open"); return; } var row = e.target.closest ? e.target.closest("[data-act]") : null; if (row && row.getAttribute("data-act") === "unlock") { state.unlock = !state.unlock; writeCfg(CFG.unlock, state.unlock); if (state.unlock) { unlockHighQuality(); toast("已开启:尝试解锁更高画质"); } else { toast("已关闭解锁更高画质"); } renderUI(); return; } }); // 拖拽 + 点击展开 var drag = null; pillEl.addEventListener("pointerdown", function (e) { if (e.button !== 0) return; var rect = host.getBoundingClientRect(); drag = { x: e.clientX, y: e.clientY, left: rect.left, top: rect.top, moved: false }; try { pillEl.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ } }); pillEl.addEventListener("pointermove", function (e) { if (!drag) return; var dx = e.clientX - drag.x; var dy = e.clientY - drag.y; if (!drag.moved && Math.abs(dx) + Math.abs(dy) < 4) return; drag.moved = true; var maxLeft = Math.max(0, window.innerWidth - host.offsetWidth); var maxTop = Math.max(0, window.innerHeight - host.offsetHeight); host.style.left = Math.min(Math.max(0, drag.left + dx), maxLeft) + "px"; host.style.top = Math.min(Math.max(0, drag.top + dy), maxTop) + "px"; host.style.bottom = "auto"; }); pillEl.addEventListener("pointerup", function (e) { if (!drag) return; var moved = drag.moved; drag = null; try { pillEl.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ } if (moved) { state.pos = { left: parseFloat(host.style.left) || 0, top: parseFloat(host.style.top) || 0 }; writeCfg(CFG.pos, state.pos); fitMenu(); } else { menuEl.classList.toggle("open"); fitMenu(); } }); // 点空白处收起 document.addEventListener( "pointerdown", function (e) { if (!menuEl.classList.contains("open")) return; if (e.composedPath && e.composedPath().indexOf(host) !== -1) return; menuEl.classList.remove("open"); }, true ); renderUI(); } /* ============================ 菜单命令 ============================ */ var menuIds = []; function unregisterMenu() { if (typeof GM_unregisterMenuCommand !== "function") return; menuIds.forEach(function (id) { try { GM_unregisterMenuCommand(id); } catch (e) { /* ignore */ } }); menuIds.length = 0; } function registerMenu() { if (typeof GM_registerMenuCommand !== "function") return; unregisterMenu(); var mark = function (id) { return state.gear === id ? "✓ " : " "; }; GEARS.forEach(function (g) { var id = GM_registerMenuCommand(mark(g.id) + g.full, function () { setGear(g.id); }); if (id !== undefined) menuIds.push(id); }); menuIds.push( GM_registerMenuCommand(mark("off") + "不干预(跟随默认)", function () { setGear("off"); }) ); menuIds.push( GM_registerMenuCommand(state.panel ? "隐藏悬浮面板" : "显示悬浮面板", function () { state.panel = !state.panel; writeCfg(CFG.panel, state.panel); if (root) host.style.display = state.panel ? "" : "none"; registerMenu(); }) ); } /* ============================ 启动 ============================ */ if (state.unlock) unlockHighQuality(); applyQuality(6000); function boot() { if (state.unlock) unlockHighQuality(); applyQuality(6000); ensureUI(); registerMenu(); } if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", boot, { once: true }); } else { boot(); } // body 尚未就绪时兜底挂载 var mountTimer = setInterval(function () { if (document.body) { ensureUI(); clearInterval(mountTimer); } }, 300); startWatcher(); })(); /* ================================================================ * 模块二:视频下载(解析下载 —— 自包含重写版) * 功能:播放器下载按钮 / 分享面板下载拦截 / 多清晰度解析 / * 音乐 / 图文下载 / 备用地址自动重试 / 进度提示可取消 / * 一键最佳画质 / 自定义文件名模板 * ================================================================ */ (function () { "use strict"; var W = typeof unsafeWindow !== "undefined" ? unsafeWindow : window; /* ---------------- 配置 ---------------- */ var CFG = { rename: "dydl_popupRename", template: "dydl_fileNameTemplate", musicTemplate: "dydl_musicFileNameTemplate", showBtn: "dydl_showDownloadButton", shareHook: "dydl_shareHook", }; var hasGM = typeof GM_getValue === "function" && typeof GM_setValue === "function"; function readCfg(key, fallback) { try { if (hasGM) { var v = GM_getValue(key, null); return v === null || v === undefined ? fallback : v; } var raw = localStorage.getItem(key); return raw === null ? fallback : JSON.parse(raw); } catch (e) { return fallback; } } function writeCfg(key, value) { try { if (hasGM) GM_setValue(key, value); else localStorage.setItem(key, JSON.stringify(value)); } catch (e) { /* ignore */ } } // 文件名模板默认值与原版《抖音优化》一致 var dl = { rename: readCfg(CFG.rename, false), template: readCfg(CFG.template, "{uid}-{nickname}-{desc}-{quality}-{downloadTime}"), musicTemplate: readCfg(CFG.musicTemplate, "{author}-{title}-{duration}-{downloadTime}"), showBtn: readCfg(CFG.showBtn, true), shareHook: readCfg(CFG.shareHook, true), }; /* ---------------- 通用工具 ---------------- */ function esc(s) { return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); } function pad(n) { return n < 10 ? "0" + n : "" + n; } function nowStr() { var d = new Date(); return ( d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()) + "_" + pad(d.getHours()) + "_" + pad(d.getMinutes()) + "_" + pad(d.getSeconds()) ); } function formatBytes(n) { n = Number(n) || 0; if (n <= 0) return "未知大小"; var units = ["B", "KB", "MB", "GB"]; var i = 0; var v = n; while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; } return (i === 0 ? v : v.toFixed(v >= 100 ? 0 : 1)) + " " + units[i]; } // 中文习惯计数:1.2万 / 3.5亿 function formatCount(n) { n = Number(n); if (!isFinite(n) || n < 0) return "—"; if (n >= 1e8) return (n / 1e8).toFixed(n % 1e8 === 0 ? 0 : 1) + "亿"; if (n >= 1e4) return (n / 1e4).toFixed(n % 1e4 === 0 ? 0 : 1) + "万"; return String(n); } function parseDuration(ms) { ms = Number(ms) || 0; if (ms <= 0) return "未知时长"; var s = Math.round(ms / 1000); return Math.floor(s / 60) + ":" + pad(s % 60); } // 清晰度标记(与原版一致:8K/4K/2K/xxxP) function qualityTag(w, h) { w = Number(w) || 0; h = Number(h) || 0; var max = Math.max(w, h); var min = Math.min(w, h); if (max > 1920 && min > 1080) { if (max > 7000 && max < 9000) return "8K"; if (max > 3500) return "4K"; if (max > 2000) return "2K"; return min + "P"; } return (min || max || "?") + "P"; } function picExt(url) { var m = String(url || "").match(/image\.([a-z0-9]+)/i); if (m) return m[1].toLowerCase() === "jpeg" ? "jpg" : m[1].toLowerCase(); m = String(url || "").match(/\.(png|jpe?g|webp|heic|avif)(?:$|\?)/i); if (m) return m[1].toLowerCase() === "jpeg" ? "jpg" : m[1].toLowerCase(); return "jpg"; } function buildFileName(template, vars) { var name = template; Object.keys(vars).forEach(function (k) { var v = vars[k]; if (v == null) return; name = name.split("{" + k + "}").join(String(v)); }); name = name .replace(/[:?"*<>|~/\\]/g, "_") .replace(/[\u0001-\u001f\u007f]/g, "_") .replace(/^[\s.]+/, "") .replace(/[\s.]+$/, ""); if (!name) name = "douyin_" + Date.now(); return name; } function fallbackCopy(text) { try { var ta = document.createElement("textarea"); ta.value = text; ta.style.cssText = "position:fixed;left:-9999px;top:0;"; document.body.appendChild(ta); ta.select(); var ok = document.execCommand("copy"); ta.remove(); return ok; } catch (e) { return false; } } function copyText(text) { return new Promise(function (resolve) { try { if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then( function () { resolve(true); }, function () { resolve(fallbackCopy(text)); } ); return; } } catch (e) { /* ignore */ } resolve(fallbackCopy(text)); }); } /* ---------------- React Fiber 解析 ---------------- */ function getReactFiber(el) { if (!el || el.nodeType !== 1) return null; var keys = Object.keys(el); for (var i = 0; i < keys.length; i++) { if (keys[i].indexOf("__reactFiber$") === 0 || keys[i].indexOf("__reactInternalInstance$") === 0) return el[keys[i]]; } return null; } // 沿 fiber.return 向上查找 memoizedProps.awemeInfo(同时兼容 DOM/网络两种数据结构) function findAwemeInfo(startEl) { var node = startEl; for (var i = 0; i < 12 && node; i++, node = node.parentElement) { var cur = getReactFiber(node); var depth = 0; while (cur && depth++ < 800) { var props = cur.memoizedProps; if (props && typeof props === "object") { var ai = props.awemeInfo; if (ai && typeof ai === "object" && (ai.awemeId != null || ai.aweme_id != null || ai.video || ai.images)) return ai; } cur = cur.return; } } return null; } /* ---------------- 视频数据解析 ---------------- */ // 解析清晰度列表(兼容 DOM 驼峰 / 网络下划线两种结构) // 优化点:修复原版 DOM 分支 backUrl 永远为空的 bug;同分辨率去重;按分辨率降序 function parseBitRateList(list) { var out = []; if (!Array.isArray(list)) return out; list.forEach(function (item) { if (!item || typeof item !== "object") return; var url = ""; var backUrl = []; var playAddr = item.playAddr || item.play_addr; if (typeof item.playApi === "string" && item.playApi) url = item.playApi; if (Array.isArray(playAddr)) { playAddr.forEach(function (p) { var src = ""; if (typeof p === "string") src = p; else if (p && typeof p.src === "string") src = p.src; if (!src) return; if (!url) url = src; else if (src !== url) backUrl.push(src); }); } else if (playAddr && Array.isArray(playAddr.url_list)) { playAddr.url_list.forEach(function (src) { if (typeof src !== "string" || !src) return; if (!url) url = src; else if (src !== url) backUrl.push(src); }); } if (!url) return; if (url.indexOf("http:") === 0) url = "https:" + url.slice(5); for (var b = 0; b < backUrl.length; b++) { if (backUrl[b].indexOf("http:") === 0) backUrl[b] = "https:" + backUrl[b].slice(5); } out.push({ bitRate: item.bitRate != null ? item.bitRate : item.bit_rate, dataSize: item.dataSize != null ? item.dataSize : item.play_addr ? item.play_addr.data_size || 0 : 0, format: item.format || "mp4", isH265: item.isH265 != null ? item.isH265 : item.is_h265, fps: item.fps != null ? item.fps : item.FPS, gearName: item.gearName != null ? item.gearName : item.gear_name, width: item.width != null ? item.width : item.play_addr ? item.play_addr.width : void 0, height: item.height != null ? item.height : item.play_addr ? item.play_addr.height : void 0, url: url, backUrl: backUrl, }); }); // 去重:同 分辨率+帧率 保留 dataSize 更大(更清晰)的 for (var i = 0; i < out.length; i++) { for (var j = i + 1; j < out.length; j++) { if (out[i].width === out[j].width && out[i].height === out[j].height && out[i].fps === out[j].fps) { if ((out[i].dataSize || 0) >= (out[j].dataSize || 0)) { out.splice(j, 1); j--; } else { out.splice(i, 1); i--; break; } } } } // 降序:最佳画质排最前 out.sort(function (a, b) { return (Number(b.width) || 0) - (Number(a.width) || 0); }); return out; } function parseAwemeInfo(awemeInfo) { var authorInfo = awemeInfo.authorInfo || awemeInfo.author || {}; var video = awemeInfo.video || {}; var music = awemeInfo.music || {}; var stats = awemeInfo.stats || awemeInfo.statistics || {}; var d = {}; d.nickname = String(authorInfo.nickname != null ? authorInfo.nickname : "") || "未知作者"; d.uid = String(authorInfo.uid != null ? authorInfo.uid : ""); d.desc = String(awemeInfo.desc != null ? awemeInfo.desc : "") || "未知视频文案"; d.originDesc = String(d.desc).replace(/ #(.+) /g, "").replace(/#(.+)/g, ""); d.awemeId = String( awemeInfo.awemeId != null ? awemeInfo.awemeId : awemeInfo.aweme_id != null ? awemeInfo.aweme_id : "" ); d.isPicture = awemeInfo.awemeType === 68 || awemeInfo.aweme_type === 68; d.videoBitRateList = parseBitRateList(video.bitRateList || video.bit_rate); /* 真实互动数据(DOM 版 stats 驼峰 / 网络版 statistics 下划线,双兼容) */ d.diggCount = stats.diggCount != null ? stats.diggCount : stats.digg_count; d.commentCount = stats.commentCount != null ? stats.commentCount : stats.comment_count; d.collectCount = stats.collectCount != null ? stats.collectCount : stats.collect_count; d.shareCount = stats.shareCount != null ? stats.shareCount : stats.share_count; // 播放量:多路径尝试(statistics.play_count / video.play_count / video.play) d.playCount = stats.playCount != null ? stats.playCount : stats.play_count != null ? stats.play_count : video.playCount != null ? video.playCount : video.play_count != null ? video.play_count : video.play && typeof video.play === "object" && video.play.play_count != null ? video.play.play_count : null; d.duration = video.duration != null ? video.duration : null; var playUrl = music.playUrl || music.play_url || {}; d.musicUrl = typeof playUrl.uri === "string" ? playUrl.uri : ""; if (d.musicUrl.indexOf("http:") === 0) d.musicUrl = "https:" + d.musicUrl.slice(5); d.musicBackUrlList = []; function collectMusicUrl(it) { if (typeof it === "string" && it && it !== d.musicUrl) { d.musicBackUrlList.push(it.indexOf("http:") === 0 ? "https:" + it.slice(5) : it); } } if (Array.isArray(playUrl.urlList)) playUrl.urlList.forEach(collectMusicUrl); if (Array.isArray(playUrl.url_list)) playUrl.url_list.forEach(collectMusicUrl); d.musicAuthor = music.author || d.nickname; d.musicAlbum = music.album || ""; d.musicTitle = music.title || "未知音乐"; d.musicDuration = music.duration || 0; d.pictureList = []; var images = awemeInfo.images; if (d.isPicture && Array.isArray(images)) { images.forEach(function (it) { var url = ""; var urlList = it.urlList || it.url_list; var dlList = it.downloadUrlList || it.download_url_list; if (Array.isArray(urlList) && urlList.length) url = urlList[0]; else if (Array.isArray(dlList) && dlList.length) url = dlList[0]; var pv = it.video || {}; d.pictureList.push({ url: typeof url === "string" ? url : "", width: it.width, height: it.height, videoBitRateList: parseBitRateList(pv.bitRateList || pv.bit_rate), }); }); } return d; } /* ---------------- 网络数据 hook(解析信息增强) ---------------- * 原版《抖音优化》优先使用 hook 到的 /aweme/v1/web/* 接口数据解析, * 网络版数据比 DOM 版完整得多:FPS、dataSize、gearName、多条备用 CDN 等。 * 在 document-start hook XHR/fetch,命中视频数据接口的响应存入 netMap, * 点击下载时优先用网络版(awemeId 匹配),DOM 版兜底。 * --------------------------------------------------------------- */ var netMap = new Map(); // awemeId -> 网络版 awemeInfo(下划线字段结构) function collectAwemeFromNet(json) { if (!json || typeof json !== "object") return; var list = []; try { if (json.aweme_detail && typeof json.aweme_detail === "object") list.push(json.aweme_detail); if (Array.isArray(json.aweme_list)) list = list.concat(json.aweme_list); if (Array.isArray(json.awemes)) list = list.concat(json.awemes); if (Array.isArray(json.data)) { json.data.forEach(function (it) { if (it && typeof it === "object" && it.aweme_info) list.push(it.aweme_info); }); } } catch (e) { return; } list.forEach(function (a) { if (!a || typeof a !== "object") return; var id = String(a.aweme_id != null ? a.aweme_id : a.awemeId != null ? a.awemeId : ""); if (!id || id === "undefined") return; netMap.delete(id); netMap.set(id, a); if (netMap.size > 100) { // 超出容量删除最旧一条(单条数据约100KB,控制内存) netMap.delete(netMap.keys().next().value); } }); } function isAwemeApiUrl(url) { url = String(url || ""); return url.indexOf("/aweme/") !== -1 || url.indexOf("/web/feed") !== -1; } /* ---- 性能设计:响应文本先入队,等浏览器空闲(requestIdleCallback)再 * 统一 JSON.parse —— 抖音接口响应可达数 MB,同步解析会与视频播放/滑动 * 抢主线程造成掉帧,空闲化后完全不干扰流畅度。 ---- */ var netParseQueue = []; var idleScheduled = false; function enqueueNetText(text) { if (!text || text.length < 2 || text.length > 1e7) return; netParseQueue.push(text); if (netParseQueue.length > 20) netParseQueue.shift(); // 只留最新,防堆积 scheduleIdleNetParse(); } function scheduleIdleNetParse() { if (idleScheduled) return; idleScheduled = true; var run = function () { idleScheduled = false; var batch = netParseQueue.splice(0, netParseQueue.length); batch.forEach(function (text) { try { collectAwemeFromNet(JSON.parse(text)); } catch (e) { /* ignore */ } }); }; if (typeof W.requestIdleCallback === "function") { W.requestIdleCallback(run, { timeout: 3000 }); } else { setTimeout(run, 800); } } function hookNetwork() { // hook XMLHttpRequest try { var xhrProto = W.XMLHttpRequest && W.XMLHttpRequest.prototype; if (xhrProto && !xhrProto.__dydl_hooked__) { var origOpen = xhrProto.open; var origSend = xhrProto.send; xhrProto.open = function (method, url) { try { this.__dydl_url = url; } catch (e) { /* ignore */ } return origOpen.apply(this, arguments); }; xhrProto.send = function () { try { var xhr = this; xhr.addEventListener("load", function () { try { var url = xhr.__dydl_url; if (!isAwemeApiUrl(url)) return; var text = ""; try { text = xhr.responseText; } catch (e2) { text = ""; } if (text) { enqueueNetText(text); } else if (xhr.response && typeof xhr.response === "object") { // responseType=json 时直接拿到对象,轻量直接收集 collectAwemeFromNet(xhr.response); } } catch (e) { /* ignore */ } }); } catch (e) { /* ignore */ } return origSend.apply(this, arguments); }; xhrProto.__dydl_hooked__ = true; } } catch (e) { /* ignore */ } // hook fetch try { if (typeof W.fetch === "function" && !W.fetch.__dydl_hooked__) { var origFetch = W.fetch; var wrapped = function () { var args = arguments; var p = origFetch.apply(W, args); try { var url = typeof args[0] === "string" ? args[0] : (args[0] && args[0].url) || ""; if (isAwemeApiUrl(url)) { p.then(function (res) { try { if (res && typeof res.clone === "function") { res .clone() .text() .then(function (text) { enqueueNetText(text); }) .catch(function () {}); } } catch (e) { /* ignore */ } }).catch(function () {}); } } catch (e) { /* ignore */ } return p; }; try { wrapped.__dydl_hooked__ = true; } catch (e) { /* ignore */ } W.fetch = wrapped; } } catch (e) { /* ignore */ } } // document-start 立刻 hook,赶在页面首批视频请求发出之前 hookNetwork(); /* ---------------- 下载进度 Toast ---------------- */ var toastHost = null; var toastTextEl = null; var toastCloseEl = null; var toastPill = null; var toastTimer = 0; var currentAbort = null; // 用户主动取消(区别于看门狗自动中止:主动取消不再重试) var userCancelled = false; function ensureToast() { if (toastHost || !document.body) return; toastHost = document.createElement("div"); toastHost.id = "dydl-toast-host"; toastHost.style.cssText = "position:fixed;right:20px;bottom:80px;z-index:2147483500;"; var root = toastHost.attachShadow({ mode: "open" }); root.innerHTML = "" + '
' + '
'; toastPill = root.querySelector(".pill"); toastTextEl = root.querySelector(".txt"); toastCloseEl = root.querySelector(".cancel"); toastCloseEl.addEventListener("click", function () { userCancelled = true; if (typeof currentAbort === "function") { try { currentAbort(); } catch (e) { /* ignore */ } } hideDlToast(); }); document.body.appendChild(toastHost); } function showDlToast(text, type, cancelable) { ensureToast(); if (!toastHost) return; toastTextEl.textContent = text; toastPill.className = "pill show" + (type ? " " + type : ""); toastCloseEl.style.display = cancelable ? "" : "none"; clearTimeout(toastTimer); } function autoHideDlToast(ms) { clearTimeout(toastTimer); toastTimer = setTimeout(hideDlToast, ms || 1800); } function hideDlToast() { if (toastPill) toastPill.classList.remove("show"); currentAbort = null; } /* ---------------- 下载引擎 ---------------- * 带两项防卡死机制(解决"下载到 98%/99% 卡死"的问题): * 1. 卡死看门狗:进度 ≥95% 后停滞 8 秒、或任意阶段 30 秒无新进度, * 自动中止当前下载并自动重试(换 GM_xmlhttpRequest 通道 → 换备用地址)。 * 2. 双通道降级:GM_download 失败/卡死后用 GM_xmlhttpRequest 拉取 blob 再保存, * 下载完成即触发保存,不存在"最后一刻挂起"。 * 手动点 ✕ 取消不会触发重试。 * ------------------------------------------------ */ function attemptGMDownload(url, fileName, onProgress, cb) { if (typeof GM_download !== "function") { cb(false, false); return; } var finished = false; var lastPercent = -1; var lastChange = Date.now(); var report = function (ok) { if (finished) return; finished = true; clearInterval(watchdog); currentAbort = null; cb(ok, userCancelled); }; // 卡死看门狗 var watchdog = setInterval(function () { var stall = Date.now() - lastChange; if ((lastPercent >= 95 && stall > 8000) || stall > 30000) { if (typeof currentAbort === "function") { try { currentAbort(); } catch (e) { /* ignore */ } } else report(false); } }, 1000); try { var result = GM_download({ url: url, name: fileName, headers: { Referer: W.location.href }, onload: function () { report(true); }, onprogress: function (d) { if (d && typeof d.loaded === "number" && typeof d.total === "number" && d.total > 0) { var p = (d.loaded / d.total) * 100; if (Math.abs(p - lastPercent) > 0.05) { lastPercent = p; lastChange = Date.now(); } onProgress(p.toFixed(1)); } }, onerror: function () { report(false); }, ontimeout: function () { report(false); }, }); if (result && typeof result.abort === "function") currentAbort = result.abort; } catch (e) { report(false); } } function attemptXhrDownload(url, fileName, onProgress, cb) { if (typeof GM_xmlhttpRequest !== "function") { cb(false, false); return; } var finished = false; var lastChange = Date.now(); var report = function (ok) { if (finished) return; finished = true; clearInterval(watchdog); currentAbort = null; cb(ok, userCancelled); }; // 卡死看门狗:任意阶段 45 秒无新进度则中止 var watchdog = setInterval(function () { if (Date.now() - lastChange > 45000) { if (typeof currentAbort === "function") { try { currentAbort(); } catch (e) { /* ignore */ } } else report(false); } }, 1000); try { var req = GM_xmlhttpRequest({ method: "GET", url: url, headers: { Referer: W.location.href }, responseType: "blob", timeout: 300000, onload: function (res) { if (res && res.status >= 200 && res.status < 300 && res.response) { try { var blobUrl = URL.createObjectURL(res.response); var a = document.createElement("a"); a.href = blobUrl; a.download = fileName; document.body.appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(blobUrl); }, 60000); report(true); } catch (e) { report(false); } } else report(false); }, onerror: function () { report(false); }, ontimeout: function () { report(false); }, onprogress: function (d) { if (d && typeof d.loaded === "number" && typeof d.total === "number" && d.total > 0) { lastChange = Date.now(); onProgress(((d.loaded / d.total) * 100).toFixed(1)); } }, }); if (req && typeof req.abort === "function") currentAbort = req.abort; } catch (e) { report(false); } } function downloadResource(url, fileName, backUrls) { if (dl.rename) { var renamed = W.prompt("请确认下载的文件名", fileName); if (typeof renamed !== "string") return; // 用户取消 if (renamed.trim()) fileName = renamed.trim(); } userCancelled = false; var candidates = [url].concat(Array.isArray(backUrls) ? backUrls.filter(Boolean) : []); var index = 0; function done() { showDlToast("下载完成:" + fileName, "ok"); autoHideDlToast(2500); } function cancelled() { showDlToast("已取消下载", ""); autoHideDlToast(1500); } function onProg(p) { showDlToast("下载中... " + p + "%", "", true); } function tryNext() { if (userCancelled) { cancelled(); return; } if (index >= candidates.length) { showDlToast("所有地址(" + candidates.length + " 个)均下载失败,已在新标签页打开直链,可右键另存", "err"); autoHideDlToast(5000); W.open(url, "_blank"); return; } var current = candidates[index++]; showDlToast("下载中... " + fileName, "", true); attemptGMDownload( current, fileName, onProg, function (ok, isCancelled) { if (userCancelled || isCancelled) { cancelled(); return; } if (ok) { done(); return; } // GM_download 失败/卡死中止,降级 GM_xmlhttpRequest 拉取 blob 重新下载 showDlToast("下载异常,正在换通道重试...", "", true); attemptXhrDownload( current, fileName, onProg, function (ok2, isCancelled2) { if (userCancelled || isCancelled2) { cancelled(); return; } if (ok2) { done(); return; } tryNext(); // 自动切换下一个备用地址 } ); } ); } tryNext(); } /* ---------------- 解析结果弹窗 ---------------- */ var dlgHost = null; function closeDialog() { if (dlgHost) { dlgHost.remove(); dlgHost = null; } } var DLG_CSS = [ ":host{position:fixed;inset:0;z-index:2147483600;}", ".mask{position:absolute;inset:0;background:rgba(0,0,0,.45);display:flex;align-items:center;justify-content:center;padding:20px;box-sizing:border-box;}", '.dlg{width:min(580px,92vw);max-height:84vh;display:flex;flex-direction:column;background:#1d1d24;color:#e9e9ee;border-radius:14px;box-shadow:0 18px 48px rgba(0,0,0,.5);overflow:hidden;font:13px/1.5 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif;}', ".dlg-head{display:flex;align-items:center;gap:10px;padding:12px 16px;border-bottom:1px solid rgba(255,255,255,.08);flex:none;}", ".dlg-title{font-weight:600;flex:1;font-size:14px;}", ".best-btn{flex:none;padding:6px 12px;border:none;border-radius:8px;background:#fe2c55;color:#fff;cursor:pointer;font-size:12px;white-space:nowrap;}", ".best-btn:hover{background:#e6274d;}", ".dlg-close{cursor:pointer;font-size:18px;color:#9494a0;padding:2px 6px;flex:none;}", ".dlg-close:hover{color:#fff;}", ".dlg-body{overflow:auto;padding:6px 16px 16px;}", ".info{margin:10px 0;padding:10px 12px;background:rgba(255,255,255,.05);border-radius:10px;}", ".info-row{display:flex;gap:6px;margin:2px 0;}", ".info-row .k{color:#9494a0;flex:none;}", ".info-row .v{word-break:break-all;}", ".sec-title{margin:14px 0 6px;font-size:12px;color:#9494a0;}", ".row{display:flex;align-items:center;gap:8px;padding:8px 10px;border-radius:10px;margin-bottom:6px;background:rgba(255,255,255,.04);flex-wrap:wrap;}", ".row:hover{background:rgba(255,255,255,.08);}", ".badge{min-width:46px;text-align:center;padding:2px 6px;border-radius:6px;background:#fe2c55;color:#fff;font-weight:600;font-size:12px;flex:none;}", ".meta{color:#c9c9d1;flex:1;min-width:0;}", ".tag{font-style:normal;font-size:10px;padding:1px 5px;border-radius:4px;background:rgba(255,255,255,.14);color:#c9c9d1;margin-left:4px;}", ".size{color:#9494a0;font-size:12px;flex:none;}", ".dl-btn{padding:5px 14px;border:none;border-radius:8px;background:#fe2c55;color:#fff;cursor:pointer;font-size:12px;flex:none;}", ".dl-btn:hover{background:#e6274d;}", ".grid{display:flex;flex-wrap:wrap;gap:8px;}", ".card{position:relative;width:132px;height:132px;border-radius:10px;overflow:hidden;cursor:pointer;background:rgba(255,255,255,.06);}", ".card img{width:100%;height:100%;object-fit:cover;display:block;}", ".card:hover img{opacity:.75;}", ".tag-video{position:absolute;top:6px;left:6px;background:rgba(0,0,0,.72);color:#4f8cff;font-size:11px;padding:2px 7px;border-radius:6px;cursor:pointer;}", ".tag-size{position:absolute;bottom:6px;right:6px;background:rgba(0,0,0,.72);color:#fff;font-size:11px;padding:2px 7px;border-radius:6px;}", ".link-line{width:100%;display:flex;gap:8px;align-items:center;font-size:11px;color:#77777f;min-width:0;}", ".link-line .k{flex:none;}", ".link-line .url{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}", ".link-line a.op{color:#6ea8ff;cursor:pointer;flex:none;text-decoration:none;}", ".link-line a.op:hover{text-decoration:underline;}", ].join(""); function baseVars(d) { return { downloadTime: nowStr(), uid: d.uid, nickname: d.nickname, desc: d.desc, originDesc: d.originDesc, awemeId: d.awemeId, }; } function buildVideoFileName(d, info) { var vars = baseVars(d); vars.quality = (info.width || "?") + "x" + (info.height || "?") + (info.fps ? " @" + info.fps : ""); vars["quality-t"] = qualityTag(info.width, info.height); var ext = String(info.format || "mp4").replace(/[^a-z0-9]/gi, "") || "mp4"; return buildFileName(dl.template, vars) + "." + ext; } function buildMusicFileName(d) { var vars = { album: d.musicAlbum, author: d.musicAuthor, title: d.musicTitle, duration: parseDuration(d.musicDuration), downloadTime: nowStr(), }; return buildFileName(dl.musicTemplate, vars) + ".mp3"; } function buildPicFileName(d, pic) { var vars = baseVars(d); var size = (pic.width || "?") + "x" + (pic.height || "?"); vars.quality = size; vars["quality-t"] = size; return buildFileName(dl.template, vars) + "." + picExt(pic.url); } function buildDialogHTML(d) { var html = ""; html += '
'; html += '
视频解析(' + (d.isFromNet ? "NetWork" : "DOM") + ")" + (d.subTitle ? " · " + esc(d.subTitle) : "") + "
"; if (d.videoBitRateList.length) html += ''; html += '✕
'; html += '
'; html += '
' + '
作者:' + esc(d.nickname) + "
" + '
文案:' + esc(d.desc) + "
" + '
数据:👍 ' + formatCount(d.diggCount) + " · 💬 " + formatCount(d.commentCount) + " · ⭐ " + formatCount(d.collectCount) + " · ↗ " + formatCount(d.shareCount) + " · ▶ " + formatCount(d.playCount) + (d.duration ? " · ⏱ " + parseDuration(d.duration) : "") + "
"; if (d.videoBitRateList.length) { html += '
视频(' + d.videoBitRateList.length + ")
"; d.videoBitRateList.forEach(function (info, i) { html += '
' + esc(qualityTag(info.width, info.height)) + ""; html += '' + (info.width || "?") + "x" + (info.height || "?") + (info.fps ? " @" + esc(String(info.fps)) + "fps" : ""); if (info.isH265) html += 'H.265'; if (info.gearName) html += '' + esc(String(info.gearName)) + ""; html += ""; html += '' + (info.dataSize ? formatBytes(info.dataSize) : "未知大小"); if (info.backUrl && info.backUrl.length) html += "|备用" + info.backUrl.length; html += ""; html += ''; // 解析信息:下载地址直链(与原版弹窗信息一致) html += ''; if (info.backUrl && info.backUrl.length) { html += '"; } html += "
"; }); } if (d.musicUrl) { html += '
音乐
'; html += '
' + esc(d.musicTitle); if (d.musicAuthor) html += " - " + esc(d.musicAuthor); html += "|" + parseDuration(d.musicDuration); if (d.musicAlbum) html += "|专辑:" + esc(d.musicAlbum); if (d.musicBackUrlList.length) html += "|备用" + d.musicBackUrlList.length; html += ""; html += ''; html += ''; if (d.musicBackUrlList.length) { html += '"; } html += "
"; } if (d.pictureList.length) { html += '
图片(' + d.pictureList.length + ",点击图片下载)
"; html += '
'; d.pictureList.forEach(function (pic, i) { if (!pic.url) return; html += '
'; html += ''; if (pic.videoBitRateList && pic.videoBitRateList.length) html += '▶ 视频'; html += '' + (pic.width || "?") + "x" + (pic.height || "?") + ""; html += "
"; }); html += "
"; } html += "
"; return html; } function showParseDialog(d) { closeDialog(); ensureToast(); if (!document.body) return; dlgHost = document.createElement("div"); dlgHost.id = "dydl-dialog-host"; var root = dlgHost.attachShadow({ mode: "open" }); root.innerHTML = "" + buildDialogHTML(d); document.body.appendChild(dlgHost); root.querySelector(".dlg-close").addEventListener("click", closeDialog); var mask = root.querySelector(".mask"); mask.addEventListener("click", function (e) { if (e.target === mask) closeDialog(); }); // 事件委托:下载按钮 / 图片视频版本 / 直链复制与打开 root.addEventListener("click", function (e) { var target = e.target; if (!(target instanceof Element)) return; var picVideo = target.closest("[data-pic-video]"); if (picVideo) { e.preventDefault(); e.stopPropagation(); var idx = Number(picVideo.getAttribute("data-pic-video")); var pic = d.pictureList[idx]; if (pic && pic.videoBitRateList && pic.videoBitRateList.length) { showParseDialog({ nickname: d.nickname, uid: d.uid, desc: d.desc, originDesc: d.originDesc, awemeId: d.awemeId, isFromNet: d.isFromNet, videoBitRateList: pic.videoBitRateList, musicUrl: "", musicBackUrlList: [], musicAuthor: "", musicAlbum: "", musicTitle: "", musicDuration: 0, pictureList: [], subTitle: "图片 " + (idx + 1) + " 的视频版本", }); } return; } var copyBtn = target.closest("[data-copy]"); if (copyBtn) { e.preventDefault(); e.stopPropagation(); var cu = ""; if (copyBtn.getAttribute("data-copy") === "video") { var vi = d.videoBitRateList[Number(copyBtn.getAttribute("data-index"))]; cu = vi ? vi.url : ""; } else if (copyBtn.getAttribute("data-copy") === "music") { cu = d.musicUrl; } if (cu) { copyText(cu).then(function (ok) { showDlToast(ok ? "已复制下载直链" : "复制失败", ok ? "ok" : "err"); autoHideDlToast(1500); }); } return; } var backBtn = target.closest("[data-copy-back]"); if (backBtn) { e.preventDefault(); e.stopPropagation(); var bv = d.videoBitRateList[Number(backBtn.getAttribute("data-copy-back"))]; var bu = bv && bv.backUrl ? bv.backUrl[Number(backBtn.getAttribute("data-bindex"))] : ""; if (bu) { copyText(bu).then(function (ok) { showDlToast(ok ? "已复制备用地址" : "复制失败", ok ? "ok" : "err"); autoHideDlToast(1500); }); } return; } var musicBackBtn = target.closest("[data-copy-music-back]"); if (musicBackBtn) { e.preventDefault(); e.stopPropagation(); var mu = d.musicBackUrlList[Number(musicBackBtn.getAttribute("data-copy-music-back"))]; if (mu) { copyText(mu).then(function (ok) { showDlToast(ok ? "已复制备用地址" : "复制失败", ok ? "ok" : "err"); autoHideDlToast(1500); }); } return; } var openBtn = target.closest("[data-open]"); if (openBtn) { e.preventDefault(); e.stopPropagation(); var ou = ""; if (openBtn.getAttribute("data-open") === "video") { var oi = d.videoBitRateList[Number(openBtn.getAttribute("data-index"))]; ou = oi ? oi.url : ""; } else if (openBtn.getAttribute("data-open") === "music") { ou = d.musicUrl; } if (ou) W.open(ou, "_blank"); return; } var btn = target.closest("[data-dl]"); if (btn) { e.preventDefault(); e.stopPropagation(); handleDialogDownload(btn, d); } }); } function handleDialogDownload(btn, d) { var kind = btn.getAttribute("data-dl"); if (kind === "video") { var info = d.videoBitRateList[Number(btn.getAttribute("data-index"))]; if (!info) return; downloadResource(info.url, buildVideoFileName(d, info), info.backUrl); } else if (kind === "music") { downloadResource(d.musicUrl, buildMusicFileName(d), d.musicBackUrlList); } else if (kind === "pic") { var pic = d.pictureList[Number(btn.getAttribute("data-index"))]; if (!pic || !pic.url) return; downloadResource(pic.url, buildPicFileName(d, pic), []); } else if (kind === "best") { var best = d.videoBitRateList[0]; if (!best) return; downloadResource(best.url, buildVideoFileName(d, best), best.backUrl); } } /* ---------------- 解析入口 ---------------- */ // 优先网络版(信息更全),DOM 版兜底;返回 { d, isFromNet } function resolveAwemeData(awemeInfo) { var d = parseAwemeInfo(awemeInfo); var isFromNet = false; if (d.awemeId && netMap.size) { var netRaw = netMap.get(d.awemeId); if (netRaw) { var dn = parseAwemeInfo(netRaw); if (dn.videoBitRateList.length || dn.pictureList.length) { d = dn; isFromNet = true; } } } return { d: d, isFromNet: isFromNet }; } function onClickParse(el) { try { if (el && el.closest && el.closest('[data-e2e="feed-live"]')) { showDlToast("无法解析直播视频的下载信息", "err"); autoHideDlToast(2500); return; } var awemeInfo = findAwemeInfo(el); if (!awemeInfo) { showDlToast("获取视频数据失败,请稍后重试", "err"); autoHideDlToast(2500); return; } var result = resolveAwemeData(awemeInfo); var d = result.d; if (!d.videoBitRateList.length && !d.pictureList.length) { showDlToast("未解析出有效的资源信息", "err"); autoHideDlToast(2500); return; } d.isFromNet = result.isFromNet; showParseDialog(d); } catch (err) { showDlToast("解析视频失败:" + (err && err.message ? err.message : err), "err"); autoHideDlToast(3000); } } function findVideoContainer() { return ( document.querySelector(".basePlayerContainer") || document.querySelector("#slidelist video") || document.querySelector("video") ); } function downloadCurrentVideo() { var el = findVideoContainer(); if (!el) { showDlToast("当前页面未找到视频", "err"); autoHideDlToast(2500); return; } onClickParse(el); } function downloadBestQuality() { var el = findVideoContainer(); if (!el) { showDlToast("当前页面未找到视频", "err"); autoHideDlToast(2500); return; } try { var awemeInfo = findAwemeInfo(el); if (!awemeInfo) throw new Error("获取视频数据失败"); var d = resolveAwemeData(awemeInfo).d; var best = d.videoBitRateList[0]; if (!best) throw new Error("未解析出视频下载信息"); downloadResource(best.url, buildVideoFileName(d, best), best.backUrl); } catch (err) { showDlToast("下载失败:" + (err && err.message ? err.message : err), "err"); autoHideDlToast(3000); } } /* ---------------- 播放器下载按钮 ---------------- */ var BTN_CLASS = "gm-video-download-btn"; var mountTimer = 0; function isLivePage() { return W.location.pathname.indexOf("/live") === 0; } function createPlayerButton(isDy) { var $btn = document.createElement(isDy ? "dy-icon" : "xg-icon"); $btn.className = BTN_CLASS; $btn.innerHTML = '
' + '' + '' + '' + "
" + '
下载
'; if (isDy) { var tips = $btn.querySelector(".xg-tips"); if (tips) tips.remove(); var icon = $btn.querySelector(".xgplayer-icon"); $btn.style.display = "flex"; $btn.style.alignItems = "center"; if (icon) { icon.style.height = "auto"; icon.style.lineHeight = "unset"; } } $btn.addEventListener("click", function (event) { event.preventDefault(); event.stopPropagation(); onClickParse($btn); }); return $btn; } function mountPlayerButtons() { if (!dl.showBtn || isLivePage() || !document.body) return; var grids = document.querySelectorAll(".basePlayerContainer xg-right-grid"); for (var i = 0; i < grids.length; i++) { if (!grids[i].querySelector("." + BTN_CLASS)) { grids[i].insertBefore(createPlayerButton(false), grids[i].firstChild); } } var rights = document.querySelectorAll(".basePlayerContainer .douyin-player-controls-right"); for (var j = 0; j < rights.length; j++) { if (!rights[j].querySelector("." + BTN_CLASS)) { rights[j].insertBefore(createPlayerButton(true), rights[j].firstChild); } } } function scheduleMount() { // 500ms 节流:抖音 DOM 高频变动(弹幕/动画),避免密集回调抢主线程 clearTimeout(mountTimer); mountTimer = setTimeout(mountPlayerButtons, 500); } function removePlayerButtons() { var btns = document.querySelectorAll("." + BTN_CLASS); for (var i = 0; i < btns.length; i++) btns[i].remove(); } /* ---------------- 分享面板"下载"拦截(无视"该视频不支持下载"提示) ---------------- */ function shareHookHandler(e) { if (!dl.shareHook) return; var target = e.target; if (!target || !(target instanceof Element)) return; var container = target.closest('[data-e2e="video-share-container"]'); if (!container) return; var menu = container.querySelector('div[data-inuser="false"]'); if (!menu) return; var downloadDiv = menu.querySelector("button + div"); if (!downloadDiv || !downloadDiv.contains(target)) return; e.preventDefault(); e.stopPropagation(); onClickParse(downloadDiv); } /* ---------------- 油猴菜单 ---------------- */ var dlMenuIds = []; function unregisterDlMenu() { if (typeof GM_unregisterMenuCommand !== "function") return; dlMenuIds.forEach(function (id) { try { GM_unregisterMenuCommand(id); } catch (e) { /* ignore */ } }); dlMenuIds.length = 0; } function registerDlMenu() { if (typeof GM_registerMenuCommand !== "function") return; unregisterDlMenu(); var add = function (text, fn) { var id = GM_registerMenuCommand(text, fn); if (id !== undefined) dlMenuIds.push(id); }; add("⬇ 下载当前视频(解析弹窗)", downloadCurrentVideo); add("⏫ 一键下载最佳画质", downloadBestQuality); add((dl.rename ? "✅ " : "⬜ ") + "下载前弹窗重命名文件名", function () { dl.rename = !dl.rename; writeCfg(CFG.rename, dl.rename); registerDlMenu(); }); add("📝 修改下载文件名模板", function () { var v = W.prompt( "文件名模板,可用占位符:\n" + "{uid} 作者ID {nickname} 作者名\n" + "{desc} 视频描述 {originDesc} 描述(不含话题)\n" + "{awemeId} 视频ID\n" + "{quality} 清晰度(1920x1080 @30) {quality-t} 清晰度(1080P/2K/4K)\n" + "{downloadTime} 下载时间", dl.template ); if (typeof v === "string" && v.trim()) { dl.template = v.trim(); writeCfg(CFG.template, dl.template); showDlToast("文件名模板已保存", "ok"); autoHideDlToast(2000); } }); add((dl.showBtn ? "✅ " : "⬜ ") + "播放器控制栏显示下载按钮", function () { dl.showBtn = !dl.showBtn; writeCfg(CFG.showBtn, dl.showBtn); if (!dl.showBtn) removePlayerButtons(); else mountPlayerButtons(); registerDlMenu(); }); add((dl.shareHook ? "✅ " : "⬜ ") + "拦截分享面板的下载按钮", function () { dl.shareHook = !dl.shareHook; writeCfg(CFG.shareHook, dl.shareHook); registerDlMenu(); }); } /* ---------------- 启动 ---------------- */ function boot() { registerDlMenu(); document.addEventListener("click", shareHookHandler, true); var mo = new MutationObserver(scheduleMount); mo.observe(document.documentElement, { subtree: true, childList: true }); mountPlayerButtons(); // 低频兜底巡检(按钮挂载后不变,3秒足够,避免空转抢主线程) setInterval(mountPlayerButtons, 3000); document.addEventListener("keydown", function (e) { if (e.key === "Escape") closeDialog(); }); } if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", boot, { once: true }); } else { boot(); } })(); })();