// ==UserScript==
// @name 嘟嘟噜追番助手:全网看番自动打卡/断点续播/直达集数 (支持 B站/巴哈/AGE/樱花/全网嗅探)
// @name:en Dudulu Scrobbler: Auto Tracking, Resume Playback & Smart Jump for Anime
// @namespace https://dudulu.moe/
// @version 1.0.53
// @description 看番自动记录进度至嘟嘟噜 (dudulu.moe)!支持根据追番记录智能直达目标集数与秒级断点续播,全网播放站点自动识别打卡,未追新番智能引导一键入库,告别手动打卡!
// @description:en Auto-sync your anime watching progress to Dudulu (dudulu.moe)! Supports smart episode jump, resume playback, and auto scrobbling across major anime streaming platforms.
// @author Dudulu Team
// @license MIT
// @icon https://dudulu.moe/icon.png
// @homepageURL https://dudulu.moe/
// @supportURL https://dudulu.moe/
// @match *://*/*
// @match https://dudulu.moe/*
// @match https://www.dudulu.moe/*
// @match https://test.dudulu.moe/*
// @match http://localhost:3001/*
// @match http://localhost:3000/*
// @match *://*.bilibili.com/*
// @match *://*.gamer.com.tw/*
// @match *://*.agedm.io/*
// @match *://*.agedm.vip/*
// @match *://*.agemys.net/*
// @match *://*.agemys.com/*
// @match *://*.agefans.com/*
// @match *://*.age.tv/*
// @match *://*.yhdm.tv/*
// @match *://*.yhdmp.cc/*
// @match *://*.yhdmp.net/*
// @match *://*.dm530.net/*
// @match *://*.iyinghua.com/*
// @match *://*.iyinghua.io/*
// @match *://*.xifanacg.com/*
// @match *://*.next.xifanacg.com/*
// @match *://*.xifan.tv/*
// @match *://*.anime1.me/*
// @match *://*.iqiyi.com/*
// @match *://*.v.qq.com/*
// @match *://*.youku.com/*
// @match *://*.acfun.cn/*
// @allFrames true
// @grant unsafeWindow
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @connect dudulu.moe
// @connect www.dudulu.moe
// @connect test.dudulu.moe
// @connect localhost
// @connect 127.0.0.1
// @run-at document-end
// ==/UserScript==
(function () {
'use strict';
const currentHost = location.hostname.toLowerCase();
// 默认服务端接口地址 (正式环境: https://dudulu.moe / 测试环境: https://test.dudulu.moe)
const DEFAULT_API_BASE = 'https://dudulu.moe';
const STORAGE_KEY_API_BASE = 'dudulu_scrobbler_api_base';
const STORAGE_KEY_TOKEN = 'dudulu_scrobbler_token';
const STORAGE_KEY_USER_NAME = 'dudulu_scrobbler_user_name';
const STORAGE_KEY_USER_ID = 'dudulu_scrobbler_user_id';
const STORAGE_KEY_SHOW_HUD = 'dudulu_scrobbler_debug_hud_v2';
const STORAGE_KEY_AUTO_SCROBBLE = 'dudulu_scrobbler_auto_scrobble';
function detectApiBase() {
if (currentHost.includes('test.dudulu.moe')) {
return 'https://test.dudulu.moe';
}
if (currentHost === 'dudulu.moe' || currentHost === 'www.dudulu.moe') {
return 'https://dudulu.moe';
}
if (currentHost === 'localhost' || currentHost === '127.0.0.1' || currentHost.startsWith('192.168.')) {
return `${location.protocol}//${location.hostname}:8080`;
}
return DEFAULT_API_BASE;
}
const isDuduluSite =
currentHost === 'dudulu.moe' ||
currentHost === 'www.dudulu.moe' ||
currentHost.includes('test.dudulu.moe') ||
currentHost === 'localhost' ||
currentHost === '127.0.0.1' ||
currentHost.startsWith('192.168.');
// 专有动漫主流平台列表
const KNOWN_ANIME_PLATFORMS = [
'bilibili.com',
'gamer.com.tw',
'agefans',
'agemys',
'age',
'yhdm',
'iyinghua',
'xifan',
'anime1.me',
'iqiyi.com',
'v.qq.com',
'youku.com',
'acfun.cn',
];
function isKnownPlatform() {
return KNOWN_ANIME_PLATFORMS.some((p) => currentHost.includes(p));
}
// 严格路径与物理元素校验:检查当前页面是否为实际视频播放路径 (非播放页如主页/搜索/专栏/非视频网页等,直接终止不运行)
function isPlaybackPage() {
if (currentHost.includes('bilibili.com')) {
return location.pathname.includes('/video/') || location.pathname.includes('/bangumi/play/');
}
if (currentHost.includes('gamer.com.tw')) {
return location.pathname.includes('/animeVideo.php');
}
if (currentHost.includes('iqiyi.com')) {
return location.pathname.includes('/v_');
}
if (currentHost.includes('v.qq.com')) {
return location.pathname.includes('/x/cover/');
}
if (currentHost.includes('youku.com')) {
return location.pathname.includes('/v_show/');
}
if (currentHost.includes('acfun.cn')) {
return location.pathname.includes('/v/ac') || location.pathname.includes('/bangumi/aa');
}
// 专门动漫网站(AGE、樱花、稀饭、Anime1 等)其主要页面均属动漫观看/选集,默认支持
if (isKnownPlatform()) {
return true;
}
// 通用第三方网站:页面必须存在 video、bwp-video 或 iframe 标签才可能是播放页
// (像 animecorner.me 等无任何视频/外链标签的纯内容网页,直接快速退出,零干扰)
return !!document.querySelector('video, bwp-video, iframe');
}
const isTopWindow = window === window.top;
function initIframeVideoBridge() {
let bridgeVideo = null;
const sendProgress = () => {
if (!bridgeVideo || !bridgeVideo.duration || isNaN(bridgeVideo.duration)) return;
// 物理门槛:过滤贴片广告与超短试看(时长必须 >= 60 秒)
if (!isKnownPlatform() && bridgeVideo.duration < 60) return;
try {
const msg = {
type: 'DUDULU_IFRAME_PROGRESS',
currentTime: bridgeVideo.currentTime,
duration: bridgeVideo.duration,
ended: bridgeVideo.ended,
};
if (window.top) window.top.postMessage(msg, '*');
if (window.parent && window.parent !== window.top) window.parent.postMessage(msg, '*');
} catch (e) {}
};
const attachBridge = () => {
let v = document.querySelector('video') || document.querySelector('bwp-video');
if (!v) {
const all = document.querySelectorAll('*');
for (let i = 0; i < all.length; i++) {
if (all[i].shadowRoot) {
const sv = all[i].shadowRoot.querySelector('video, bwp-video');
if (sv) {
v = sv;
break;
}
}
}
}
if (v && v !== bridgeVideo) {
bridgeVideo = v;
bridgeVideo.addEventListener('timeupdate', sendProgress);
bridgeVideo.addEventListener('seeked', sendProgress);
bridgeVideo.addEventListener('pause', sendProgress);
bridgeVideo.addEventListener('playing', sendProgress);
bridgeVideo.addEventListener('ended', sendProgress);
bridgeVideo.addEventListener('loadedmetadata', sendProgress);
bridgeVideo.addEventListener('durationchange', sendProgress);
bridgeVideo.addEventListener('canplay', sendProgress);
sendProgress();
}
};
attachBridge();
setInterval(attachBridge, 800);
// 监听来自宿主顶层页面的快进/断点续播 Seek 指令 (支持透传至嵌套子 iframe)
window.addEventListener('message', (e) => {
if (e.data && e.data.type === 'DUDULU_SEEK_TO' && typeof e.data.time === 'number') {
if (bridgeVideo) {
try {
bridgeVideo.currentTime = e.data.time;
} catch (err) {}
}
document.querySelectorAll('iframe').forEach((ifr) => {
try {
ifr.contentWindow.postMessage(e.data, '*');
} catch (err) {}
});
}
});
}
// ==========================================
// 0. 子 Iframe 专用:视频播放监听与跨域消息中继桥
// (解决 AGE动漫、樱花动漫等外部解析器 iframe 无法获取番名,以及顶层页面抓不到 cross-origin video 的问题)
// 注意:必须置于顶层播放页熔断之前执行,因为外链解析 iframe 域名属于第三方且其 video 元素通常异步生成!
// ==========================================
if (!isTopWindow) {
initIframeVideoBridge();
return; // 子 iframe 绝不渲染 HUD,绝不独立向后端打卡
}
// 嘟嘟噜主站授权握手 (在嘟嘟噜主站直接进入授权握手流程,无需执行播放嗅探与视频页面检查)
if (isDuduluSite) {
initDuduluSiteHandshake();
return;
}
// 0. 顶层非播放页面快速熔断:若当前页面在非播放路径,直接彻底终止,零内存侵占
if (!isPlaybackPage()) {
return;
}
console.log(
'%c[嘟嘟噜助手] 脚本已加载: ' + location.href,
'color: #00A1D6; font-weight: bold; font-size: 13px; background: #E6F4FA; padding: 4px 8px; border-radius: 4px;'
);
let currentMatchedAnime = null; // 经嘟嘟噜识别关联的番剧元数据 { id, title, totalEp, watchedEp, nextEp, lastTimeSec }
let lastProgressInfo = { currentTime: 0, duration: 0, ratio: 0, ended: false };
function decodeTokenUserId(token) {
if (!token || typeof token !== 'string') return 0;
try {
const parts = token.split('.');
if (parts.length < 2) return 0;
const base64Url = parts[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
atob(base64)
.split('')
.map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
.join('')
);
const parsed = JSON.parse(jsonPayload);
return parsed.uid || parsed.user_id || parsed.sub || 0;
} catch (e) {
return 0;
}
}
function getEffectiveUserId() {
const uid = GM_getValue(STORAGE_KEY_USER_ID, 0);
if (uid) return uid;
return decodeTokenUserId(getToken());
}
function getPlaybackStorageKey() {
const uid = getEffectiveUserId();
return uid ? `dudulu_scrobbler_playback_user_${uid}` : null;
}
// 强制清理历史版本可能残留为 true 的 HUD 状态,确保默认绝对不显示 HUD
if (typeof GM_deleteValue === 'function') {
GM_deleteValue('dudulu_scrobbler_show_hud');
}
const AUTO_SCROBBLE_RULES =
'【🐾 嘟嘟噜追番助手 · 自动记录规则说明】\n\n' +
'1. 📺 常规单集番剧(20 ~ 45 分钟):\n' +
' 观看满 20 分钟 或 进度达到 85% 自动记录进度(完美契合跳过片尾曲/下集预告的习惯);\n\n' +
'2. 🍜 泡面番 / 短番(时长不足 20 分钟):\n' +
' 观看进度达到 85% 自动记录进度;\n\n' +
'3. 🎬 剧场版 / 特别篇(时长超过 45 分钟):\n' +
' 观看进度达到 85% 自动记录进度;\n\n' +
'4. 🏁 视频播完 (Ended):\n' +
' 直接自动打卡完成本集。\n\n' +
'💡 提示:若关闭自动记录,可通过油猴菜单【⚡ 手动记录当前播放进度】或 HUD 按钮随时手动打卡!';
function getApiBase() {
return GM_getValue(STORAGE_KEY_API_BASE, DEFAULT_API_BASE);
}
function getToken() {
return GM_getValue(STORAGE_KEY_TOKEN, '');
}
function getUserName() {
return GM_getValue(STORAGE_KEY_USER_NAME, '');
}
function isShowHud() {
return GM_getValue(STORAGE_KEY_SHOW_HUD, false); // 默认不显示 HUD
}
function setShowHud(val) {
GM_setValue(STORAGE_KEY_SHOW_HUD, !!val);
if (hudElement) {
hudElement.style.display = val ? 'block' : 'none';
if (val) updateDebugHUD();
}
}
function isAutoScrobble() {
return GM_getValue(STORAGE_KEY_AUTO_SCROBBLE, true); // 默认开启自动记录
}
function setAutoScrobble(val) {
GM_setValue(STORAGE_KEY_AUTO_SCROBBLE, !!val);
updateDebugHUD();
}
function getRealWindow() {
return typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
}
// 注册油猴扩展菜单 (每次点击实时读取最新值,操作直观零门槛)
if (typeof GM_registerMenuCommand === 'function') {
GM_registerMenuCommand('📌 点击查看账号 / 连接状态', () => {
const token = getToken();
const user = getUserName();
const apiBase = getApiBase();
if (token) {
alert(
`🎉 嘟嘟噜追番助手【已连接】\n\n• 当前用户: ${user || '已授权用户'}\n• 接口服务: ${apiBase}\n• 自动记录: ${isAutoScrobble() ? '已开启 ✓' : '已关闭 ✕'}\n\n全网看番将自动同步打卡!`
);
} else {
alert(
`❌ 嘟嘟噜追番助手【尚未绑定】\n\n请在当前浏览器打开并登录嘟嘟噜 (https://dudulu.moe 或 https://test.dudulu.moe),页面将全自动握手授权,无需手动配置!`
);
}
});
GM_registerMenuCommand('⚡ 手动记录当前播放进度', () => {
manualTriggerScrobble();
});
GM_registerMenuCommand(
'⏱️ 切换自动记录进度开关 (当前: ' + (isAutoScrobble() ? '开启中' : '已关闭') + ')',
() => {
const next = !isAutoScrobble();
setAutoScrobble(next);
if (next) {
showToast('已开启自动记录进度 (看满20分钟或85%自动打卡)', 'success', 4000);
} else {
showToast('已关闭自动记录进度 (仍可点击菜单手动记录)', 'info', 4000);
}
}
);
GM_registerMenuCommand('📖 查看自动记录进度规则说明', () => {
alert(AUTO_SCROBBLE_RULES);
});
GM_registerMenuCommand('💬 遇到问题?向嘟嘟噜提交反馈 / 申请收录', () => {
showFeedbackModal();
});
GM_registerMenuCommand('🖥️ 切换 HUD 浮窗显示 (当前: ' + (isShowHud() ? '显示中' : '已隐藏') + ')', () => {
const next = !isShowHud();
setShowHud(next);
showToast(next ? '已开启播放监听 HUD 浮窗' : '已隐藏播放监听 HUD 浮窗', 'info', 3000);
});
}
// ==========================================
// 1. 嘟嘟噜主站授权握手 (Auth Handshake)
// ==========================================
function initDuduluSiteHandshake() {
// 确保彻底移除主站悬浮徽章,保持页面极简无感
const existing = document.getElementById('dudulu-scrobbler-site-badge');
if (existing) existing.remove();
window.addEventListener('dudulu_scrobbler_ready', (e) => {
if (e.detail && e.detail.token) {
const uid = e.detail.userId || decodeTokenUserId(e.detail.token);
saveAndShowSuccess(e.detail.token, e.detail.user, uid);
}
});
window.addEventListener('dudulu_scrobbler_logout', () => {
if (getApiBase() === detectApiBase()) {
GM_deleteValue(STORAGE_KEY_TOKEN);
GM_deleteValue(STORAGE_KEY_USER_NAME);
GM_deleteValue(STORAGE_KEY_USER_ID);
console.log('[嘟嘟噜助手] 嘟嘟噜主站账号已退出,已同步清理油猴凭据');
}
});
let retryCount = 0;
const pollAuth = () => {
retryCount++;
let token = '';
let userName = '';
let userId = 0;
if (document.body) {
token = document.body.getAttribute('data-dudulu-token') || '';
userName = document.body.getAttribute('data-dudulu-user') || '';
userId = parseInt(document.body.getAttribute('data-dudulu-uid') || '0', 10) || 0;
}
if (!token) {
const realWin = getRealWindow();
try {
token =
realWin.localStorage?.getItem('dudulu_jwt_token_v2') ||
localStorage.getItem('dudulu_jwt_token_v2') ||
'';
const userRaw =
realWin.localStorage?.getItem('dudulu_auth_user_v2') ||
localStorage.getItem('dudulu_auth_user_v2') ||
'';
if (userRaw) {
const u = JSON.parse(userRaw);
userName = u.name || u.nick || '';
if (u.id) userId = u.id;
}
} catch (err) {
console.warn('[嘟嘟噜助手] 读取 storage 失败:', err);
}
}
if (token) {
if (!userId) userId = decodeTokenUserId(token);
saveAndShowSuccess(token, userName, userId);
} else if (retryCount < 10) {
setTimeout(pollAuth, 300);
} else {
// 主站轮询结束确认无登录态,若当前环境与绑定的环境一致则同步清空,防止换号或登出残留
const currentToken = getToken();
if (currentToken && getApiBase() === detectApiBase()) {
GM_deleteValue(STORAGE_KEY_TOKEN);
GM_deleteValue(STORAGE_KEY_USER_NAME);
GM_deleteValue(STORAGE_KEY_USER_ID);
console.log('[嘟嘟噜助手] 主站当前未登录,已同步清空旧账号凭据');
}
}
};
setTimeout(pollAuth, 100);
}
function saveAndShowSuccess(token, userName, userId) {
GM_setValue(STORAGE_KEY_TOKEN, token);
if (userName) GM_setValue(STORAGE_KEY_USER_NAME, userName);
if (userId) GM_setValue(STORAGE_KEY_USER_ID, userId);
const targetApiBase = detectApiBase();
GM_setValue(STORAGE_KEY_API_BASE, targetApiBase);
const existing = document.getElementById('dudulu-scrobbler-site-badge');
if (existing) existing.remove();
console.log('[嘟嘟噜助手] 账号握手成功,已关联用户:', userName || '已授权', '环境:', targetApiBase);
}
// ==========================================
// 2. 动画元数据与纯净标题解析算法
// ==========================================
const NOISE_WORDS_REGEX =
/(?:4k|1080p|720p|hevc|x264|x265|60fps|hdr|合集|全集|未删减|生肉|熟肉|无修|更新|国语|中字|双语|纯享|周更|日更|中文字幕|英文字幕|双语字幕|简日|繁日|aac|mp4|mkv|\d+月|新番|完结|全\s*\d+\s*[集话回]|先行|pv|cm|特报|预告|花絮|特典|oad|ova|sp|剧场版|最终回|下集预告|独家|首播|独播|漫剪|高能|开局|反转|慎入|字幕组|汉化组|压制|搬运|正片搬运|出品|分段|reaction|自制|视频选集|选集|合集详情|播放列表|分P|多P|相关视频|推荐视频)/i;
// 中文/阿拉伯数字混合解析器 (支持 "第2话"、"第二话"、"十二" 等格式)
function parseChineseOrArabicNumber(str) {
if (!str) return 1;
const num = parseInt(str, 10);
if (!isNaN(num) && num > 0) return num;
const cnMap = {
一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5,
六: 6, 七: 7, 八: 8, 九: 9, 十: 10,
};
const trimmed = String(str).trim();
if (trimmed.length === 1 && cnMap[trimmed]) return cnMap[trimmed];
if (trimmed.length === 2) {
if (trimmed.startsWith('十')) return 10 + (cnMap[trimmed[1]] || 0);
if (trimmed.endsWith('十')) return (cnMap[trimmed[0]] || 1) * 10;
}
if (trimmed.length === 3 && trimmed[1] === '十') {
return (cnMap[trimmed[0]] || 1) * 10 + (cnMap[trimmed[2]] || 0);
}
return 1;
}
function extractCleanAnimeTitle(rawText) {
if (!rawText) return '';
const raw = String(rawText).trim();
// 1. 扫描所有中文/日文/英文括号对: 『 』 「 」 《 》 【 】 [ ]
const epIndex = raw.search(
/(?:第\s*(?:\d+|[一二三四五六七八九十]+)\s*[集话回期季]|全\s*(?:\d+|[一二三四五六七八九十]+)\s*[集话回]|\b(?:ep|e)\s*\d+)/i
);
const bracketRegex = /[『「《【\[](.*?)[』」》】\]]/g;
let m;
const candidates = [];
while ((m = bracketRegex.exec(raw)) !== null) {
const cand = m[1].trim();
const candPos = m.index;
// 若括号位于集数之后且为「」,通常为单集副标题(例如 第03话「欧吉桑」),跳过
if (epIndex !== -1 && candPos > epIndex && raw[candPos] === '「') {
continue;
}
if (cand && !NOISE_WORDS_REGEX.test(cand) && cand.length >= 2) {
candidates.push(cand);
}
}
if (candidates.length > 0) {
// 优先取书名号《》或日式书名引号『』中的正统番名,其次取【】或「」或[]
const bookQuote = candidates.find((c) => raw.includes(`《${c}》`) || raw.includes(`『${c}』`));
return bookQuote || candidates[0];
}
// 2. 无可用括号时,剥离集数与噪声文本提取前缀
let prefix = epIndex !== -1 ? raw.substring(0, epIndex) : raw;
let clean = prefix
.replace(/[『「《【\[](.*?)[』」》】\]]/g, (match, inner) => {
return NOISE_WORDS_REGEX.test(inner.trim()) ? ' ' : inner;
})
.replace(/[《》『』「」【】\[\]()()]/g, ' ')
.replace(/[-_].*$/, ' ')
.replace(/\s+/g, ' ')
.trim();
if (clean && !NOISE_WORDS_REGEX.test(clean) && clean.length >= 2) {
return clean;
}
return '';
}
// 提取 B站页面 __INITIAL_STATE__ 全局元数据 (同时兼容普通页面上下文、Tampermonkey unsafeWindow 与扩展内容脚本 DOM 穿透)
function getBilibiliInitialState() {
try {
const realWin = getRealWindow();
if (realWin && realWin.__INITIAL_STATE__) return realWin.__INITIAL_STATE__;
} catch (e) {}
try {
if (window.__INITIAL_STATE__) return window.__INITIAL_STATE__;
} catch (e) {}
try {
const scripts = document.querySelectorAll('script:not([src])');
for (let i = 0; i < scripts.length; i++) {
const text = scripts[i].textContent || '';
if (text.includes('__INITIAL_STATE__')) {
const m = text.match(/window\.__INITIAL_STATE__\s*=\s*(\{.*?\});/);
if (m) {
return JSON.parse(m[1]);
}
}
}
} catch (e) {}
return null;
}
// 提取 B站视频主分区 (如: 动画、番剧、国创、影视、游戏、科技等)
function getBilibiliChannel() {
const initState = getBilibiliInitialState();
if (initState && initState.videoData) {
const vd = initState.videoData;
if (vd.tname) return vd.tname.trim();
if (vd.tname_v2) return vd.tname_v2.trim();
// B站官方分类体系 tid 精确映射 (当 tname 为空时权威判定)
const animeTids = [1, 13, 24, 25, 27, 32, 33, 47, 51, 86, 152, 153, 167, 168, 169, 170, 195, 210];
if (animeTids.includes(Number(vd.tid))) {
return '动画';
}
if (Number(vd.tid_v2) === 2004) {
return '影视正片搬运';
}
}
try {
const scripts = document.querySelectorAll('script[type="application/ld+json"]');
for (let i = 0; i < scripts.length; i++) {
const json = JSON.parse(scripts[i].textContent || '{}');
if (Array.isArray(json.genre) && json.genre.length > 0) {
return json.genre[0].trim();
}
if (Array.isArray(json.itemListElement) && json.itemListElement.length >= 2) {
return json.itemListElement[1].name ? json.itemListElement[1].name.trim() : '';
}
}
} catch (e) {}
const crumbLink = document.querySelector('.crumbs-item a, .video-crumbs a, .crumb-item a, a.channel-link');
if (crumbLink && crumbLink.textContent) {
return crumbLink.textContent.trim();
}
return '';
}
// 纯非动漫主分区黑名单正则
const NON_ANIME_CHANNELS_REGEX = /^(?:游戏|数码|科技|生活|知识|鬼畜|汽车|时尚|娱乐|运动|舞蹈|音乐|美食|动物圈|资讯)/i;
// 综合多维度裁定当前 B站视频是否属于动漫打卡范围 (防止非动漫视频干扰用户,同时精准覆盖 UP 主搬运/影视区动漫)
function isAnimeBilibiliVideo(channel, rawTitle) {
// 1. 若主分区为正统动画、番剧、国创或影视正片搬运,直接确认为动漫视频
if (channel && /^(?:动画|番剧|国创|影视正片搬运)/i.test(channel)) {
return true;
}
const initState = getBilibiliInitialState();
// 2. 根据 B站权威 tid 判定
const animeTids = [1, 13, 24, 25, 27, 32, 33, 47, 51, 86, 152, 153, 167, 168, 169, 170, 195, 210];
if (initState?.videoData?.tid && animeTids.includes(Number(initState.videoData.tid))) {
return true;
}
if (Number(initState?.videoData?.tid_v2) === 2004) {
return true;
}
// 3. 视频标签 (Tags):若标签中显式包含 新番/番剧/漫改/动漫/动画/二次元/国创 等动漫硬核标签
const tags = [];
if (Array.isArray(initState?.tags)) {
initState.tags.forEach((t) => {
if (t && t.tag_name) tags.push(t.tag_name);
});
}
document.querySelectorAll('.tag-link, .tag-txt, a[href*="video_tag"]').forEach((el) => {
const txt = el.textContent.trim();
if (txt) tags.push(txt);
});
document.querySelectorAll('script[type="application/ld+json"]').forEach((sc) => {
try {
const j = JSON.parse(sc.textContent || '{}');
if (Array.isArray(j.keywords)) tags.push(...j.keywords);
} catch (e) {}
});
const animeTagRegex = /(?:新番|番剧|漫改|动漫|动画|二次元|国创)/i;
if (tags.some((t) => animeTagRegex.test(t))) {
return true;
}
// 4. UGC 合集 / 系列标题 (ugc_season / video-pod):合集标题含新番/番剧/动漫/动画/追番
const seasonTitle =
initState?.videoData?.ugc_season?.title ||
document.querySelector('.video-pod__header a.title.jumpable, .video-pod__header')?.textContent ||
'';
if (/(?:新番|番剧|动漫|动画|追番)/i.test(seasonTitle)) {
return true;
}
// 5. 若已被明确归类为游戏、数码、科技、生活等纯非动漫分区,且无上述强动漫标签/合集,直接排除!
if (channel && NON_ANIME_CHANNELS_REGEX.test(channel)) {
return false;
}
// 6. 针对影视区 (含海外剧/正片搬运) 或未获取到分区的页面:必须具备强动漫特征
const titleText = rawTitle || initState?.videoData?.title || document.title;
const hasBracketCandidate = Boolean(extractCleanAnimeTitle(titleText));
const hasEpOrSeason =
/(?:第\s*(?:\d+|[一二三四五六七八九十]+)\s*[集话回期季]|全\s*(?:\d+|[一二三四五六七八九十]+)\s*[集话回]|\b(?:ep|e)\s*\d+)/i.test(
titleText
);
const hasAnimeReleaseWord =
/(?:新番|番剧|漫改|未删减|周更|日更|超清中字|中文字幕|双语字幕|无修|熟肉|生肉|简日|繁日|先行版|先行上映|剧场版|OVA|OAD)/i.test(
titleText
);
// 影视区/无分区:包含有效括号番名,且同时具备动漫发布修饰词 或 明确的动漫话数/季数标记
if (
hasBracketCandidate &&
(hasAnimeReleaseWord ||
/(?:第\s*(?:\d+|[一二三四五六七八九十]+)\s*[话回期季]|全\s*(?:\d+|[一二三四五六七八九十]+)\s*[集话回])/i.test(
titleText
))
) {
return true;
}
// 同时具备集数/季数与动漫发布修饰词 (如 "杀手旅店 第二季 全12话 超清中字")
if (hasEpOrSeason && hasAnimeReleaseWord) {
return true;
}
return false;
}
// A. 哔哩哔哩 (Bilibili - 兼容官方番剧播放页与UP主搬运/合集投稿视频)
function parseBilibili() {
if (!currentHost.includes('bilibili.com')) return null;
const isBangumi = location.pathname.includes('/bangumi/play/');
const isVideo = location.pathname.includes('/video/');
if (!isBangumi && !isVideo) return null;
let title = '';
let ep = 1;
if (isBangumi) {
// 1. 尝试从 og:title 获取纯净番剧名
const ogTitle = document.querySelector('meta[property="og:title"]')?.getAttribute('content');
if (ogTitle) {
title = ogTitle.split('/')[0].trim();
}
// 2. 尝试从页面元素获取
if (!title) {
const titleEl =
document.querySelector('.media-info-title-t') ||
document.querySelector('.media-title') ||
document.querySelector('a.mediainfo_media_title__4_y_k');
if (titleEl) title = titleEl.textContent.trim().split('/')[0].trim();
}
// 3. 尝试从全局数据获取
const initState = getBilibiliInitialState();
if (!title && initState?.mediaInfo?.title) {
title = initState.mediaInfo.title.split('/')[0].trim();
}
// 4. 从 document.title 提取
if (!title) {
title = document.title.split('第')[0].split('_')[0].split('-')[0].split('/')[0].trim();
}
// 提取当前集数
const activeEp =
document.querySelector('.ep-item.cursor') ||
document.querySelector('.ep-list-wrapper .badge.active') ||
document.querySelector('.ep-section-module .active') ||
document.querySelector('.ep-item.active');
if (activeEp) {
const m = activeEp.textContent.match(/\d+/);
if (m) ep = parseInt(m[0], 10);
} else {
const m = document.title.match(/第\s*(\d+)\s*[集话回]/);
if (m) ep = parseInt(m[1], 10);
}
} else if (isVideo) {
const h1 = document.querySelector('h1.video-title') || document.querySelector('h1');
const initState = getBilibiliInitialState();
const rawTitle = h1 ? h1.textContent.trim() : (initState?.videoData?.title || document.title);
// 0. B站视频动漫打卡白名单与智能特征检测
const channel = getBilibiliChannel();
if (!isAnimeBilibiliVideo(channel, rawTitle)) {
return null;
}
// 1. 优先从当前视频标题提取(多番剧大合集如"2026十月新番",当前视频标题【番名】才是真正作品名)
title = extractCleanAnimeTitle(rawTitle);
// 2. 若视频标题未提取出括号番名(如视频标题仅为 "第01话"),尝试从 B站合集/UGC系列标题提取
if (!title) {
const podLinkEl =
document.querySelector('.video-pod__header a.title.jumpable') ||
document.querySelector('.video-pod__header a[href*="collectiondetail"]') ||
document.querySelector('a.collection-title');
const podCand = (podLinkEl ? podLinkEl.textContent.trim() : '') || (initState?.videoData?.ugc_season?.title || '');
if (podCand && !NOISE_WORDS_REGEX.test(podCand) && podCand.length >= 2) {
title = podCand;
}
}
// 3. 兜底:从 document.title 提取
if (!title) {
title = extractCleanAnimeTitle(document.title);
}
// 4. 提取当前分P或集数 (严格区分 B站分P 与 UGC合集)
// 优先级 1: URL 中的 ?p= 参数是 B站普通视频分P最权威、最准的指标
const pMatch = location.search.match(/[?&]p=(\d+)/);
if (pMatch && parseInt(pMatch[1], 10) > 0) {
ep = parseInt(pMatch[1], 10);
} else {
// 优先级 2: 查找真实的分P列表选中项 (.multi-page-v1, .cur-list, .list-box, .page-list-box)
const activeP =
document.querySelector('.multi-page-v1 .cur-list li.on') ||
document.querySelector('.cur-list .on') ||
document.querySelector('.list-box li.on') ||
document.querySelector('.page-list-box li.on') ||
document.querySelector('.multi-page-v1 li.on');
if (activeP) {
const m =
activeP.textContent.match(/第\s*(\d+|[一二三四五六七八九十]+)\s*[集话回]/i) ||
activeP.textContent.match(/\d+/);
if (m) ep = parseChineseOrArabicNumber(m[1] || m[0]);
} else {
// 优先级 3: 仅当合集项文本明确包含 "第X话/第X集/EP.X" 时才提取
const activePod =
document.querySelector('.video-pod__item.active') ||
document.querySelector('.simple-video-pod__item.active');
if (activePod) {
const m =
activePod.textContent.match(/第\s*(\d+|[一二三四五六七八九十]+)\s*[集话回]/i) ||
activePod.textContent.match(/\b(?:ep|e)\s*(\d+)/i);
if (m) ep = parseChineseOrArabicNumber(m[1]);
}
if (ep === 1) {
// 优先级 4: 从单视频标题中解析集数
const m =
rawTitle.match(/第\s*(\d+|[一二三四五六七八九十]+)\s*[集话回]/i) ||
rawTitle.match(/\b(?:ep|e)\s*(\d+)/i) ||
rawTitle.match(/[\[【]\s*(\d+)\s*[】\]]/);
if (m) ep = parseChineseOrArabicNumber(m[1]);
}
}
}
}
return { title, episode: ep, platform: 'bilibili', url: location.href };
}
// B. 巴哈姆特动画疯 (Bahamut)
function parseBahamut() {
if (!currentHost.includes('gamer.com.tw')) return null;
let title = '';
const titleEl = document.querySelector('.anime_name h1');
if (titleEl) title = titleEl.textContent.trim();
let ep = 1;
const playingEl =
document.querySelector('.season ul li.playing') ||
document.querySelector('.season ul li.active');
if (playingEl) {
const m = playingEl.textContent.match(/\d+/);
if (m) ep = parseInt(m[0], 10);
} else {
const m = document.title.match(/\[(\d+)\]/);
if (m) ep = parseInt(m[1], 10);
}
return { title, episode: ep, platform: 'bahamut', url: location.href };
}
// C. AGE动漫家族 (agemys, agedm, agefans, agedm.io 等)
function parseAge() {
if (
!currentHost.includes('agemys') &&
!currentHost.includes('agedm') &&
!currentHost.includes('agefans') &&
!currentHost.includes('age.tv')
) {
return null;
}
let title = '';
// 排除 h1.modal-title (登录/注册弹窗) 等误导性元素
const titleEl =
document.querySelector('.card-title') ||
document.querySelector('.video_detail_box h5') ||
document.querySelector('.detail_imform_name') ||
document.querySelector('h1:not(.modal-title)');
if (titleEl && !titleEl.textContent.includes('登录') && !titleEl.textContent.includes('注册')) {
title = titleEl.textContent.trim();
}
// 从 document.title 提取兜底 (如 "骸骨骑士大人异世界冒险中 第二季 第03集 - 在线播放 - AGE动漫")
const docTitle = document.title || '';
if (!title && docTitle) {
title = docTitle.split('第')[0].split('-')[0].split('_')[0].trim();
}
let ep = 1;
// 1. 优先从 URL /play/20260208/1/3 匹配集数 3
const urlEpMatch = location.pathname.match(/\/play\/\d+\/\d+\/(\d+)/);
if (urlEpMatch) {
ep = parseInt(urlEpMatch[1], 10);
} else {
const activeEp =
document.querySelector('.play_num .active') ||
document.querySelector('.video_detail_series .active') ||
document.querySelector('.anthology-list-play .active') ||
document.querySelector('a.active[href*="/play/"]');
if (activeEp) {
const m = activeEp.textContent.match(/\d+/);
if (m) ep = parseInt(m[0], 10);
} else {
const m = docTitle.match(/(?:第\s*(\d+)\s*[集话回]|EP\s*(\d+))/i);
if (m) ep = parseInt(m[1] || m[2], 10);
}
}
return { title, episode: ep, platform: 'agefans', url: location.href };
}
// D. 樱花动漫家族 (yhdmp, yhdm, iyinghua 等)
function parseYhdm() {
if (
!currentHost.includes('yhdmp') &&
!currentHost.includes('yhdm') &&
!currentHost.includes('iyinghua') &&
!currentHost.includes('dm530')
) {
return null;
}
let title = '';
const titleEl =
document.querySelector('.card-title') ||
document.querySelector('.g-title') ||
document.querySelector('h1:not(.modal-title)');
if (titleEl && !titleEl.textContent.includes('登录') && !titleEl.textContent.includes('注册')) {
title = titleEl.textContent.trim();
}
const docTitle = document.title || '';
if (!title && docTitle) {
title = docTitle.split('第')[0].split('-')[0].split('_')[0].trim();
}
let ep = 1;
const urlEpMatch = location.pathname.match(/\/v\/\d+-(\d+)\.html/);
if (urlEpMatch) {
ep = parseInt(urlEpMatch[1], 10);
} else {
const activeEp =
document.querySelector('.movurl .playon') ||
document.querySelector('.tabs .active') ||
document.querySelector('.ul-play li a.on') ||
document.querySelector('a.active[href*="/v/"]');
if (activeEp) {
const m = activeEp.textContent.match(/\d+/);
if (m) ep = parseInt(m[0], 10);
} else {
const m = docTitle.match(/(?:第\s*(\d+)\s*[集话回]|EP\s*(\d+))/i);
if (m) ep = parseInt(m[1] || m[2], 10);
}
}
return { title, episode: ep, platform: 'yhdm', url: location.href };
}
// E. 稀饭动漫 (xifanacg, xifan.tv, next.xifanacg.com)
function parseXifan() {
if (!currentHost.includes('xifan')) return null;
let title = '';
const h1 = document.querySelector('h1');
if (h1) title = h1.textContent.trim();
const ogTitle = document.querySelector('meta[property="og:title"]')?.getAttribute('content') || '';
const docTitle = document.title || '';
let ep = 1;
// 1. 优先从当前选中的集数播放按钮提取 (适配 next.xifanacg.com 的 a[aria-current="true"] 及各版本)
const activeEp =
document.querySelector('a[aria-current="true"]') ||
document.querySelector('.anthology-list-play .active') ||
document.querySelector('.ep-list .active') ||
document.querySelector('a.active[href*="/play/"]') ||
document.querySelector('.anthology-list a.active');
if (activeEp) {
const m = activeEp.textContent.match(/\d+/);
if (m) ep = parseInt(m[0], 10);
} else {
// 2. 兜底从 og:title 或 document.title 提取 "第 4 集" / "EP04"
const m = (ogTitle || docTitle).match(/(?:第\s*(\d+)\s*[集话回]|EP\s*(\d+))/i);
if (m) ep = parseInt(m[1] || m[2], 10);
}
if (!title && ogTitle) {
title = ogTitle.split('第')[0].split('-')[0].split('·')[0].trim();
}
if (!title && docTitle) {
title = docTitle.split('第')[0].split('-')[0].split('·')[0].trim();
}
return { title, episode: ep, platform: 'xifan', url: location.href };
}
// F. Anime1 (anime1.me)
function parseAnime1() {
if (!currentHost.includes('anime1.me')) return null;
let raw = '';
const titleEl = document.querySelector('h1.page-title, h2.entry-title');
if (titleEl) raw = titleEl.textContent.trim();
if (!raw) raw = document.title || '';
let ep = 1;
const m = raw.match(/\[(\d+)\]/);
if (m) ep = parseInt(m[1], 10);
// 清洗掉 [02] 及后续部分
let title = raw.replace(/\[\d+\].*/, '').trim();
return { title, episode: ep, platform: 'anime1', url: location.href };
}
// G. 爱奇艺 (iqiyi.com)
function parseIqiyi() {
if (!currentHost.includes('iqiyi.com')) return null;
let title = '';
const albumMeta = document.querySelector('meta[name="irAlbumName"]');
if (albumMeta && albumMeta.content) {
title = albumMeta.content.trim();
}
if (!title) {
const albumLink = document.querySelector('.album-title a') || document.querySelector('.qy-player-title a');
if (albumLink) title = albumLink.textContent.trim();
}
if (!title) {
title = (document.title || '').split('-')[0].replace(/第\s*\d+\s*[集话回].*/, '').trim();
}
let ep = 1;
const activeEp = document.querySelector('.qy-episode-num.selected, .qy-episode-num.active, .episode-item.selected');
if (activeEp) {
const m = activeEp.textContent.match(/\d+/);
if (m) ep = parseInt(m[0], 10);
} else {
const m = (document.title || '').match(/第\s*(\d+)\s*[集话回]/);
if (m) ep = parseInt(m[1], 10);
}
return { title, episode: ep, platform: 'iqiyi', url: location.href };
}
// H. 腾讯视频 (v.qq.com)
function parseTencent() {
if (!currentHost.includes('v.qq.com')) return null;
let title = '';
const metaTitle = document.querySelector('meta[name="title"]');
if (metaTitle && metaTitle.content) {
title = metaTitle.content.split('_')[0].trim();
}
if (!title) {
const playerTitle = document.querySelector('.player__title') || document.querySelector('.video_title');
if (playerTitle) title = playerTitle.textContent.trim();
}
if (!title) {
title = (document.title || '').split('_')[0].replace(/第\s*\d+\s*[集话回].*/, '').trim();
}
let ep = 1;
const activeEp = document.querySelector('.episode-item.current, .episode-item.is-active, .mod_episode_list .current');
if (activeEp) {
const m = activeEp.textContent.match(/\d+/);
if (m) ep = parseInt(m[0], 10);
} else {
const m = (document.title || '').match(/(?:第\s*(\d+)\s*[集话回]|_(\d{1,3})_)/);
if (m) ep = parseInt(m[1] || m[2], 10);
}
return { title, episode: ep, platform: 'tencent', url: location.href };
}
// I. 优酷 (youku.com)
function parseYouku() {
if (!currentHost.includes('youku.com')) return null;
let title = '';
const titleEl = document.querySelector('.title-link') || document.querySelector('.anthology-title');
if (titleEl) title = titleEl.textContent.trim();
if (!title) {
title = (document.title || '').split('-')[0].replace(/第\s*\d+\s*[集话回].*/, '').replace(/\b\d{1,4}\b/, '').trim();
}
let ep = 1;
const activeEp = document.querySelector('.anthology-item.current, .item.current');
if (activeEp) {
const m = activeEp.textContent.match(/\d+/);
if (m) ep = parseInt(m[0], 10);
} else {
const m = (document.title || '').match(/(?:第\s*(\d+)\s*[集话回]|\b(\d{1,4})\b)/);
if (m) ep = parseInt(m[1] || m[2], 10);
}
return { title, episode: ep, platform: 'youku', url: location.href };
}
// J. AcFun (acfun.cn)
function parseAcfun() {
if (!currentHost.includes('acfun.cn')) return null;
let title = '';
const dramaEl = document.querySelector('.drama-title') || document.querySelector('.title-box .title');
if (dramaEl) title = dramaEl.textContent.trim();
if (!title) {
title = (document.title || '').split('-')[0].replace(/第\s*\d+\s*[集话回].*/, '').trim();
}
let ep = 1;
const activeEp = document.querySelector('.episode-item.active, .drama-part-item.active');
if (activeEp) {
const m = activeEp.textContent.match(/\d+/);
if (m) ep = parseInt(m[0], 10);
} else {
const m = (document.title || '').match(/第\s*(\d+)\s*[集话回]/);
if (m) ep = parseInt(m[1], 10);
}
return { title, episode: ep, platform: 'acfun', url: location.href };
}
// K. 通用智能嗅探引擎 (Generic Video Sniffer - 兼容全网所有动漫小站)
function parseGeneric() {
// 1. 已知专有平台必须由专属解析器裁定,绝不走泛用兜底误报
if (isKnownPlatform()) {
return null;
}
// 2. 强物理门槛:页面必须存在真实的播放器元素或已激活的外链播放器
const v = findVideoElement();
if (!v && !iframeVideoActive) {
return null;
}
// 3. 播放时长门槛:若视频时长已载入,必须 >= 300 秒 (5分钟),排除短视频、广告片、动图和背景循环视频
if (v && v.duration && !isNaN(v.duration) && v.duration < 300) {
return null;
}
// 4. 集数提取:优先提取显式集数标记 (第X集 / EPxx / [01] / 【01】)
// 若无明确集数标识(如动画电影、剧场版、单集 OVA、SP等),默认按第 1 话/全篇处理
const rawTitle = document.title || '';
if (!rawTitle) return null;
const epMatch =
rawTitle.match(/第\s*(\d+)\s*[集话回]/i) ||
rawTitle.match(/\b(?:ep|e)\s*(\d{1,4})\b/i) ||
rawTitle.match(/[\[【]\s*(\d{1,4})\s*[\]】]/) ||
rawTitle.match(/(?:^|\s)-?\s*#?(\d{1,3})\s*(?:话|集|[-_·|]|$)/);
let ep = 1;
if (epMatch) {
const parsedEp = parseInt(epMatch[1] || epMatch[2] || epMatch[3] || epMatch[4], 10);
if (parsedEp > 0 && parsedEp <= 2000) {
ep = parsedEp;
}
}
let title = extractCleanAnimeTitle(rawTitle);
// 2. 尝试从 meta[property="og:title"]
if (!title) {
const ogTitle = document.querySelector('meta[property="og:title"]')?.getAttribute('content');
if (ogTitle && ogTitle.length >= 2 && !/登录|注册/i.test(ogTitle)) {
title = extractCleanAnimeTitle(ogTitle) || ogTitle.split('第')[0].split('-')[0].split('_')[0].split('·')[0].trim();
}
}
// 3. 尝试从页面干净的 h1 提取 (排除 modal, logo, login 等误导项)
if (!title) {
const h1 = document.querySelector('h1:not(.modal-title):not(.logo)');
if (h1 && !/登录|注册|搜索|导航|首页/i.test(h1.textContent)) {
const text = h1.textContent.trim();
if (text.length >= 2 && text.length < 50) {
title = text;
}
}
}
// 4. 兜底清洗 document.title
if (!title) {
let s = rawTitle.split(/[-_·|]/)[0].trim();
s = s.replace(/第\s*\d+\s*[集话回].*/, '');
s = s.replace(/[\[【]\d+[\]】].*/, '');
s = s.replace(/\bEP\s*\d+.*/i, '');
title = s.trim();
}
if (!title || NOISE_WORDS_REGEX.test(title)) {
return null;
}
return { title, episode: ep, platform: 'generic', url: location.href };
}
function extractCurrentMediaInfo() {
// 1. 各大官方/专门视频平台:必须由专属解析器权威裁定,严禁在专属判定为非动漫后降级回 parseGeneric() 误报
if (currentHost.includes('bilibili.com')) {
return parseBilibili();
}
if (currentHost.includes('gamer.com.tw')) {
return parseBahamut();
}
if (currentHost.includes('age')) {
return parseAge();
}
if (currentHost.includes('yhdm') || currentHost.includes('iyinghua')) {
return parseYhdm();
}
if (currentHost.includes('xifan')) {
return parseXifan();
}
if (currentHost.includes('anime1.me')) {
return parseAnime1();
}
if (currentHost.includes('iqiyi.com')) {
return parseIqiyi();
}
if (currentHost.includes('v.qq.com')) {
return parseTencent();
}
if (currentHost.includes('youku.com')) {
return parseYouku();
}
if (currentHost.includes('acfun.cn')) {
return parseAcfun();
}
// 2. 仅在未知的第三方泛用播放站,才尝试兜底嗅探
return parseGeneric();
}
// 深度查找页面中的 video 元素 (支持普通 video, bwp-video, Shadow DOM 穿透以及同源 iframe)
function findVideoElement() {
let v = document.querySelector('video');
if (v) return v;
v = document.querySelector('bwp-video');
if (v) return v;
// 检查 shadowRoot 穿透
const all = document.querySelectorAll('*');
for (let i = 0; i < all.length; i++) {
const el = all[i];
if (el.shadowRoot) {
const sv = el.shadowRoot.querySelector('video, bwp-video');
if (sv) return sv;
}
}
// 尝试穿透同源可访问 iframe
const iframes = document.querySelectorAll('iframe');
for (let i = 0; i < iframes.length; i++) {
try {
const doc = iframes[i].contentDocument || iframes[i].contentWindow?.document;
if (doc) {
const iv = doc.querySelector('video, bwp-video');
if (iv) return iv;
}
} catch (e) {}
}
return null;
}
// ==========================================
// 3. 视频播放器监听与实时开发调试浮窗 (Debug HUD)
// ==========================================
let activeVideoElement = null;
let iframeVideoActive = false;
let reportStatus = 'idle'; // 'idle' | 'reporting' | 'success' | 'ask_add' | 'failed'
let reportDetailMsg = '';
let lastProgressDisplay = '00:00 / 00:00 (0%)';
let hudCurrentStatusTip = '';
function escapeHtml(str) {
if (str === null || str === undefined) return '';
return String(str)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// 调试浮窗:在播放页左下角展示实时状态
let hudElement = null;
function updateDebugHUD(progressText, statusTip) {
if (!isShowHud()) {
if (hudElement) hudElement.style.display = 'none';
const existingEl = document.getElementById('dudulu-scrobbler-debug-hud');
if (existingEl) existingEl.style.display = 'none';
return;
}
const media = extractCurrentMediaInfo();
// 关键:若当前页面未识别为动漫番剧(如在 B站看普通生活/数码/游戏/户外视频),必须彻底隐藏 HUD,绝不在非动漫视频上抢占用户视野
if (!media || !media.title) {
if (hudElement) hudElement.style.display = 'none';
const existingEl = document.getElementById('dudulu-scrobbler-debug-hud');
if (existingEl) existingEl.style.display = 'none';
return;
}
// 通用第三方站点强物理门槛:页面必须存在真实的播放器元素或已激活的外链播放器,且时长 >= 300 秒
if (!isKnownPlatform()) {
const v = findVideoElement();
if (!v && !iframeVideoActive) {
if (hudElement) hudElement.style.display = 'none';
const existingEl = document.getElementById('dudulu-scrobbler-debug-hud');
if (existingEl) existingEl.style.display = 'none';
return;
}
if (v && v.duration && !isNaN(v.duration) && v.duration < 300) {
if (hudElement) hudElement.style.display = 'none';
const existingEl = document.getElementById('dudulu-scrobbler-debug-hud');
if (existingEl) existingEl.style.display = 'none';
return;
}
}
if (progressText && (progressText.includes('/') || progressText.includes('%'))) {
lastProgressDisplay = progressText;
hudCurrentStatusTip = ''; // 真实时间进度到达时,自动清除"正在寻找"等等待提示
} else if (progressText && typeof progressText === 'string') {
hudCurrentStatusTip = progressText;
}
if (statusTip) {
hudCurrentStatusTip = statusTip;
}
if (!hudElement) {
hudElement = document.createElement('div');
hudElement.id = 'dudulu-scrobbler-debug-hud';
hudElement.style.cssText = `
position: fixed;
bottom: 24px;
left: 24px;
z-index: 9999999;
background: rgba(15, 23, 42, 0.92);
color: #e2e8f0;
border: 1px solid rgba(88, 178, 220, 0.4);
border-radius: 12px;
padding: 10px 14px;
font-size: 12px;
line-height: 1.6;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, monospace;
backdrop-filter: blur(10px);
box-shadow: 0 10px 25px rgba(0,0,0,0.4);
max-width: 380px;
pointer-events: auto;
`;
document.body.appendChild(hudElement);
}
hudElement.style.display = 'block';
const token = getToken();
let statusDisplay = '';
if (reportStatus === 'reporting') {
statusDisplay = '🚀 正在上报至嘟嘟噜...';
} else if (reportStatus === 'success') {
statusDisplay = `${escapeHtml(reportDetailMsg) || '✅ 已成功记录进度 ✓'}`;
} else if (reportStatus === 'ask_add') {
statusDisplay = '🐾 发现新番 (请在右上角确认是否加入追番)';
} else if (reportStatus === 'failed') {
const isNotMatched =
reportDetailMsg.includes('未能匹配') ||
reportDetailMsg.includes('未找到') ||
reportDetailMsg.includes('未能提取');
const actionLabel = isNotMatched ? '[反馈未录入 ↗]' : '[反馈问题 ↗]';
statusDisplay = `❌ 未能打卡: ${escapeHtml(reportDetailMsg)} ${actionLabel}`;
} else if (!isAutoScrobble()) {
statusDisplay = '⏸️ 自动记录已关闭 (可点击上方按钮手动记录)';
} else if (hudCurrentStatusTip) {
statusDisplay = `⏳ ${escapeHtml(hudCurrentStatusTip)}`;
} else {
let targetTip = '需看完85%';
const dur = activeVideoElement?.duration || lastProgressInfo?.duration;
if (dur && dur <= 45 * 60 && dur >= 20 * 60) {
targetTip = '满20分钟或85%';
}
statusDisplay = `⏳ 监听中 (${targetTip}自动打卡)`;
}
hudElement.innerHTML = `
🐾 嘟嘟噜播放监听 HUD
识别番剧: ${media ? `${escapeHtml(media.title)} (第 ${escapeHtml(media.episode)} 话)` : '未识别'}
播放进度: ${escapeHtml(lastProgressDisplay)}
打卡状态: ${statusDisplay}
账号连接: ${token ? '已连接 ✓' : '未连接 (请先打开嘟嘟噜网页登录)'}
`;
const triggerBtn = document.getElementById('dudulu-hud-trigger-btn');
if (triggerBtn) {
triggerBtn.onclick = () => {
manualTriggerScrobble();
};
}
const fbBtn = document.getElementById('dudulu-hud-feedback-btn');
if (fbBtn) {
fbBtn.onclick = () => {
const curMedia = extractCurrentMediaInfo();
showFeedbackModal({
title: curMedia?.title,
episode: curMedia?.episode,
platform: curMedia?.platform,
});
};
}
const reportLink = document.getElementById('dudulu-hud-report-link');
if (reportLink) {
reportLink.onclick = () => {
const curMedia = extractCurrentMediaInfo();
showFeedbackModal({
type: reportDetailMsg.includes('未能匹配') ? 'not_indexed' : 'error',
title: curMedia?.title,
episode: curMedia?.episode,
platform: curMedia?.platform,
detailMsg: reportDetailMsg,
});
};
}
const closeBtn = document.getElementById('dudulu-hud-close-btn');
if (closeBtn) {
closeBtn.onclick = () => {
setShowHud(false);
showToast('HUD 浮窗已隐藏,后台仍会正常自动打卡。可在油猴扩展菜单随时重新开启', 'info', 4000);
};
}
}
function initPlayerListener() {
const video = findVideoElement();
const media = extractCurrentMediaInfo();
if (!video) {
if (iframeVideoActive) {
return;
}
// 只有在已确认为专门动漫网站(如 Age/樱花 等外链解析站)且识别出媒体信息时,才重试等待 iframe
// 通用未知站点绝不盲目轮询 iframe,避免在带广告 iframes 的普通网页上不断循环
const hasIframe = !!document.querySelector('iframe');
if (isKnownPlatform() && media && media.title && hasIframe) {
updateDebugHUD(null, '检测到外链播放器,等待加载...');
setTimeout(initPlayerListener, 2000);
}
return;
}
if (activeVideoElement === video) return;
activeVideoElement = video;
console.log('[嘟嘟噜助手] 成功绑定播放器元素:', video);
const onProgress = () => {
if (!video.duration || isNaN(video.duration)) {
updateDebugHUD(null, '播放器已就绪,等待时长加载...');
return;
}
handleVideoProgress(video.currentTime, video.duration, video.ended);
};
// 监听播放、进度更新、拖拽跳转与结束
video.addEventListener('timeupdate', onProgress);
video.addEventListener('seeked', onProgress);
video.addEventListener('pause', onProgress);
video.addEventListener('ended', onProgress);
// 初始触发一次刷新 HUD
onProgress();
}
// 统一进度处理函数 (同时支持本页原生 Video 与来自 Iframe 的跨域中继)
function handleVideoProgress(currentTime, duration, ended) {
if (!duration || isNaN(duration)) return;
const ratio = currentTime / duration;
const percent = (ratio * 100).toFixed(1) + '%';
// 时间格式化 mm:ss 或 hh:mm:ss
const formatTime = (sec) => {
const s = Math.floor(sec || 0);
const m = Math.floor(s / 60);
const remainS = (s % 60).toString().padStart(2, '0');
if (m >= 60) {
const h = Math.floor(m / 60);
const remainM = (m % 60).toString().padStart(2, '0');
return `${h}:${remainM}:${remainS}`;
}
return `${m}:${remainS}`;
};
const timeStr = `${formatTime(currentTime)} / ${formatTime(duration)}`;
const progressText = `${timeStr} (${percent})`;
lastProgressInfo = { currentTime, duration, ratio, ended };
// 智能打卡阈值判定:
// 1. 常规单集动漫(<=45分钟):看到 20 分钟(1200秒)自动打卡,贴合跳过片尾曲/下集预告的观看习惯;
// 2. 短番/泡面番(总长不足20分钟):达到 85% 自动打卡;
// 3. 剧场版/长视频(>45分钟):达到 85% 自动打卡;
// 4. 视频播放至结尾 (ended):直接触发。
const isLongVideo = duration > 45 * 60;
const reach20Min = !isLongVideo && currentTime >= 20 * 60;
const reachRatio = ratio >= 0.85;
const isEligible = reach20Min || reachRatio || ended;
updateDebugHUD(progressText);
// 实时断点记录 (未完播时持续更新本地缓存并防抖同步云端)
if (!ended && currentTime > 10 && currentMatchedAnime && currentMatchedAnime.id > 0) {
const media = extractCurrentMediaInfo();
const ep = media ? media.episode || 1 : 1;
saveLocalPlaybackTime(currentMatchedAnime.id, ep, currentTime, duration);
syncPlaybackTimeToCloud(currentMatchedAnime.id, currentMatchedAnime.title, ep, currentTime, duration);
}
if (isEligible) {
const media = extractCurrentMediaInfo();
if (!media || !media.title) {
// 当前视频并非动漫番剧,静默跳过,绝不打卡也不弹报错
return;
}
if (!isAutoScrobble()) {
// 用户已关闭自动记录进度,跳过自动打卡
return;
}
if (reportStatus === 'idle') {
reportStatus = 'reporting';
reportDetailMsg = '';
triggerScrobble(ratio);
}
}
}
// 监听来自外部/子 Iframe 播放器的跨域进度广播
window.addEventListener('message', (e) => {
if (e.data && e.data.type === 'DUDULU_IFRAME_PROGRESS') {
const wasIframeActive = iframeVideoActive;
iframeVideoActive = true;
const { currentTime, duration, ended } = e.data;
handleVideoProgress(currentTime, duration, ended);
// 若此前因 iframe 尚未就绪而未执行过续播与选集检查,在收到首帧有效广播时立即执行
if (!wasIframeActive && !checkedExternalResume) {
checkAutoJumpOrResumePrompt();
}
}
});
// ==========================================
// 3.5 智能选集定位与秒级断点续播 (基于番剧ID+集数多端无缝协同)
// ==========================================
function getLocalPlaybackTimes() {
const key = getPlaybackStorageKey();
if (!key) return {};
try {
return JSON.parse(GM_getValue(key, '{}'));
} catch (e) {
return {};
}
}
function saveLocalPlaybackTime(animeId, episode, timeSec, durationSec) {
if (!animeId || !episode || timeSec <= 10) return;
const key = getPlaybackStorageKey();
if (!key) return;
const store = getLocalPlaybackTimes();
store[String(animeId)] = {
episode,
time: Math.floor(timeSec),
duration: Math.floor(durationSec || 0),
updatedAt: Date.now(),
};
GM_setValue(key, JSON.stringify(store));
}
function clearLocalPlaybackTime(animeId) {
if (!animeId) return;
const key = getPlaybackStorageKey();
if (!key) return;
const store = getLocalPlaybackTimes();
if (store[String(animeId)]) {
delete store[String(animeId)];
GM_setValue(key, JSON.stringify(store));
}
}
let lastCloudSyncTime = 0;
let lastCloudSyncSeconds = 0;
function syncPlaybackTimeToCloud(animeId, title, episode, timeSec, durationSec, force = false) {
const token = getToken();
if (!token || !animeId || !episode || timeSec <= 15) return;
if (currentMatchedAnime && currentMatchedAnime.status !== 'watching') return;
const now = Date.now();
if (!force) {
if (now - lastCloudSyncTime < 25000 && Math.abs(timeSec - lastCloudSyncSeconds) < 20) {
return;
}
}
lastCloudSyncTime = now;
lastCloudSyncSeconds = timeSec;
const apiBase = getApiBase();
const payload = {
anime_id: animeId,
title: title || '',
episode,
time_sec: Math.floor(timeSec),
duration_sec: Math.floor(durationSec || 0),
};
GM_xmlhttpRequest({
method: 'POST',
url: apiBase + '/api/v2/watchlist/playback-time',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token,
},
data: JSON.stringify(payload),
});
}
function updateAnimeWatchStatus(animeId, status, watchedEp, callback) {
const token = getToken();
if (!token || !animeId) {
if (callback) callback({ code: 401, message: '尚未连接嘟嘟噜账号' });
return;
}
const apiBase = getApiBase();
const body = { status: status || 'watching' };
if (typeof watchedEp === 'number') {
body.watchedEp = watchedEp;
}
GM_xmlhttpRequest({
method: 'PUT',
url: apiBase + '/api/v2/user/watchlist/' + animeId,
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token,
},
data: JSON.stringify(body),
onload: function (res) {
try {
const resp = JSON.parse(res.responseText);
if (callback) callback(resp);
} catch (e) {
if (callback) callback({ code: 500, message: e.message });
}
},
onerror: function (err) {
if (callback) callback({ code: 500, message: '网络请求失败' });
},
});
}
function formatTimeLabel(seconds) {
if (!seconds || seconds <= 0) return '00:00';
const total = Math.floor(seconds);
const m = Math.floor(total / 60);
const s = (total % 60).toString().padStart(2, '0');
if (m >= 60) {
const h = Math.floor(m / 60);
const remainM = (m % 60).toString().padStart(2, '0');
return `${h}:${remainM}:${s}`;
}
return `${m.toString().padStart(2, '0')}:${s}`;
}
function getTargetEpisodeFromUrl() {
const hash = location.hash || '';
const mHash = hash.match(/dudulu_ep=(\d+)/);
if (mHash) return parseInt(mHash[1], 10);
const mSearch = location.search.match(/[?&]dudulu_ep=(\d+)/);
if (mSearch) return parseInt(mSearch[1], 10);
return 0;
}
function getTargetTimeFromUrl() {
const hash = location.hash || '';
const mHash = hash.match(/dudulu_time=(\d+)/);
if (mHash) return parseInt(mHash[1], 10);
const mSearch = location.search.match(/[?&]dudulu_time=(\d+)/);
if (mSearch) return parseInt(mSearch[1], 10);
return 0;
}
function cleanEpisodeHash() {
try {
if (location.hash && (location.hash.includes('dudulu_ep=') || location.hash.includes('dudulu_time='))) {
history.replaceState(null, '', location.pathname + location.search);
lastUrl = location.href;
if (typeof lastComparableUrl !== 'undefined') {
lastComparableUrl = getComparableUrl(location.href);
}
}
} catch (e) {}
}
function seekVideoToTime(targetSec) {
if (!targetSec || targetSec <= 0) return false;
let ok = false;
const v = findVideoElement();
if (v) {
try {
v.currentTime = targetSec;
ok = true;
} catch (e) {}
}
const iframes = document.querySelectorAll('iframe');
iframes.forEach((ifr) => {
try {
ifr.contentWindow.postMessage({ type: 'DUDULU_SEEK_TO', time: targetSec }, '*');
ok = true;
} catch (e) {}
});
return ok;
}
let handledResumeTime = false;
function promptResumePlayback(targetSec) {
if (handledResumeTime || !targetSec || targetSec <= 15) return;
handledResumeTime = true;
const timeLabel = formatTimeLabel(targetSec);
showToast(`🐾 嘟嘟噜:上次看到 ${timeLabel}`, 'info', 8000, {
text: `▶ 点击续播至 ${timeLabel} ↗`,
onClick: () => {
seekVideoToTime(targetSec);
showToast(`已为你续播至 ${timeLabel}`, 'success', 3000);
},
});
}
function matchItemEpisode(text, targetEp) {
if (!text || !targetEp || targetEp <= 0) return false;
const str = String(text).trim();
if (!str) return false;
// 1. 显式中文格式:第X集/话/回/期
const m1 = str.match(/第\s*(\d+)\s*[集话回期]/i);
if (m1 && parseInt(m1[1], 10) === targetEp) return true;
// 2. 显式 EP / P 格式:EP03, P3, ep 3, EP.3
const m2 = str.match(/(?:ep|p)[.\s]*0*(\d+)\b/i);
if (m2 && parseInt(m2[1], 10) === targetEp) return true;
// 3. 括号包裹格式:【03】, [03], (03)
const m3 = str.match(/[【\[\((]\s*0*(\d+)\s*[】\]\))]/);
if (m3 && parseInt(m3[1], 10) === targetEp) return true;
// 4. 开头纯数字:03 标题, 3 - 标题, 03.标题
const m4 = str.match(/^\s*0*(\d+)(?:[\s._\-::、]|$)/);
if (m4 && parseInt(m4[1], 10) === targetEp) return true;
// 5. 纯文本对齐
if (str === String(targetEp) || str === String(targetEp).padStart(2, '0')) return true;
return false;
}
function hasEpisodeOnPage(targetEp) {
if (!targetEp || targetEp <= 0) return false;
// 1. AGE 动漫
if (
currentHost.includes('agemys') ||
currentHost.includes('agedm') ||
currentHost.includes('agefans') ||
currentHost.includes('age.tv')
) {
const links = document.querySelectorAll('a[href*="/play/"]');
for (const el of links) {
const m = (el.getAttribute('href') || '').match(/\/play\/\d+\/\d+\/(\d+)/);
if (m && parseInt(m[1], 10) === targetEp) return true;
if (matchItemEpisode(el.textContent, targetEp)) return true;
}
return false;
}
// 2. B 站普通分P / 合集 / 番剧
if (currentHost.includes('bilibili.com')) {
// 场景 2.1: B站普通视频分P列表
const multiParts = document.querySelectorAll(
'.multi-page-v1 .cur-list li, .cur-list li, .list-box li, .page-list-box li, .multi-page-v1 li'
);
if (multiParts.length > 0) {
return targetEp <= multiParts.length;
}
// 场景 2.2: B站官方番剧剧集列表
const epLinks = document.querySelectorAll(
'.ep-list-wrapper .ep-item, .ep-section .ep-item, .slider-list .ep-item'
);
if (epLinks.length > 0) {
for (let idx = 0; idx < epLinks.length; idx++) {
if (matchItemEpisode(epLinks[idx].textContent, targetEp)) return true;
}
if (epLinks.length >= targetEp) return true;
return false;
}
// 场景 2.3: UGC 合集列表 (仅当文本明确包含集数特征时才判定存在)
const podItems = document.querySelectorAll('.video-pod__list .video-pod__item, .simple-video-pod__item');
if (podItems.length > 0) {
for (let idx = 0; idx < podItems.length; idx++) {
if (matchItemEpisode(podItems[idx].textContent, targetEp)) return true;
}
}
// 场景 2.4: 视频播放页 URL 参数兜底 (如果当前位于 /video/ 且 targetEp > 1)
if (location.pathname.includes('/video/')) {
return true;
}
}
// 3. 通用 DOM 选集元素扫描
const candSelectors = [
'.ep-list-wrapper .ep-item',
'.ep-section .ep-item',
'.slider-list .ep-item',
'.season ul li',
'.play_num a',
'.movurl ul li a',
'.playlist ul li a',
'.anthology-list a',
'.episodes-list a',
];
for (const selector of candSelectors) {
const elements = document.querySelectorAll(selector);
if (!elements || elements.length === 0) continue;
for (let idx = 0; idx < elements.length; idx++) {
const el = elements[idx];
if (matchItemEpisode(el.textContent, targetEp)) {
return true;
}
if (idx === targetEp - 1 && elements.length >= targetEp && /\d+/.test(el.textContent || '')) {
return true;
}
}
return false;
}
return false;
}
function jumpToEpisode(targetEp) {
if (!targetEp || targetEp <= 0) return false;
// 1. AGE 动漫:支持通过改写 URL 路由跳转
if (
currentHost.includes('agemys') ||
currentHost.includes('agedm') ||
currentHost.includes('agefans') ||
currentHost.includes('age.tv')
) {
const m = location.pathname.match(/^(\/play\/\d+\/\d+\/)(\d+)/);
if (m) {
const currentEp = parseInt(m[2], 10);
if (currentEp !== targetEp) {
console.log(`[嘟嘟噜] AGE 路由跳转至第 ${targetEp} 话`);
location.pathname = m[1] + targetEp;
return true;
}
return true; // 已经是目标集数
}
}
// 2. B站普通合集 / 分P / 番剧
if (currentHost.includes('bilibili.com')) {
// 场景 2.1: B站普通投稿视频 (/video/BV...) 的分P机制
// 只要是普通视频分P页面,URL 参数 ?p=X 是 B站官方最核心、最稳固的跳集机制!
if (location.pathname.includes('/video/')) {
const multiParts = document.querySelectorAll(
'.multi-page-v1 .cur-list li, .cur-list li, .list-box li, .page-list-box li, .multi-page-v1 li'
);
if (multiParts.length > 0 && targetEp <= multiParts.length) {
const targetEl = multiParts[targetEp - 1];
if (targetEl) {
const clickTarget = targetEl.querySelector('a') || targetEl;
clickTarget.click();
}
}
// 无论 DOM 点击是否被框架拦截,强制通过 URL 参数进行可靠跳转与重定位
const curP = parseInt(new URLSearchParams(location.search).get('p') || '1', 10);
if (curP !== targetEp) {
const url = new URL(location.href);
url.searchParams.set('p', targetEp.toString());
location.href = url.toString();
return true;
}
return true;
}
// 场景 2.2: B站官方番剧 (/bangumi/play/...)
const epLinks = document.querySelectorAll(
'.ep-list-wrapper .ep-item, .ep-section .ep-item, .slider-list .ep-item, .ep-item'
);
if (epLinks.length > 0) {
for (let idx = 0; idx < epLinks.length; idx++) {
const el = epLinks[idx];
if (matchItemEpisode(el.textContent, targetEp)) {
const clickTarget = el.querySelector('a') || el;
clickTarget.click();
return true;
}
}
if (epLinks.length >= targetEp && epLinks[targetEp - 1]) {
const clickTarget = epLinks[targetEp - 1].querySelector('a') || epLinks[targetEp - 1];
clickTarget.click();
return true;
}
}
// 场景 2.3: UGC 合集列表 (.video-pod__list .video-pod__item)
// 仅当合集项文本明确包含目标集数关键词时才允许点击,绝不盲目按索引点击不同番剧!
const podItems = document.querySelectorAll('.video-pod__list .video-pod__item, .simple-video-pod__item');
if (podItems.length > 0) {
for (let idx = 0; idx < podItems.length; idx++) {
const el = podItems[idx];
if (matchItemEpisode(el.textContent, targetEp)) {
const clickTarget = el.querySelector('a') || el;
clickTarget.click();
return true;
}
}
}
}
// 3. 通用 DOM 选集点击:在页面集数列表中寻找匹配目标集数的元素
const candSelectors = [
// B站 番剧 ep 列表
'.ep-list-wrapper .ep-item',
'.ep-section .ep-item',
'.slider-list .ep-item',
// 巴哈姆特
'.season ul li',
'.season ul li a',
// AGE 动漫
'.play_num a',
'.play_num li',
'.video_detail_series a',
'.anthology-list-play a',
'a[href*="/play/"]',
// 樱花动漫 & 常见影视站
'.movurl ul li a',
'.playlist ul li a',
'.play-list a',
'.anthology-list a',
'.anthology-wrap a',
'.anthology-play a',
'.episodes-list a',
'.episode-list a',
// 通用按钮/链接
'a',
'button',
'li',
];
for (const selector of candSelectors) {
const elements = document.querySelectorAll(selector);
if (!elements || elements.length === 0) continue;
for (let idx = 0; idx < elements.length; idx++) {
const el = elements[idx];
if (matchItemEpisode(el.textContent, targetEp)) {
console.log(`[嘟嘟噜] 匹配到第 ${targetEp} 话元素:`, el);
el.click();
return true;
}
if (idx === targetEp - 1 && elements.length >= targetEp && /\d+/.test(el.textContent || '')) {
console.log(`[嘟嘟噜] 索引匹配到第 ${targetEp} 话元素:`, el);
el.click();
return true;
}
}
}
return false;
}
let handledTargetEp = false;
let checkedExternalResume = false;
function checkAutoJumpOrResumePrompt() {
// 只在顶层窗口运行,不在 iframe 中弹窗
if (window !== window.top) return;
// 严禁在无真实视频播放器的普通网页上弹窗查询或提示!
const video = findVideoElement();
if (!video && !iframeVideoActive) {
return;
}
// 通用第三方站点强物理门槛:时长必须 >= 300 秒
if (!isKnownPlatform() && video && video.duration && !isNaN(video.duration) && video.duration < 300) {
return;
}
const targetEp = getTargetEpisodeFromUrl();
const targetTime = getTargetTimeFromUrl();
// 场景 A: 从嘟嘟噜跳转而来(URL 包含目标集数定位参数与可选断点秒数)
if (targetEp > 0 && !handledTargetEp) {
handledTargetEp = true;
checkedExternalResume = true; // 锁定:既然携带了嘟嘟噜明确的目标集数,锁定外部探活,绝不允许同页面重复触发场景 B
cleanEpisodeHash();
const curMedia = extractCurrentMediaInfo();
const currentEp = curMedia ? curMedia.episode : 1;
if (currentEp === targetEp) {
showToast(`🌸 嘟嘟噜:当前为第 ${targetEp} 话 ✓`, 'info', 3500);
if (targetTime > 15) {
promptResumePlayback(targetTime);
}
return;
}
// 当前集数非目标集数:坚决不自动跳转,跟时间进度一样展示提示,用户主动点击后再跳转
const tipText = targetEp > 1
? `🐾 嘟嘟噜:你已经看完第 ${targetEp - 1} 话,推荐观看第 ${targetEp} 话`
: `🐾 嘟嘟噜:推荐观看第 ${targetEp} 话 (当前为第 ${currentEp} 话)`;
showToast(
tipText,
'info',
9000,
{
text: `👉 点击切换至第 ${targetEp} 话 ↗`,
onClick: () => {
const jumped = jumpToEpisode(targetEp);
if (jumped) {
showToast(`🌸 正在为你切换至第 ${targetEp} 话...`, 'success', 3000);
if (targetTime > 15) {
setTimeout(() => {
promptResumePlayback(targetTime);
}, 1500);
}
} else {
showToast(`未能在页面找到第 ${targetEp} 话选集按钮,请手动选集`, 'warning', 4000);
}
},
}
);
return;
}
// 场景 B: 用户直接访问播放站(无定位参数),检测嘟嘟噜已有进度与断点秒数
if (!targetEp && !checkedExternalResume) {
const token = getToken();
if (!token) return;
const curMedia = extractCurrentMediaInfo();
if (!curMedia || !curMedia.title) return;
checkedExternalResume = true;
const apiBase = getApiBase();
const queryUrl = `${apiBase}/api/v2/watchlist/scrobble?title=${encodeURIComponent(
curMedia.title
)}&url=${encodeURIComponent(location.href)}`;
GM_xmlhttpRequest({
method: 'GET',
url: queryUrl,
headers: {
Authorization: 'Bearer ' + token,
},
onload: function (res) {
try {
const resp = JSON.parse(res.responseText);
// 未收录到嘟嘟噜的番剧,按规则不启用跨站点断点与续播功能,保持轻量无侵入
if (!resp || resp.code !== 0 || !resp.data || !resp.data.anime_id) {
currentMatchedAnime = null;
return;
}
const animeId = resp.data.anime_id;
const currentEp = curMedia.episode || 1;
const watchedEp = resp.data.watched_ep || 0;
const nextEp = resp.data.next_ep || 1;
const cloudTimeSec = resp.data.last_time_sec || 0;
const watchStatus = resp.data.status || 'unfollowed';
currentMatchedAnime = {
id: animeId,
title: resp.data.title || curMedia.title,
cover: resp.data.cover || '',
totalEp: resp.data.total_ep || 0,
watchedEp,
nextEp,
lastTimeSec: cloudTimeSec,
status: watchStatus,
};
const doJumpOrResume = () => {
const curWatched = currentMatchedAnime.watchedEp;
const curNext = currentMatchedAnime.nextEp;
const curCloudTime = currentMatchedAnime.lastTimeSec;
// 分支 B1: 推荐下一话 (仅当当前集数落后于待观看的新一话且页面确实收录了该集)
if (curNext > curWatched && currentEp < curNext && hasEpisodeOnPage(curNext)) {
showToast(
`🐾 嘟嘟噜:你已经看完第 ${curWatched} 话,推荐观看第 ${curNext} 话`,
'info',
9000,
{
text: `👉 点击切换至第 ${curNext} 话 ↗`,
onClick: () => {
const jumped = jumpToEpisode(curNext);
if (jumped) {
showToast(`🌸 正在为你切换至第 ${curNext} 话...`, 'success', 3000);
} else {
showToast(`未能在页面找到第 ${curNext} 话选集按钮,请手动选集`, 'warning', 4000);
}
},
}
);
} else if (currentEp >= curNext) {
// 分支 B2: 用户正在观看当前推荐进度,若存在未完播断点,提供轻量点击续播 (绝不未经允许强制跳转)
let resumeSec = 0;
// 1. 本地精准秒级记忆 (严格按 userId + animeId 索引,杜绝跨账号串台)
const localStore = getLocalPlaybackTimes();
const record = localStore[String(animeId)];
if (record && record.episode === currentEp && record.time > 15) {
resumeSec = record.time;
}
// 2. 云端断点兜底:
// 严格防旧集污染:
// a) 若当前集数已完播 (currentEp <= curWatched),说明该集已看完,绝不提示续播;
// b) 仅当当前集数属于未完播的新一集 (currentEp > curWatched),且本地无冲突时,才采纳云端断点
if (!resumeSec && curCloudTime > 15 && currentEp > curWatched) {
if (!record || record.episode === currentEp) {
resumeSec = curCloudTime;
}
}
if (resumeSec > 15) {
promptResumePlayback(resumeSec);
}
}
};
// 核心判定: 若识别到当前的番剧不是在看状态 (status !== 'watching')
// 进站立即弹出带封面、番名与当前集数的入库追番弹窗,让用户清晰感知插件正在生效
if (watchStatus !== 'watching') {
showAddWatchlistModal({
...resp.data,
anime_id: animeId,
title: resp.data.title || curMedia.title,
cover: resp.data.cover || '',
total_ep: resp.data.total_ep || 0,
watched_ep: watchedEp,
currentEp: currentEp,
mode: 'entry',
onAdded: () => {
setTimeout(() => {
doJumpOrResume();
}, 500);
},
});
return;
}
// 当前已处于在看状态,直接进入推荐或续播逻辑
doJumpOrResume();
} catch (e) {
// 静默处理,不打扰用户
}
},
});
}
}
// 页面离开时瞬间保存最后断点
window.addEventListener('beforeunload', () => {
const v = findVideoElement();
if (currentMatchedAnime && currentMatchedAnime.id > 0 && v && v.currentTime > 15) {
const curMedia = extractCurrentMediaInfo();
const ep = curMedia ? curMedia.episode || 1 : 1;
// 关键防旧集污染:若该集已标记完播 (ep <= watchedEp) 或已成功打卡,严禁向本地与云端回写旧断点
if (ep <= currentMatchedAnime.watchedEp || reportStatus === 'success') {
return;
}
saveLocalPlaybackTime(currentMatchedAnime.id, ep, v.currentTime, v.duration);
syncPlaybackTimeToCloud(currentMatchedAnime.id, currentMatchedAnime.title, ep, v.currentTime, v.duration, true);
}
});
function getComparableUrl(url) {
try {
const u = new URL(url);
// 忽略纯 hash 或 dudulu 专用锚点参数对页面路由判定的干扰
return u.origin + u.pathname + u.search;
} catch (e) {
return (url || '').split('#')[0];
}
}
let lastUrl = location.href;
let lastComparableUrl = getComparableUrl(location.href);
let pageTransitionTimer = null;
setInterval(() => {
const curComparable = getComparableUrl(location.href);
if (curComparable !== lastComparableUrl) {
lastComparableUrl = curComparable;
lastUrl = location.href;
reportStatus = 'idle';
reportDetailMsg = '';
activeVideoElement = null;
handledTargetEp = false;
handledResumeTime = false;
checkedExternalResume = false;
currentMatchedAnime = null;
// 清除未完成的续播防抖定时器
if (pageTransitionTimer) clearTimeout(pageTransitionTimer);
// 给单页应用 (SPA 如B站) 1.2秒时间更新 DOM 与播放器实例,彻底避免读取上一部番的旧标题和旧时间
pageTransitionTimer = setTimeout(() => {
initPlayerListener();
checkAutoJumpOrResumePrompt();
}, 1200);
return;
}
// 定时动态探活与进度同步 (防止拖拽进度条或暂停时漏监听)
const curVideo = findVideoElement();
if (curVideo && curVideo !== activeVideoElement) {
initPlayerListener();
if (!checkedExternalResume) {
checkAutoJumpOrResumePrompt();
}
} else if (activeVideoElement && activeVideoElement.duration && !isNaN(activeVideoElement.duration)) {
handleVideoProgress(activeVideoElement.currentTime, activeVideoElement.duration, activeVideoElement.ended);
}
}, 1000);
// 延迟启动以等待 SPA DOM 就绪
setTimeout(() => {
initPlayerListener();
checkAutoJumpOrResumePrompt();
}, 1200);
// ==========================================
// 4. 上报后端与智能分流交互 (API & Modal)
// ==========================================
// 手动记录当前播放进度 (油猴扩展菜单 & HUD 手动记录进度按钮统一调用)
function manualTriggerScrobble() {
if (currentMatchedAnime && currentMatchedAnime.id > 0) {
clearLocalPlaybackTime(currentMatchedAnime.id);
}
const curMedia = extractCurrentMediaInfo();
if (!curMedia || !curMedia.title) {
showToast('🐾 嘟嘟噜:当前视频并非动漫番剧 (未通过主分区或番剧特征校验)', 'warning', 4000);
return;
}
if (!isKnownPlatform()) {
const v = findVideoElement();
if (!v && !iframeVideoActive) {
showToast('🐾 嘟嘟噜:当前页面未检测到正在播放的视频', 'warning', 4000);
return;
}
if (v && v.duration && !isNaN(v.duration) && v.duration < 300) {
showToast('🐾 嘟嘟噜:视频时长小于 5 分钟,非完整动漫正片', 'warning', 4000);
return;
}
}
reportStatus = 'idle'; // 重置状态允许重新上报
showToast('🚀 正在记录当前播放进度至嘟嘟噜...', 'info', 2000);
const curRatio =
activeVideoElement && activeVideoElement.duration && !isNaN(activeVideoElement.duration)
? activeVideoElement.currentTime / activeVideoElement.duration
: 1.0;
triggerScrobble(curRatio, false);
}
function triggerScrobble(ratio, forceAdd = false) {
const mediaInfo = extractCurrentMediaInfo();
if (!mediaInfo || !mediaInfo.title) {
reportStatus = 'failed';
reportDetailMsg = '当前视频并非动漫番剧';
return;
}
if (!isKnownPlatform()) {
const v = findVideoElement();
if (!v && !iframeVideoActive) {
reportStatus = 'failed';
reportDetailMsg = '页面未检测到视频播放器';
return;
}
if (v && v.duration && !isNaN(v.duration) && v.duration < 300) {
reportStatus = 'failed';
reportDetailMsg = '视频时长不足5分钟,非正片';
return;
}
}
const token = getToken();
if (!token) {
reportStatus = 'failed';
reportDetailMsg = '尚未连接账号,请先登录主站';
updateDebugHUD();
showToast('🐾 检测到你看了这集番剧,但尚未连接嘟嘟噜账号!请先打开嘟嘟噜网页登录', 'warning', 7000);
return;
}
reportStatus = 'reporting';
reportDetailMsg = '';
updateDebugHUD();
const apiBase = getApiBase();
const payload = {
title: mediaInfo.title,
episode: mediaInfo.episode,
url: mediaInfo.url,
platform: mediaInfo.platform,
progress_ratio: ratio,
force_add: forceAdd,
};
console.log('[嘟嘟噜助手] 正在上报进度:', payload);
GM_xmlhttpRequest({
method: 'POST',
url: apiBase + '/api/v2/watchlist/scrobble',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token,
},
data: JSON.stringify(payload),
onload: function (res) {
try {
const resp = JSON.parse(res.responseText);
console.log('[嘟嘟噜助手] 接口返回:', resp);
if (resp.code === 0 && resp.data) {
handleScrobbleSuccess(resp.data);
} else {
reportStatus = 'failed';
reportDetailMsg = resp.message || '未知响应';
const isNotIndexed =
res.status === 404 ||
(resp.message && (resp.message.includes('未能匹配') || resp.message.includes('未找到')));
if (isNotIndexed) {
showToast('嘟嘟噜:库内暂未录入该番剧', 'warning', 9000, {
text: '🐾 申请收录 / 反馈 ↗',
onClick: () => {
const curMedia = extractCurrentMediaInfo();
showFeedbackModal({
type: 'not_indexed',
title: curMedia?.title,
episode: curMedia?.episode,
platform: curMedia?.platform,
detailMsg: resp.message || '未能匹配到嘟嘟噜库内的对应番剧',
});
},
});
} else {
showToast('嘟嘟噜提示: ' + (resp.message || '未知响应'), 'warning', 7000, {
text: '💬 问题反馈 ↗',
onClick: () => {
const curMedia = extractCurrentMediaInfo();
showFeedbackModal({
type: 'error',
title: curMedia?.title,
episode: curMedia?.episode,
platform: curMedia?.platform,
detailMsg: resp.message,
});
},
});
}
updateDebugHUD();
}
} catch (e) {
console.error('[嘟嘟噜助手] 解析返回失败:', e, res.responseText);
reportStatus = 'failed';
reportDetailMsg = '响应解析异常';
updateDebugHUD();
}
},
onerror: function (err) {
console.error('[嘟嘟噜助手] 请求失败:', err);
reportStatus = 'failed';
reportDetailMsg = '网络连接或服务端异常';
showToast('请求嘟嘟噜接口失败,请检查网络或后端状态', 'warning', 6000, {
text: '💬 反馈 ↗',
onClick: () => {
showFeedbackModal({
type: 'error',
detailMsg: '请求嘟嘟噜接口失败: 网络连接或服务端异常',
});
},
});
updateDebugHUD();
},
});
}
function handleScrobbleSuccess(data) {
const { action, title, watched_ep, message } = data;
if (action === 'scrobbled' || action === 'added_and_scrobbled') {
reportStatus = 'success';
reportDetailMsg = `✅ 已成功记录进度至第 ${watched_ep} 话 ✓`;
if (currentMatchedAnime && currentMatchedAnime.id > 0) {
clearLocalPlaybackTime(currentMatchedAnime.id);
currentMatchedAnime.watchedEp = watched_ep;
currentMatchedAnime.lastTimeSec = 0;
}
const curMedia = extractCurrentMediaInfo();
showToast('🌸 嘟嘟噜:' + message, 'success', 6000, {
text: '番名配错?报错 ↗',
onClick: () => {
showFeedbackModal({
type: 'wrong_match',
title: curMedia?.title,
episode: curMedia?.episode,
platform: curMedia?.platform,
matchedTitle: title,
});
},
});
updateDebugHUD();
} else if (action === 'already_watched') {
const curMedia = extractCurrentMediaInfo();
const currentEp = curMedia?.episode || 1;
const isBehind = currentEp < watched_ep;
const defaultMsg = isBehind
? `当前为第 ${currentEp} 话,非最新进度,无需更新`
: `第 ${currentEp} 话进度已记录 ✓`;
reportStatus = 'success';
reportDetailMsg = message || defaultMsg;
if (currentMatchedAnime && currentMatchedAnime.id > 0) {
clearLocalPlaybackTime(currentMatchedAnime.id);
currentMatchedAnime.watchedEp = Math.max(currentMatchedAnime.watchedEp || 0, watched_ep);
currentMatchedAnime.lastTimeSec = 0;
}
showToast('🐾 嘟嘟噜:' + (message || defaultMsg), 'info', 4000, {
text: '报错 ↗',
onClick: () => {
showFeedbackModal({
type: 'wrong_match',
title: curMedia?.title,
episode: curMedia?.episode,
platform: curMedia?.platform,
matchedTitle: title,
});
},
});
updateDebugHUD();
} else if (action === 'ask_add_watchlist') {
reportStatus = 'ask_add';
reportDetailMsg = '等待右上角确认入库';
updateDebugHUD();
showAddWatchlistModal(data);
}
}
// ==========================================
// 5. 交互 UI 悬浮组件 (Toast & Modal)
// ==========================================
let activeToastTimer = null;
let lastToastKey = '';
let lastToastTime = 0;
function showToast(text, type = 'success', duration = 4000, action = null) {
if (!text) return;
// 1. 防抖与重复过滤:同一文案在 3 秒内不重复弹出
const now = Date.now();
const toastKey = `${text}_${type}`;
if (toastKey === lastToastKey && now - lastToastTime < 3000) {
return;
}
lastToastKey = toastKey;
lastToastTime = now;
let container = document.getElementById('dudulu-scrobbler-toast-box');
if (!container) {
container = document.createElement('div');
container.id = 'dudulu-scrobbler-toast-box';
container.style.cssText =
'position: fixed; top: 24px; right: 24px; z-index: 2147483647; display: flex; flex-direction: column; align-items: flex-end; gap: 8px; pointer-events: none; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;';
if (document.body) {
document.body.appendChild(container);
} else {
document.documentElement.appendChild(container);
}
}
// 2. 单例模式:清空现有 Toast,全局永远最多只显示 1 条,坚决杜绝多条垂直堆叠
if (activeToastTimer) {
clearTimeout(activeToastTimer);
activeToastTimer = null;
}
while (container.firstChild) {
container.removeChild(container.firstChild);
}
const toast = document.createElement('div');
const bgStyles = {
success: {
bg: 'linear-gradient(135deg, rgba(5, 150, 105, 0.88), rgba(16, 185, 129, 0.75))',
border: 'rgba(167, 243, 208, 0.55)',
shadow: '0 10px 25px -4px rgba(16, 185, 129, 0.35), 0 2px 8px rgba(0, 0, 0, 0.18)',
},
info: {
bg: 'linear-gradient(135deg, rgba(2, 132, 199, 0.88), rgba(14, 165, 233, 0.75))',
border: 'rgba(186, 230, 253, 0.55)',
shadow: '0 10px 25px -4px rgba(14, 165, 233, 0.35), 0 2px 8px rgba(0, 0, 0, 0.18)',
},
warning: {
bg: 'linear-gradient(135deg, rgba(217, 119, 6, 0.88), rgba(245, 158, 11, 0.75))',
border: 'rgba(254, 240, 138, 0.55)',
shadow: '0 10px 25px -4px rgba(245, 158, 11, 0.35), 0 2px 8px rgba(0, 0, 0, 0.18)',
},
error: {
bg: 'linear-gradient(135deg, rgba(220, 38, 38, 0.88), rgba(244, 63, 94, 0.75))',
border: 'rgba(254, 202, 202, 0.55)',
shadow: '0 10px 25px -4px rgba(239, 68, 68, 0.35), 0 2px 8px rgba(0, 0, 0, 0.18)',
},
};
const styleConf = bgStyles[type] || bgStyles.info;
toast.style.cssText = `
background: ${styleConf.bg};
color: #ffffff;
padding: 8px 14px 8px 12px;
border-radius: 9999px;
font-size: 12.5px;
font-weight: 600;
box-shadow: ${styleConf.shadow};
backdrop-filter: blur(14px) saturate(160%);
-webkit-backdrop-filter: blur(14px) saturate(160%);
transition: all 0.32s cubic-bezier(0.16, 1, 0.3, 1);
transform: translateX(20px);
opacity: 0;
pointer-events: auto;
border: 1px solid ${styleConf.border};
display: flex;
align-items: center;
gap: 8px;
max-width: 460px;
box-sizing: border-box;
line-height: 1.4;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
`;
const textSpan = document.createElement('span');
textSpan.textContent = text;
textSpan.style.cssText = 'flex: 1; min-width: 0; letter-spacing: -0.01em;';
toast.appendChild(textSpan);
let isDismissed = false;
const dismiss = () => {
if (isDismissed) return;
isDismissed = true;
toast.style.transform = 'translateX(20px)';
toast.style.opacity = '0';
setTimeout(() => toast.remove(), 350);
};
if (action && action.text) {
const actionBtn = document.createElement('button');
actionBtn.textContent = action.text;
actionBtn.style.cssText = `
background: rgba(255, 255, 255, 0.22);
color: #ffffff;
border: 1px solid rgba(255, 255, 255, 0.45);
border-radius: 9999px;
padding: 2px 9px;
font-size: 11px;
font-weight: 700;
cursor: pointer;
white-space: nowrap;
flex-shrink: 0;
transition: all 0.2s;
outline: none;
margin-left: 4px;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
`;
actionBtn.onmouseenter = () => {
actionBtn.style.background = 'rgba(255, 255, 255, 0.38)';
actionBtn.style.borderColor = 'rgba(255, 255, 255, 0.7)';
};
actionBtn.onmouseleave = () => {
actionBtn.style.background = 'rgba(255, 255, 255, 0.22)';
actionBtn.style.borderColor = 'rgba(255, 255, 255, 0.45)';
};
actionBtn.onclick = (e) => {
e.stopPropagation();
dismiss();
if (typeof action.onClick === 'function') action.onClick();
};
toast.appendChild(actionBtn);
}
container.appendChild(toast);
requestAnimationFrame(() => {
toast.style.transform = 'translateX(0)';
toast.style.opacity = '1';
});
let timer = null;
let isHovering = false;
const startTimer = (ms) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
if (!isHovering) dismiss();
}, ms);
activeToastTimer = timer;
};
// 悬停暂停倒计时,给用户充足的点击交互时间
toast.addEventListener('mouseenter', () => {
isHovering = true;
if (timer) {
clearTimeout(timer);
timer = null;
}
activeToastTimer = null;
});
toast.addEventListener('mouseleave', () => {
isHovering = false;
if (!isDismissed) {
startTimer(2500);
}
});
startTimer(duration);
}
function showAddWatchlistModal(data) {
if (document.getElementById('dudulu-add-watchlist-modal')) return;
const modal = document.createElement('div');
modal.id = 'dudulu-add-watchlist-modal';
modal.style.cssText = `
position: fixed;
top: 28px;
right: 28px;
z-index: 9999999;
width: 320px;
background: rgba(255, 255, 255, 0.98);
border: 1px solid #E2ECF2;
border-radius: 16px;
box-shadow: 0 20px 40px -10px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(12px);
padding: 16px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
animation: duduluSlideDown 0.3s ease-out;
`;
const isEntry = data.mode === 'entry';
const tagText = isEntry ? '🐾 发现新番 · 智能识别' : '🐾 发现新番 · 完播打卡';
const epNum = isEntry ? (data.currentEp || 1) : data.watched_ep;
const epPrefix = isEntry ? '正在观看第 ' : '已看完第 ';
const totalEpStr = data.total_ep ? ` (全${escapeHtml(data.total_ep)}话)` : '';
const coverHtml = data.cover
? `
`
: `📺
`;
let descText = '这部番尚未加入你的嘟嘟噜追番列表,是否一键加入并在嘟嘟噜记录进度?';
if (!isEntry && data.total_ep > 0 && data.watched_ep >= data.total_ep) {
descText = '这部番尚未加入你的追番列表,已看到最终话,是否一键记录并标记为「看完了」?';
}
let btnText = '✨ 加入在看';
if (!isEntry) {
btnText = (data.total_ep > 0 && data.watched_ep >= data.total_ep) ? '✨ 标记看完全集并打卡' : '✨ 加入在看并打卡';
}
modal.innerHTML = `
${coverHtml}
${tagText}
${escapeHtml(data.title)}
${epPrefix}${escapeHtml(epNum)} 话${totalEpStr}
${descText}
`;
document.body.appendChild(modal);
document.getElementById('dudulu-modal-btn-ignore').onclick = () => {
modal.remove();
};
const wrongBtn = document.getElementById('dudulu-modal-btn-wrong');
if (wrongBtn) {
wrongBtn.onclick = () => {
modal.remove();
const curMedia = extractCurrentMediaInfo();
showFeedbackModal({
type: 'wrong_match',
title: curMedia?.title,
episode: curMedia?.episode,
platform: curMedia?.platform,
matchedTitle: data.title,
});
};
}
document.getElementById('dudulu-modal-btn-add').onclick = () => {
const addBtn = document.getElementById('dudulu-modal-btn-add');
if (isEntry) {
if (addBtn) {
addBtn.disabled = true;
addBtn.textContent = '正在加入...';
}
const resetWatchedEp =
data.total_ep > 0 && data.watched_ep >= data.total_ep
? (data.currentEp > 1 ? data.currentEp - 1 : 0)
: undefined;
updateAnimeWatchStatus(data.anime_id, 'watching', resetWatchedEp, (setResp) => {
modal.remove();
if (setResp && setResp.code === 0) {
if (currentMatchedAnime) {
currentMatchedAnime.status = 'watching';
if (typeof resetWatchedEp === 'number') {
currentMatchedAnime.watchedEp = resetWatchedEp;
}
}
showToast('🌸 嘟嘟噜:已加入在看,将为你自动记录观看进度 ✓', 'success', 3500);
if (typeof data.onAdded === 'function') {
data.onAdded();
}
} else {
showToast('设置追番状态失败: ' + (setResp?.message || '未知错误'), 'warning', 4000);
}
});
} else {
modal.remove();
triggerScrobble(1.0, true);
}
};
setTimeout(() => {
if (document.body.contains(modal)) {
modal.remove();
}
}, 15000);
}
// ==========================================
// 6. 问题反馈与未录入番剧收录申请弹窗 (Feedback Modal)
// ==========================================
function showFeedbackModal(options = {}) {
const existing = document.getElementById('dudulu-feedback-modal-wrapper');
if (existing) existing.remove();
const curMedia = extractCurrentMediaInfo();
const rawTitle = options.title || curMedia?.title || '';
const rawEp = options.episode || curMedia?.episode || 1;
const platform = options.platform || curMedia?.platform || location.hostname;
const matchedTitle = options.matchedTitle || '';
const defaultType = options.type || (options.detailMsg?.includes('未能匹配') ? 'not_indexed' : (rawTitle ? 'wrong_match' : 'not_indexed'));
const wrapper = document.createElement('div');
wrapper.id = 'dudulu-feedback-modal-wrapper';
wrapper.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(15, 23, 42, 0.65);
z-index: 10000000;
display: flex;
align-items: center;
justify-content: center;
backdrop-filter: blur(6px);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
`;
const modal = document.createElement('div');
modal.style.cssText = `
background: #ffffff;
color: #1e293b;
width: 440px;
max-width: 92vw;
border-radius: 18px;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.35);
border: 1px solid #e2e8f0;
overflow: hidden;
animation: duduluModalIn 0.25s cubic-bezier(0.16, 1, 0.3, 1);
`;
const displayUrl = location.href.length > 55 ? location.href.slice(0, 52) + '...' : location.href;
modal.innerHTML = `
自动采集的环境信息
• 网页番名: ${escapeHtml(rawTitle || '未能提取')}
• 识别集数: 第 ${escapeHtml(rawEp)} 话 (${escapeHtml(platform)})
${matchedTitle ? `
• 匹配结果: ${escapeHtml(matchedTitle)}
` : ''}
${options.detailMsg ? `
• 提示信息: ${escapeHtml(options.detailMsg)}
` : ''}
• 播放地址: ${escapeHtml(displayUrl)}
`;
wrapper.appendChild(modal);
document.body.appendChild(wrapper);
// 关闭逻辑
const closeModal = () => {
window.removeEventListener('keydown', onKeyDown);
wrapper.remove();
};
const onKeyDown = (e) => {
if (e.key === 'Escape') closeModal();
};
window.addEventListener('keydown', onKeyDown);
// 阻止输入框按键冒泡到播放器 (防止按空格暂停、按F全屏等干扰)
modal.addEventListener('keydown', (e) => {
e.stopPropagation();
});
document.getElementById('dudulu-fb-close-btn').onclick = closeModal;
document.getElementById('dudulu-fb-btn-cancel').onclick = closeModal;
wrapper.onclick = (e) => {
if (e.target === wrapper) closeModal();
};
// 提交逻辑
const submitBtn = document.getElementById('dudulu-fb-btn-submit');
submitBtn.onclick = () => {
const typeSelect = document.getElementById('dudulu-fb-type-select').value;
const comment = document.getElementById('dudulu-fb-comment').value.trim();
const contact = document.getElementById('dudulu-fb-contact').value.trim();
submitBtn.disabled = true;
submitBtn.textContent = '正在提交...';
submitBtn.style.opacity = '0.7';
let fullInfo = `【追番助手反馈 · ${typeSelect}】\n` +
`• 播放地址: ${location.href}\n` +
`• 提取番名: ${rawTitle || '未能提取'}\n` +
`• 识别集数: 第 ${rawEp} 话\n` +
`• 播放平台: ${platform}\n`;
if (matchedTitle) fullInfo += `• 匹配条目: ${matchedTitle}\n`;
if (options.detailMsg) fullInfo += `• 状态报错: ${options.detailMsg}\n`;
if (comment) fullInfo += `• 用户说明: ${comment}\n`;
const apiBase = getApiBase();
const token = getToken();
// 提取纯净 URL,剥离无用的营销跟踪参数 (如 spm_id_from, vd_source, from_spmid 等)
let cleanUrl = location.href;
try {
const u = new URL(location.href);
const trackingKeys = ['spm_id_from', 'vd_source', 'from_spmid', 'share_source', 'share_medium', 'bbid', 'ts'];
trackingKeys.forEach((k) => u.searchParams.delete(k));
cleanUrl = u.toString();
} catch (e) {}
if (cleanUrl.length > 500) cleanUrl = cleanUrl.slice(0, 500);
const payload = {
obj_key: cleanUrl,
info: fullInfo,
contact: contact,
device_info: `Dudulu Scrobbler v1.0.23 | ${navigator.userAgent}`,
};
GM_xmlhttpRequest({
method: 'POST',
url: apiBase + '/api/v2/feedback',
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: 'Bearer ' + token } : {}),
},
data: JSON.stringify(payload),
onload: function (res) {
try {
const resp = JSON.parse(res.responseText);
if (resp.code === 0) {
closeModal();
showToast('🌸 反馈已成功提交!嘟嘟噜管理员会尽快核实处理,感谢你的支持~', 'success', 5000);
} else {
showToast('提交失败: ' + (resp.message || '未知错误'), 'warning', 4000);
submitBtn.disabled = false;
submitBtn.textContent = '🚀 重新提交';
submitBtn.style.opacity = '1';
}
} catch (e) {
showToast('提交失败,响应解析异常', 'warning', 4000);
submitBtn.disabled = false;
submitBtn.textContent = '🚀 重新提交';
submitBtn.style.opacity = '1';
}
},
onerror: function (err) {
showToast('网络请求失败,请检查网络连接', 'warning', 4000);
submitBtn.disabled = false;
submitBtn.textContent = '🚀 重新提交';
submitBtn.style.opacity = '1';
},
});
};
}
})();