// ==UserScript== // @name LibreTV 搜索净化与聚合 // @namespace https://libretv.is-an.org/ // @version 1.8.9 // @description 搜索净化与多源聚合,播放页支持跨源续播/收藏/状态条/片头跳过,含追剧提醒与 WebDAV 同步 // @author Trae // @match https://tv.zymn.cc/* // @match https://tv.vbk.bid/* // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant unsafeWindow // @connect * // @run-at document-idle // @license MIT // ==/UserScript== (function () { 'use strict'; // 供顶层页面检测 iframe 里是否已经运行脚本,避免重复注入 try { const pageWindow = typeof unsafeWindow !== 'undefined' && unsafeWindow ? unsafeWindow : window; pageWindow.__ltvCleanerLoaded = true; } catch (e) { // 忽略 } // 新版站点把播放器放在全屏 iframe 里(地址栏仍是首页), // 因此脚本必须允许在 iframe 内运行;非顶层只初始化播放页功能。 const IS_TOP_FRAME = (function () { try { return window.top === window.self; } catch (e) { return false; } })(); const STYLE_ID = 'ltv-cleaner-style'; const TOOLBAR_ID = 'ltv-cleaner-toolbar'; const HOME_ENTRY_ID = 'ltv-home-entry'; const OVERLAY_ID = 'ltv-cleaner-overlay'; const STATS_ID = 'ltv-cleaner-stats'; const SETTINGS_KEY = 'ltv_cleaner_settings_v1'; const HIDDEN_CLASS = 'ltv-cleaner-hidden'; const NOISE_WORDS = [ '电影解说', '解说', '预告片', '预告', '花絮', '幕后', '特辑', '彩蛋', '片段', '速看', '剪辑', '混剪', '短剧', '综艺' ]; const EXTRA_TAGS = [ '粤语版', '国语版', '粤语', '国语', '中字', '中英双字', '中英字幕', 'HD', '4K', '1080P', '720P', '高清', '蓝光', '完结', '已完结', '全集', '抢先版', '清晰版', '无删减', '未删减' ]; const DEFAULT_SETTINGS = { dedupe: true, filterNoise: true, filterVariety: false, onlyRelevant: false, sort: 'relevance' }; const SORT_VALUES = ['relevance', 'default', 'year', 'title']; const SETTINGS_TIME_KEY = 'ltv_cleaner_settings_updated_at'; const SITE_CONFIG_TIME_KEY = 'ltv_site_config_updated_at'; const SYNC_KEY = 'ltv_sync_config_v1'; const SYNC_FILE = 'libretv-sync.json'; const SYNC_APP = 'LibreTV-SearchCleaner'; const HISTORY_KEY = 'viewingHistory'; const SEARCH_HISTORY_KEY = 'videoSearchHistory'; const VIEWING_META_KEY = 'ltv_viewing_meta_v1'; const SEARCH_META_KEY = 'ltv_search_meta_v1'; const FAVORITES_KEY = 'ltv_favorites_v1'; const FAV_META_KEY = 'ltv_fav_meta_v1'; const FAVORITE_LIMIT = 200; const FAV_AUTO_CHECK_KEY = 'ltv_fav_auto_check_v1'; const FAV_CHECK_INTERVAL = 24 * 60 * 60 * 1000; const FAV_CHECK_FAVORITE_LIMIT = 20; const FAV_CHECK_SOURCE_LIMIT = 5; const FAV_CHECK_TIMEOUT = 7000; const FAV_CHECK_TOTAL_TIMEOUT = 90000; const SHOW_PROGRESS_KEY = 'ltv_show_progress_v1'; const SHOW_PROGRESS_LIMIT = 100; const PLAYER_PROGRESS_SAVE_GAP = 5000; const OP_MARKS_KEY = 'ltv_op_marks_v1'; const OP_LEARN_KEY = 'ltv_op_learn_v1'; const OP_LEARN_ON_KEY = 'ltv_op_learn_on_v1'; const OP_GUESS_RANGE = 10; const OP_FAR_RANGE = 30; const OP_SEGMENT_LIMIT = 50; const OP_SHOW_LIMIT = 200; const TOMBSTONE_LIMIT = 300; const SOURCE_MODAL_ID = 'ltv-source-overlay'; const SOURCE_CACHE_KEY = 'ltv_source_test_cache_v1'; const SOURCE_KEYWORD_KEY = 'ltv_source_test_keyword'; const SOURCE_SHOW_ADULT_KEY = 'ltv_source_show_adult_v1'; const SOURCE_DEFAULT_KEYWORD = '流浪地球'; const SOURCE_TEST_TIMEOUT = 8000; const SOURCE_CACHE_TTL = 30 * 60 * 1000; const CUSTOM_API_MAX = 20; const DEFAULT_SYNC_CONFIG = { url: '', username: '', password: '', device: '', autoSync: true, syncHistory: true, syncSearchHistory: true, syncSiteConfig: true, syncFavorites: true, syncOpMarks: true, lastSyncAt: 0, remoteUpdatedAt: 0, remoteDevice: '' }; let settings = loadSettings(); let syncConfig = loadSyncConfig(); let syncState = 'off'; let syncMessage = ''; let syncInFlight = false; let syncQueued = false; let syncUploadTimer = null; let syncPollTimer = null; let lastUploadAt = 0; let historySnapshot = ''; let syncModal = null; let sourceModal = null; let sourceTab = 'test'; let sourceCatalog = []; let builtinSources = null; let sourceTesting = false; let sourceKeyword = ''; let sourceShowAdult = false; let sourceTestCache = {}; let sourceFormMode = 'add'; let sourceEditIndex = -1; let sourceFormStatus = null; let sourceNotice = ''; let siteConfigSnapshot = ''; let siteConfigApplying = false; let siteConfigStale = false; let siteSyncNoticePending = false; let resultsEl = null; let toolbar = null; let observer = null; let pickerOverlay = null; let favModal = null; let favChecking = false; let parsedCards = []; let renderFavoriteMap = new Map(); let renderFavoriteNormMap = new Map(); let playerStatusBar = null; let playerFavButton = null; let playerVideo = null; let playerOverlayRoot = null; let playerStatusTimer = null; let playerUiTimer = null; let playerUiAutoHide = false; let playerUiBound = false; let playerLastStatusAt = 0; let playerLastSaveAt = 0; let playerEpisodeNo = 0; let playerPromptedEpisodes = {}; let playerMutationObserver = null; let playerWatchTimer = null; let opPanel = null; let opToolsRow = null; let opSkipButton = null; let opMarkBand = null; let opMarkLine = null; let opLastUiAt = 0; let opLastTime = 0; let opLearnToast = null; let renderTimer = null; let waitTimer = null; let urlTimer = null; let lastSignature = ''; let lastSettingsKey = ''; let lastUrl = location.href; let boundResultsEl = null; let groupMap = new Map(); let originalIndexMap = new WeakMap(); let nextOriginalIndex = 0; let parsedCardMap = new WeakMap(); let decorationMap = new WeakMap(); let decoratedCards = []; let renderStamp = 0; let orderSupported = null; function getPageStorage() { try { if (typeof unsafeWindow !== 'undefined' && unsafeWindow && unsafeWindow.localStorage) { return unsafeWindow.localStorage; } } catch (e) { // 某些沙箱设置不允许访问 unsafeWindow } try { return localStorage; } catch (e) { return null; } } function gmGet(key, fallback) { try { if (typeof GM_getValue === 'function') return GM_getValue(key, fallback); } catch (e) { // 回退到本地存储 } try { const store = getPageStorage(); const raw = store ? store.getItem('gm_' + key) : null; return raw ? JSON.parse(raw) : fallback; } catch (e) { return fallback; } } function gmSet(key, value) { try { if (typeof GM_setValue === 'function') { GM_setValue(key, value); return; } } catch (e) { // 回退到本地存储 } try { const store = getPageStorage(); if (store) store.setItem('gm_' + key, JSON.stringify(value)); } catch (e) { // 忽略存储失败 } } function sanitizeSettings(saved) { const result = Object.assign({}, DEFAULT_SETTINGS); if (!saved || typeof saved !== 'object') return result; Object.keys(DEFAULT_SETTINGS).forEach(function (key) { if (key === 'sort') { if (SORT_VALUES.indexOf(saved.sort) >= 0) result.sort = saved.sort; } else if (typeof saved[key] === 'boolean') { result[key] = saved[key]; } }); return result; } function loadSettings() { try { const store = getPageStorage(); const raw = store ? store.getItem(SETTINGS_KEY) : null; return sanitizeSettings(JSON.parse(raw || '{}')); } catch (e) { return Object.assign({}, DEFAULT_SETTINGS); } } function saveSettings(timestamp) { try { const store = getPageStorage(); if (store) store.setItem(SETTINGS_KEY, JSON.stringify(settings)); } catch (e) { // 忽略存储失败 } if (timestamp !== false) { setSettingsUpdatedAt(typeof timestamp === 'number' ? timestamp : Date.now()); } } function getSettingsUpdatedAt() { try { const store = getPageStorage(); const value = store ? store.getItem(SETTINGS_TIME_KEY) : null; return parseInt(value || '0', 10) || 0; } catch (e) { return 0; } } function setSettingsUpdatedAt(timestamp) { try { const store = getPageStorage(); if (store) store.setItem(SETTINGS_TIME_KEY, String(timestamp || 0)); } catch (e) { // 忽略存储失败 } } function detectDeviceName() { const ua = navigator.userAgent || ''; if (/iPad|Tablet|PlayBook|Silk/i.test(ua) || (/Android/i.test(ua) && !/Mobile/i.test(ua)) || (navigator.maxTouchPoints > 1 && /Macintosh/i.test(ua))) { return '平板'; } if (/iPhone|iPod|Android.*Mobile|Mobile/i.test(ua)) { return '手机'; } return '电脑'; } function confirmDialog(message) { try { if (typeof unsafeWindow !== 'undefined' && typeof unsafeWindow.confirm === 'function') { return unsafeWindow.confirm(message); } } catch (e) { // 回退到沙箱窗口 } return window.confirm(message); } function loadSyncConfig() { const result = Object.assign({}, DEFAULT_SYNC_CONFIG); let saved = gmGet(SYNC_KEY, null); if (typeof saved === 'string') { try { saved = JSON.parse(saved); } catch (e) { saved = null; } } if (saved && typeof saved === 'object') { ['url', 'username', 'password', 'device', 'remoteDevice'].forEach(function (key) { if (typeof saved[key] === 'string') result[key] = saved[key]; }); ['autoSync', 'syncHistory', 'syncSearchHistory', 'syncSiteConfig', 'syncFavorites', 'syncOpMarks'].forEach(function (key) { if (typeof saved[key] === 'boolean') result[key] = saved[key]; }); ['lastSyncAt', 'remoteUpdatedAt'].forEach(function (key) { if (typeof saved[key] === 'number') result[key] = saved[key]; }); } if (!result.device) result.device = detectDeviceName(); return result; } function saveSyncConfig() { gmSet(SYNC_KEY, syncConfig); } function readViewingHistory() { try { const store = getPageStorage(); const parsed = JSON.parse((store && store.getItem(HISTORY_KEY)) || '[]'); return Array.isArray(parsed) ? parsed : []; } catch (e) { return []; } } function writeViewingHistory(list) { try { const store = getPageStorage(); if (store) store.setItem(HISTORY_KEY, JSON.stringify((list || []).slice(0, 50))); } catch (e) { // 忽略存储失败 } } function normalizeSearchEntry(item) { if (typeof item === 'string') { const text = item.trim(); return text ? { text: text, timestamp: 0 } : null; } if (item && typeof item === 'object' && typeof item.text === 'string') { const text = item.text.trim(); return text ? { text: text, timestamp: Number(item.timestamp) || 0 } : null; } return null; } function readSearchHistory() { try { const store = getPageStorage(); const parsed = JSON.parse((store && store.getItem(SEARCH_HISTORY_KEY)) || '[]'); if (!Array.isArray(parsed)) return []; return parsed.map(normalizeSearchEntry).filter(Boolean); } catch (e) { return []; } } function writeSearchHistory(list) { try { const store = getPageStorage(); if (!store) return; const normalized = (list || []).map(normalizeSearchEntry).filter(Boolean).slice(0, 5); store.setItem(SEARCH_HISTORY_KEY, JSON.stringify(normalized)); } catch (e) { // 忽略存储失败 } } function normalizeTombstoneMap(raw) { const result = {}; if (raw && typeof raw === 'object' && !Array.isArray(raw)) { Object.keys(raw).forEach(function (key) { const timestamp = Number(raw[key]) || 0; if (key && timestamp > 0) result[key] = timestamp; }); } return result; } function normalizeViewingMeta(raw) { return { deletions: normalizeTombstoneMap(raw && raw.deletions), clearedAt: Number((raw && raw.clearedAt) || 0) || 0 }; } function normalizeSearchMeta(raw) { return { deletions: normalizeTombstoneMap(raw && raw.deletions), clearedAt: Number((raw && raw.clearedAt) || 0) || 0 }; } function readViewingMeta() { try { const store = getPageStorage(); return normalizeViewingMeta(JSON.parse((store && store.getItem(VIEWING_META_KEY)) || '{}')); } catch (e) { return normalizeViewingMeta(null); } } function writeViewingMeta(meta) { try { const store = getPageStorage(); if (store) store.setItem(VIEWING_META_KEY, JSON.stringify(normalizeViewingMeta(meta))); } catch (e) { // 忽略存储失败 } } function readSearchMeta() { try { const store = getPageStorage(); return normalizeSearchMeta(JSON.parse((store && store.getItem(SEARCH_META_KEY)) || '{}')); } catch (e) { return normalizeSearchMeta(null); } } function writeSearchMeta(meta) { try { const store = getPageStorage(); if (store) store.setItem(SEARCH_META_KEY, JSON.stringify(normalizeSearchMeta(meta))); } catch (e) { // 忽略存储失败 } } function mergeHistoryMeta(localMeta, remoteMeta) { const local = localMeta || normalizeViewingMeta(null); const remote = remoteMeta || normalizeViewingMeta(null); const mergedDeletions = {}; [local.deletions, remote.deletions].forEach(function (map) { Object.keys(map || {}).forEach(function (key) { mergedDeletions[key] = Math.max(mergedDeletions[key] || 0, map[key] || 0); }); }); const clearedAt = Math.max(Number(local.clearedAt) || 0, Number(remote.clearedAt) || 0); const keys = Object.keys(mergedDeletions) .filter(function (key) { return mergedDeletions[key] > clearedAt; }) .sort(function (a, b) { return mergedDeletions[b] - mergedDeletions[a]; }) .slice(0, TOMBSTONE_LIMIT); const deletions = {}; keys.forEach(function (key) { deletions[key] = mergedDeletions[key]; }); return { deletions: deletions, clearedAt: clearedAt }; } function sameHistoryMeta(left, right) { return stableStringify({ deletions: (left && left.deletions) || {}, clearedAt: Number((left && left.clearedAt) || 0) || 0 }) === stableStringify({ deletions: (right && right.deletions) || {}, clearedAt: Number((right && right.clearedAt) || 0) || 0 }); } function filterViewingHistory(list, meta) { const clearedAt = Number(meta && meta.clearedAt) || 0; const deletions = (meta && meta.deletions) || {}; return (list || []).filter(function (entry) { if (!entry || typeof entry !== 'object') return false; const timestamp = Number(entry.timestamp) || 0; if (clearedAt && timestamp <= clearedAt) return false; const deletedAt = Math.max( Number(deletions[entry.url]) || 0, entry.title ? Number(deletions['t:' + entry.title]) || 0 : 0 ); if (deletedAt && timestamp <= deletedAt) return false; return true; }); } function filterSearchHistory(list, meta) { const clearedAt = Number(meta && meta.clearedAt) || 0; const deletions = (meta && meta.deletions) || {}; return (list || []).filter(function (entry) { if (!entry) return false; const timestamp = Number(entry.timestamp) || 0; if (clearedAt && (!timestamp || timestamp <= clearedAt)) return false; const deletedAt = Number(deletions[entry.text]) || 0; if (deletedAt && (!timestamp || timestamp <= deletedAt)) return false; return true; }); } function scheduleHistoryMetaUpload(kind) { if (!syncConfig.url || !syncConfig.autoSync) return; if (kind === 'viewing' && !syncConfig.syncHistory) return; if (kind === 'search' && !syncConfig.syncSearchHistory) return; scheduleSyncUpload(true); } function recordViewingDeletion(url, title) { if (!url && !title) return; const now = Date.now(); const meta = readViewingMeta(); if (url) meta.deletions[url] = Math.max(Number(meta.deletions[url]) || 0, now); if (title) meta.deletions['t:' + title] = Math.max(Number(meta.deletions['t:' + title]) || 0, now); writeViewingMeta(meta); refreshHistorySnapshot(); scheduleHistoryMetaUpload('viewing'); } function recordViewingClear() { const meta = readViewingMeta(); meta.clearedAt = Date.now(); meta.deletions = {}; writeViewingMeta(meta); refreshHistorySnapshot(); scheduleHistoryMetaUpload('viewing'); } function recordSearchDeletion(text) { const query = String(text || '').trim(); if (!query) return; const now = Date.now(); const meta = readSearchMeta(); meta.deletions[query] = Math.max(Number(meta.deletions[query]) || 0, now); writeSearchMeta(meta); scheduleHistoryMetaUpload('search'); } function recordSearchClear() { const meta = readSearchMeta(); meta.clearedAt = Date.now(); meta.deletions = {}; writeSearchMeta(meta); scheduleHistoryMetaUpload('search'); } function installHistoryHooks() { const win = getSiteWindow(); if (!win) return; try { if (win.__ltvHistoryHooks) return; win.__ltvHistoryHooks = true; } catch (e) { return; } const wrap = function (name, beforeFn, afterFn) { const original = win[name]; if (typeof original !== 'function' || original.__ltvWrapped) return; const wrapped = function () { const args = Array.prototype.slice.call(arguments); let before = null; try { before = beforeFn ? beforeFn(args) : null; } catch (e) { // 忽略前置快照失败 } let result; try { result = original.apply(this, args); } finally { try { afterFn(args, before); } catch (e) { // 忽略删除记录失败,不影响站点原逻辑 } } return result; }; wrapped.__ltvWrapped = true; try { win[name] = wrapped; } catch (e) { // 某些沙箱不允许覆盖页面函数 } }; wrap('deleteHistoryItem', function (args) { const encodedUrl = String(args[0] || ''); let url = encodedUrl; try { url = decodeURIComponent(encodedUrl); } catch (e) { // 使用原始值 } const entry = readViewingHistory().find(function (item) { return item && item.url === url; }); return { url: url, title: entry ? String(entry.title || '') : '', existed: !!entry }; }, function (args, before) { if (!before || !before.existed) return; const stillExists = readViewingHistory().some(function (item) { return item && item.url === before.url; }); if (!stillExists) recordViewingDeletion(before.url, before.title); }); wrap('clearViewingHistory', function () { return { count: readViewingHistory().length }; }, function (args, before) { if (before && before.count > 0 && readViewingHistory().length === 0) { recordViewingClear(); } }); wrap('deleteSingleSearchHistory', function (args) { const text = String(args[0] || '').trim(); return { text: text, existed: readSearchHistory().some(function (item) { return item && item.text === text; }) }; }, function (args, before) { if (!before || !before.existed) return; const stillExists = readSearchHistory().some(function (item) { return item && item.text === before.text; }); if (!stillExists) recordSearchDeletion(before.text); }); wrap('clearSearchHistory', function () { return { count: readSearchHistory().length }; }, function (args, before) { if (before && before.count > 0 && readSearchHistory().length === 0) { recordSearchClear(); } }); } function refreshSiteHistoryViews() { const win = getSiteWindow(); try { if (typeof win.loadViewingHistory === 'function') win.loadViewingHistory(); } catch (e) { // 站点未打开历史面板时忽略 } try { if (typeof win.renderSearchHistory === 'function') win.renderSearchHistory(); } catch (e) { // 站点未渲染搜索历史时忽略 } } function mergeViewingHistory(localList, remoteList, meta) { const localFiltered = filterViewingHistory(localList, meta || {}); const remoteFiltered = filterViewingHistory(remoteList, meta || {}); const map = new Map(); const all = []; all.push.apply(all, remoteFiltered); all.push.apply(all, localFiltered); for (const item of all) { if (!item || typeof item.title !== 'string' || !item.title) continue; const existing = map.get(item.title); if (!existing) { map.set(item.title, Object.assign({}, item)); continue; } const itemTime = Number(item.timestamp) || 0; const existingTime = Number(existing.timestamp) || 0; const newer = itemTime >= existingTime ? item : existing; const older = newer === item ? existing : item; const merged = Object.assign({}, newer); if (Number(newer.episodeIndex) === Number(older.episodeIndex)) { merged.playbackPosition = Math.max( Number(newer.playbackPosition) || 0, Number(older.playbackPosition) || 0 ); merged.duration = Math.max( Number(newer.duration) || 0, Number(older.duration) || 0 ); } const newerEpisodes = Array.isArray(newer.episodes) ? newer.episodes : []; const olderEpisodes = Array.isArray(older.episodes) ? older.episodes : []; if (olderEpisodes.length > newerEpisodes.length) { merged.episodes = olderEpisodes.slice(); } else if (newerEpisodes.length) { merged.episodes = newerEpisodes.slice(); } map.set(item.title, merged); } return Array.from(map.values()) .sort(function (a, b) { const byTime = (Number(b.timestamp) || 0) - (Number(a.timestamp) || 0); if (byTime) return byTime; return String(a.title || '').localeCompare(String(b.title || ''), 'zh-CN'); }) .slice(0, 50); } function mergeSearchHistory(localList, remoteList, meta) { const map = new Map(); const add = function (item) { const entry = normalizeSearchEntry(item); if (!entry) return; const existing = map.get(entry.text); if (!existing || entry.timestamp > existing.timestamp) { map.set(entry.text, entry); } }; const localFiltered = filterSearchHistory( (localList || []).map(normalizeSearchEntry).filter(Boolean), meta || {} ); const remoteFiltered = filterSearchHistory( (remoteList || []).map(normalizeSearchEntry).filter(Boolean), meta || {} ); remoteFiltered.forEach(add); localFiltered.forEach(add); return Array.from(map.values()) .sort(function (a, b) { const byTime = (Number(b.timestamp) || 0) - (Number(a.timestamp) || 0); if (byTime) return byTime; return a.text.localeCompare(b.text, 'zh-CN'); }) .slice(0, 5); } function parseEpisodeInfo(remarks) { const text = String(remarks || '').replace(/\s+/g, ''); let episode = 0; const pushNumber = function (value) { const number = parseInt(value, 10) || 0; if (number > episode) episode = number; }; (text.match(/(\d+)\s*集/g) || []).forEach(function (item) { pushNumber(String(item).replace(/[^\d]/g, '')); }); const updateMatch = text.match(/(?:更新至|更新到|第)(\d+)/); if (updateMatch) pushNumber(updateMatch[1]); const fullMatch = text.match(/全(\d+)集/); if (fullMatch) pushNumber(fullMatch[1]); const finished = /(已完结|完结|大结局|全集|全\d+集)/.test(text); return { episode: episode, finished: finished }; } function normalizeFavorite(raw) { if (!raw || typeof raw.key !== 'string' || !raw.key) return null; if (typeof raw.title !== 'string' || !raw.title) return null; return { key: raw.key, title: raw.title, norm: typeof raw.norm === 'string' ? raw.norm : '', kind: typeof raw.kind === 'string' ? raw.kind : '', year: String(raw.year || ''), type: String(raw.type || ''), remarks: String(raw.remarks || ''), poster: String(raw.poster || ''), episode: Number(raw.episode) || 0, finished: !!raw.finished, latestEpisode: Number(raw.latestEpisode) || 0, latestFinished: !!raw.latestFinished, latestRemarks: String(raw.latestRemarks || ''), hasUpdate: !!raw.hasUpdate, follow: raw.follow !== false, sourceCode: String(raw.sourceCode || raw.source || ''), id: String(raw.id || ''), addedAt: Number(raw.addedAt) || 0, updatedAt: Number(raw.updatedAt) || Number(raw.addedAt) || 0, checkedAt: Number(raw.checkedAt) || 0 }; } function readFavorites() { try { const store = getPageStorage(); const parsed = JSON.parse((store && store.getItem(FAVORITES_KEY)) || '[]'); if (!Array.isArray(parsed)) return []; return parsed .map(normalizeFavorite) .filter(Boolean) .sort(function (a, b) { if (!!a.hasUpdate !== !!b.hasUpdate) return a.hasUpdate ? -1 : 1; return (b.addedAt || 0) - (a.addedAt || 0); }) .slice(0, FAVORITE_LIMIT); } catch (e) { return []; } } function writeFavorites(list) { try { const store = getPageStorage(); if (!store) return; const normalized = (list || []).map(normalizeFavorite).filter(Boolean).slice(0, FAVORITE_LIMIT); store.setItem(FAVORITES_KEY, JSON.stringify(normalized)); } catch (e) { // 忽略存储失败 } } function readFavMeta() { try { const store = getPageStorage(); return normalizeViewingMeta(JSON.parse((store && store.getItem(FAV_META_KEY)) || '{}')); } catch (e) { return normalizeViewingMeta(null); } } function writeFavMeta(meta) { try { const store = getPageStorage(); if (store) store.setItem(FAV_META_KEY, JSON.stringify(normalizeViewingMeta(meta))); } catch (e) { // 忽略存储失败 } } function filterFavorites(list, meta) { const clearedAt = Number(meta && meta.clearedAt) || 0; const deletions = (meta && meta.deletions) || {}; return (list || []).filter(function (raw) { const entry = normalizeFavorite(raw); if (!entry) return false; const timestamp = entry.updatedAt || entry.addedAt || 0; if (clearedAt && timestamp <= clearedAt) return false; const deletedAt = Number(deletions[entry.key]) || 0; if (deletedAt && timestamp <= deletedAt) return false; return true; }); } function mergeFavorites(localList, remoteList, meta) { const map = new Map(); const add = function (raw) { const entry = normalizeFavorite(raw); if (!entry) return; const existing = map.get(entry.key); if (!existing) { map.set(entry.key, entry); return; } const winner = entry.updatedAt >= existing.updatedAt ? entry : existing; const other = winner === entry ? existing : entry; const merged = Object.assign({}, winner); merged.addedAt = Math.min(existing.addedAt || winner.addedAt, entry.addedAt || winner.addedAt); merged.episode = Math.max(existing.episode || 0, entry.episode || 0); const latestSource = (entry.latestEpisode || 0) >= (existing.latestEpisode || 0) ? entry : existing; merged.latestEpisode = Math.max(existing.latestEpisode || 0, entry.latestEpisode || 0); merged.latestFinished = existing.latestFinished || entry.latestFinished; if (latestSource.latestRemarks) merged.latestRemarks = latestSource.latestRemarks; else if (other.latestRemarks) merged.latestRemarks = other.latestRemarks; merged.checkedAt = Math.max(existing.checkedAt || 0, entry.checkedAt || 0); if (merged.latestEpisode > merged.episode || (!merged.finished && merged.latestFinished) || merged.hasUpdate) { merged.hasUpdate = true; } map.set(entry.key, merged); }; filterFavorites(remoteList, meta).forEach(add); filterFavorites(localList, meta).forEach(add); return Array.from(map.values()) .sort(function (a, b) { if (!!a.hasUpdate !== !!b.hasUpdate) return a.hasUpdate ? -1 : 1; return (b.addedAt || 0) - (a.addedAt || 0); }) .slice(0, FAVORITE_LIMIT); } function findFavorite(key) { if (!key) return null; return readFavorites().find(function (item) { return item.key === key; }) || null; } function favoriteStats() { const list = readFavorites(); return { count: list.length, updates: list.filter(function (item) { return item.hasUpdate; }).length }; } function scheduleFavoriteUpload() { if (!syncConfig.url || !syncConfig.autoSync || !syncConfig.syncFavorites) return; scheduleSyncUpload(true); } function recordFavoriteDeletion(key) { if (!key) return; const meta = readFavMeta(); meta.deletions[key] = Date.now(); writeFavMeta(meta); scheduleFavoriteUpload(); } function recordFavoriteClear() { const meta = readFavMeta(); meta.clearedAt = Date.now(); meta.deletions = {}; writeFavMeta(meta); scheduleFavoriteUpload(); } function stableStringify(value) { if (Array.isArray(value)) { return '[' + value.map(stableStringify).join(',') + ']'; } if (value && typeof value === 'object') { return '{' + Object.keys(value).sort().map(function (key) { return JSON.stringify(key) + ':' + stableStringify(value[key]); }).join(',') + '}'; } return JSON.stringify(value); } function sameList(left, right) { return stableStringify(left || []) === stableStringify(right || []); } function normalizeDavUrl(raw) { let url = String(raw || '').trim(); if (!url) return ''; if (!/^https?:\/\//i.test(url)) url = 'https://' + url; if (url.indexOf('?') >= 0 || url.indexOf('#') >= 0) return ''; if (/\.json$/i.test(url)) return url; if (url.charAt(url.length - 1) !== '/') url += '/'; return url + SYNC_FILE; } function basicAuthHeader(user, password) { const raw = String(user || '') + ':' + String(password || ''); if (!user && !password) return null; try { if (typeof TextEncoder === 'function') { const bytes = new TextEncoder().encode(raw); let binary = ''; bytes.forEach(function (byte) { binary += String.fromCharCode(byte); }); return 'Basic ' + btoa(binary); } } catch (e) { // 回退到旧编码方式 } try { return 'Basic ' + btoa(unescape(encodeURIComponent(raw))); } catch (e) { return null; } } function davRequest(method, url, body, config, timeout) { const cfg = config || syncConfig; const headers = {}; const auth = basicAuthHeader(cfg.username, cfg.password); if (auth) headers.Authorization = auth; if (body !== undefined && body !== null) { headers['Content-Type'] = 'application/json; charset=utf-8'; } const limit = timeout || 20000; return new Promise(function (resolve, reject) { if (typeof GM_xmlhttpRequest === 'function') { GM_xmlhttpRequest({ method: method, url: url, headers: headers, data: body === undefined ? undefined : body, timeout: limit, anonymous: true, onload: function (response) { resolve({ status: response.status, text: response.responseText || '' }); }, onerror: function () { reject(new Error('网络连接失败,检查地址、网络或证书')); }, ontimeout: function () { reject(new Error('连接超时')); } }); return; } fetch(url, { method: method, headers: headers, body: body === undefined ? undefined : body, cache: 'no-store' }).then(function (response) { return response.text().then(function (text) { resolve({ status: response.status, text: text }); }); }).catch(function () { reject(new Error('网络连接失败,检查地址、网络或 CORS')); }); }); } async function davGet(config) { const fileUrl = normalizeDavUrl(config.url); if (!fileUrl) throw new Error('请填写有效的 WebDAV 地址'); const response = await davRequest('GET', fileUrl, undefined, config); if (response.status === 404) return { exists: false, data: null }; if (response.status === 401) throw new Error('认证失败,请检查用户名和密码'); if (response.status === 403) throw new Error('没有权限读取云端文件'); if (response.status < 200 || response.status >= 300) { throw new Error('云端返回 HTTP ' + response.status); } let data; try { data = JSON.parse(response.text); } catch (e) { throw new Error('云端文件不是有效的 JSON'); } if (!data || data.app !== SYNC_APP || !data.settings || typeof data.settings !== 'object') { throw new Error('云端文件不是本脚本的同步数据'); } return { exists: true, data: data }; } async function davPut(payload, config) { const fileUrl = normalizeDavUrl(config.url); if (!fileUrl) throw new Error('请填写有效的 WebDAV 地址'); const response = await davRequest('PUT', fileUrl, JSON.stringify(payload), config); if (response.status >= 200 && response.status < 300) return true; if (response.status === 401) throw new Error('认证失败,请检查用户名和密码'); if (response.status === 403) throw new Error('没有权限写入云端文件'); if (response.status === 404 || response.status === 409) { throw new Error('目标目录不存在,请先在 WebDAV 中创建该目录'); } if (response.status === 507) throw new Error('WebDAV 空间不足'); throw new Error('上传失败,云端返回 HTTP ' + response.status); } function buildPayload(config, remoteData, forceLocalSiteConfig) { const cfg = config || syncConfig; const now = Date.now(); const payload = { app: SYNC_APP, schema: 1, updatedAt: now, settingsUpdatedAt: getSettingsUpdatedAt() || now, device: cfg.device || detectDeviceName(), settings: Object.assign({}, settings) }; if (cfg.syncHistory) { const remoteMeta = normalizeViewingMeta(remoteData && remoteData.viewingMeta); const mergedMeta = mergeHistoryMeta(readViewingMeta(), remoteMeta); payload.viewingMeta = mergedMeta; payload.viewingHistory = mergeViewingHistory( readViewingHistory(), remoteData && Array.isArray(remoteData.viewingHistory) ? remoteData.viewingHistory : [], mergedMeta ); } else { if (remoteData && Array.isArray(remoteData.viewingHistory)) { payload.viewingHistory = remoteData.viewingHistory; } if (remoteData && remoteData.viewingMeta) { payload.viewingMeta = normalizeViewingMeta(remoteData.viewingMeta); } } if (cfg.syncSearchHistory) { const remoteMeta = normalizeSearchMeta(remoteData && remoteData.searchMeta); const mergedMeta = mergeHistoryMeta(readSearchMeta(), remoteMeta); payload.searchMeta = mergedMeta; payload.searchHistory = mergeSearchHistory( readSearchHistory(), remoteData && Array.isArray(remoteData.searchHistory) ? remoteData.searchHistory : [], mergedMeta ); } else { if (remoteData && Array.isArray(remoteData.searchHistory)) { payload.searchHistory = remoteData.searchHistory; } if (remoteData && remoteData.searchMeta) { payload.searchMeta = normalizeSearchMeta(remoteData.searchMeta); } } if (cfg.syncFavorites) { const remoteMeta = normalizeViewingMeta(remoteData && remoteData.favoritesMeta); const mergedMeta = mergeHistoryMeta(readFavMeta(), remoteMeta); payload.favoritesMeta = mergedMeta; payload.favorites = mergeFavorites( readFavorites(), remoteData && Array.isArray(remoteData.favorites) ? remoteData.favorites : [], mergedMeta ); } else { if (remoteData && Array.isArray(remoteData.favorites)) { payload.favorites = remoteData.favorites; } if (remoteData && remoteData.favoritesMeta) { payload.favoritesMeta = normalizeViewingMeta(remoteData.favoritesMeta); } } if (cfg.syncOpMarks) { payload.opMarks = mergeOpMarks(readOpMarks(), remoteData && remoteData.opMarks); } else if (remoteData && remoteData.opMarks) { payload.opMarks = normalizeOpMarks(remoteData.opMarks); } if (cfg.syncSiteConfig) { const localSite = readSiteConfigState(); const remoteSite = normalizeSiteConfigPayload(remoteData ? remoteData.siteConfig : null); const remoteSiteAt = remoteData ? Number(remoteData.siteConfigUpdatedAt || 0) : 0; const localSiteAt = getSiteConfigUpdatedAt(); const remoteWins = !forceLocalSiteConfig && remoteSiteAt > localSiteAt; const unionDefinitions = !localSiteAt || !remoteSiteAt || localSiteAt === remoteSiteAt; const mergedSite = mergeSiteConfigs(localSite, remoteSite, remoteWins, unionDefinitions); const mergedSitePayload = { customAPIs: mergedSite.customAPIs, selectedUrls: mergedSite.selectedUrls }; payload.siteConfig = mergedSitePayload; // 配置没变时沿用云端时间戳,避免每次上传都把“源配置更新时间”推到现在, // 导致其他设备离线修改的源配置被误判为更旧而丢失 const sameAsRemote = !!remoteData && sameSiteConfig(mergedSitePayload, remoteSite); payload.siteConfigUpdatedAt = sameAsRemote ? (Number(remoteData.siteConfigUpdatedAt) || now) : now; } else if (remoteData && remoteData.siteConfig) { payload.siteConfig = remoteData.siteConfig; payload.siteConfigUpdatedAt = Number(remoteData.siteConfigUpdatedAt) || now; } return payload; } function applyRemoteSettings(remoteSettings, remoteTimestamp) { settings = sanitizeSettings(remoteSettings); saveSettings(typeof remoteTimestamp === 'number' ? remoteTimestamp : Date.now()); if (toolbar) syncToolbar(); if (resultsEl) render(true); } function formatSyncTime(timestamp) { const value = Number(timestamp) || 0; if (!value) return '尚未同步'; const date = new Date(value); const pad = function (number) { return number < 10 ? '0' + number : String(number); }; return pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()); } function setSyncState(state, message) { syncState = state; syncMessage = message || ''; updateSyncIndicators(); } function hasPlayerDom() { // 新版站点可能把播放器渲染在根路径或 SPA 容器里,只要页面出现播放器 DOM 就当作播放页 return !!(document.getElementById('player') || document.getElementById('playerContainer') || document.getElementById('episodeInfo')); } function isPlayerPage() { const path = String(location.pathname || '').toLowerCase(); if (path.indexOf('/player') === 0 || path.indexOf('/watch') === 0) return true; return hasPlayerDom(); } function getHistorySignature() { return JSON.stringify({ h: readViewingHistory().map(function (item) { return [item.title, item.episodeIndex, item.timestamp, item.playbackPosition]; }), s: readSearchHistory(), f: readFavorites().map(function (item) { return [item.key, item.updatedAt, item.hasUpdate, item.episode, item.latestEpisode]; }) }); } function refreshHistorySnapshot() { historySnapshot = getHistorySignature(); } async function runSync(mode, configOverride) { const cfg = configOverride || syncConfig; if (!cfg.url) { setSyncState('off', '未配置 WebDAV'); return null; } if (syncInFlight) { syncQueued = true; return null; } syncInFlight = true; const firstSync = syncConfig.lastSyncAt === 0; const isUpload = mode === 'upload' || mode === 'upload-force'; const label = mode === 'restore' ? '正在从云端恢复...' : (isUpload ? '正在上传...' : '正在同步...'); setSyncState('syncing', label); try { if (isUpload) { if (mode === 'upload-force') setSettingsUpdatedAt(Date.now()); const remote = await davGet(cfg); if (mode !== 'upload-force' && remote.exists) { const remoteSettingsAt = Number(remote.data.settingsUpdatedAt || remote.data.updatedAt || 0); if (remoteSettingsAt > getSettingsUpdatedAt()) { applyRemoteSettings(remote.data.settings, remoteSettingsAt); } } const payload = buildPayload(cfg, remote.exists ? remote.data : null, mode === 'upload-force'); await davPut(payload, cfg); lastUploadAt = Date.now(); syncConfig.lastSyncAt = Date.now(); syncConfig.remoteUpdatedAt = payload.updatedAt; syncConfig.remoteDevice = payload.device; saveSyncConfig(); refreshHistorySnapshot(); setSyncState('ready', '已上传 · ' + formatSyncTime(payload.updatedAt)); return { uploaded: true, payload: payload }; } const remote = await davGet(cfg); const remoteData = remote.exists ? remote.data : null; if (mode === 'restore' && !remoteData) { syncConfig.lastSyncAt = Date.now(); saveSyncConfig(); setSyncState('ready', '云端还没有同步文件'); return { restored: false }; } if (remoteData) { syncConfig.remoteUpdatedAt = Number(remoteData.updatedAt) || syncConfig.remoteUpdatedAt; syncConfig.remoteDevice = remoteData.device || syncConfig.remoteDevice; } let appliedRemoteSettings = false; let localHistoryChanged = false; let localSearchChanged = false; let localFavoritesChanged = false; let localOpMarksChanged = false; let historyRemoteDiff = false; let searchRemoteDiff = false; let favoritesRemoteDiff = false; let opMarksRemoteDiff = false; let siteConfigChanged = false; let siteConfigRemoteDiff = false; if (remoteData) { const remoteSettingsAt = Number(remoteData.settingsUpdatedAt || remoteData.updatedAt || 0); const localSettingsAt = getSettingsUpdatedAt(); if (mode === 'restore' || remoteSettingsAt >= localSettingsAt) { applyRemoteSettings(remoteData.settings, remoteSettingsAt); appliedRemoteSettings = true; } } if (cfg.syncHistory) { const localHistory = readViewingHistory(); const remoteHistory = remoteData && Array.isArray(remoteData.viewingHistory) ? remoteData.viewingHistory : []; const localMeta = readViewingMeta(); const remoteMeta = normalizeViewingMeta(remoteData && remoteData.viewingMeta); const mergedMeta = mergeHistoryMeta(localMeta, remoteMeta); if (!sameHistoryMeta(mergedMeta, localMeta)) { writeViewingMeta(mergedMeta); localHistoryChanged = true; } if (remoteData && !sameHistoryMeta(mergedMeta, remoteMeta)) historyRemoteDiff = true; if (!remoteData && (Object.keys(mergedMeta.deletions).length || mergedMeta.clearedAt)) { historyRemoteDiff = true; } const merged = mergeViewingHistory(localHistory, remoteHistory, mergedMeta); if (!sameList(merged, localHistory)) { writeViewingHistory(merged); localHistoryChanged = true; } if (remoteData && !sameList(merged, remoteHistory)) historyRemoteDiff = true; if (!remoteData && merged.length) historyRemoteDiff = true; } if (cfg.syncSearchHistory) { const localSearch = readSearchHistory(); const remoteSearch = remoteData && Array.isArray(remoteData.searchHistory) ? remoteData.searchHistory : []; const localMeta = readSearchMeta(); const remoteMeta = normalizeSearchMeta(remoteData && remoteData.searchMeta); const mergedMeta = mergeHistoryMeta(localMeta, remoteMeta); if (!sameHistoryMeta(mergedMeta, localMeta)) { writeSearchMeta(mergedMeta); localSearchChanged = true; } if (remoteData && !sameHistoryMeta(mergedMeta, remoteMeta)) searchRemoteDiff = true; if (!remoteData && (Object.keys(mergedMeta.deletions).length || mergedMeta.clearedAt)) { searchRemoteDiff = true; } const merged = mergeSearchHistory(localSearch, remoteSearch, mergedMeta); if (!sameList(merged, localSearch)) { writeSearchHistory(merged); localSearchChanged = true; } if (remoteData && !sameList(merged, remoteSearch)) searchRemoteDiff = true; if (!remoteData && merged.length) searchRemoteDiff = true; } if (localHistoryChanged || localSearchChanged) refreshSiteHistoryViews(); if (cfg.syncFavorites) { const localFavorites = readFavorites(); const remoteFavorites = remoteData && Array.isArray(remoteData.favorites) ? remoteData.favorites : []; const localMeta = readFavMeta(); const remoteMeta = normalizeViewingMeta(remoteData && remoteData.favoritesMeta); const mergedMeta = mergeHistoryMeta(localMeta, remoteMeta); if (!sameHistoryMeta(mergedMeta, localMeta)) { writeFavMeta(mergedMeta); localFavoritesChanged = true; } if (remoteData && !sameHistoryMeta(mergedMeta, remoteMeta)) favoritesRemoteDiff = true; if (!remoteData && (Object.keys(mergedMeta.deletions).length || mergedMeta.clearedAt)) { favoritesRemoteDiff = true; } const merged = mergeFavorites(localFavorites, remoteFavorites, mergedMeta); if (!sameList(merged, localFavorites)) { writeFavorites(merged); localFavoritesChanged = true; } if (remoteData && !sameList(merged, remoteFavorites)) favoritesRemoteDiff = true; if (!remoteData && merged.length) favoritesRemoteDiff = true; } if (localFavoritesChanged) { updateFavoriteIndicators(); refreshFavoriteButtons(); if (favModal) renderFavList(); } if (cfg.syncOpMarks) { const localOpMarks = readOpMarks(); const remoteOpMarks = normalizeOpMarks(remoteData && remoteData.opMarks); const mergedOpMarks = mergeOpMarks(localOpMarks, remoteOpMarks); if (!sameOpMarks(mergedOpMarks, localOpMarks)) { writeOpMarks(mergedOpMarks); localOpMarksChanged = true; } if (remoteData && !sameOpMarks(mergedOpMarks, remoteOpMarks)) opMarksRemoteDiff = true; if (!remoteData && Object.keys(mergedOpMarks.shows).length) opMarksRemoteDiff = true; } if (localOpMarksChanged) { refreshOpPlayerUi(true); if (opPanel) renderOpPanel(); } if (cfg.syncSiteConfig) { const localSite = readSiteConfigState(); const remoteSite = normalizeSiteConfigPayload(remoteData ? remoteData.siteConfig : null); const remoteSiteAt = remoteData ? Number(remoteData.siteConfigUpdatedAt || remoteData.updatedAt || 0) : 0; const localSiteAt = getSiteConfigUpdatedAt(); const remoteWins = mode === 'restore' || remoteSiteAt > localSiteAt; const unionDefinitions = !localSiteAt || !remoteSiteAt || localSiteAt === remoteSiteAt; const mergedSite = mergeSiteConfigs(localSite, remoteSite, remoteWins, unionDefinitions); siteConfigChanged = applySiteConfigState( mergedSite, remoteWins ? remoteSiteAt : localSiteAt ); if (remoteData) { siteConfigRemoteDiff = !sameSiteConfig( { customAPIs: mergedSite.customAPIs, selectedUrls: mergedSite.selectedUrls }, remoteSite ); } else if (mergedSite.customAPIs.length) { siteConfigRemoteDiff = true; } } let uploaded = false; if (mode !== 'restore') { const remoteSettingsAt = remoteData ? Number(remoteData.settingsUpdatedAt || remoteData.updatedAt || 0) : 0; const localSettingsAt = getSettingsUpdatedAt(); const remoteSiteAt = remoteData ? Number(remoteData.siteConfigUpdatedAt || 0) : 0; const needUpload = !remoteData || localSettingsAt > remoteSettingsAt || historyRemoteDiff || searchRemoteDiff || favoritesRemoteDiff || opMarksRemoteDiff || siteConfigRemoteDiff || (cfg.syncSiteConfig && getSiteConfigUpdatedAt() > remoteSiteAt); if (needUpload) { const payload = buildPayload(cfg, remoteData); await davPut(payload, cfg); uploaded = true; lastUploadAt = Date.now(); syncConfig.remoteUpdatedAt = payload.updatedAt; syncConfig.remoteDevice = payload.device; refreshHistorySnapshot(); } } syncConfig.lastSyncAt = Date.now(); saveSyncConfig(); refreshHistorySnapshot(); const notes = []; if (appliedRemoteSettings) notes.push('已应用云端设置'); if (uploaded) notes.push('已上传本地变更'); if (localHistoryChanged || localSearchChanged) notes.push('已合并云端历史'); if (localFavoritesChanged) notes.push('已合并云端收藏'); if (localOpMarksChanged) notes.push('已合并云端片头'); if (siteConfigChanged || siteConfigRemoteDiff) notes.push('已同步源配置'); setSyncState('ready', '上次同步 ' + formatSyncTime(syncConfig.lastSyncAt) + (notes.length ? ' · ' + notes.join(' · ') : '')); if (cfg.syncSiteConfig && siteConfigChanged) { if (sourceModal) { refreshSourceCatalog(false).then(function () { if (sourceModal) { sourceNotice = '云端自定义源配置已更新。'; renderSourceModal(); } }).catch(function () {}); } else if (!isPlayerPage()) { if (firstSync && !syncModal && !pickerOverlay) { setTimeout(function () { location.reload(); }, 500); } else if (!syncModal) { showSiteSyncNotice(); } else { siteSyncNoticePending = true; } } } return { uploaded: uploaded, appliedRemoteSettings: appliedRemoteSettings, restored: mode === 'restore' }; } catch (error) { setSyncState('error', error.message || '同步失败'); throw error; } finally { syncInFlight = false; if (syncQueued) { syncQueued = false; setTimeout(function () { runSync('auto').catch(function () {}); }, 1200); } } } async function testSyncConnection(cfg) { setSyncState('syncing', '正在测试连接...'); try { const remote = await davGet(cfg); if (remote.exists) { setSyncState('ready', '连接成功 · 云端已有文件(' + (remote.data.device || '未知设备') + ' · ' + formatSyncTime(remote.data.updatedAt) + ')'); } else { setSyncState('ready', '连接成功 · 云端还没有同步文件'); } return true; } catch (error) { setSyncState('error', error.message || '连接失败'); throw error; } } function scheduleSyncUpload(immediate) { if (!syncConfig.url || !syncConfig.autoSync) return; if (syncInFlight) { syncQueued = true; return; } if (syncUploadTimer) { if (!immediate) return; clearTimeout(syncUploadTimer); } const delay = immediate ? 900 : Math.max(3000, 60000 - (Date.now() - lastUploadAt)); syncUploadTimer = setTimeout(function () { syncUploadTimer = null; if (!immediate && Date.now() - lastUploadAt < 60000) { scheduleSyncUpload(false); return; } runSync('upload').catch(function () {}); }, delay); } function startSyncPolling() { if (syncPollTimer) clearInterval(syncPollTimer); refreshHistorySnapshot(); siteConfigSnapshot = getSiteConfigSignature(); syncPollTimer = setInterval(function () { if (!siteConfigApplying) { const siteSignature = getSiteConfigSignature(); if (siteSignature !== siteConfigSnapshot) { siteConfigSnapshot = siteSignature; setSiteConfigUpdatedAt(Date.now()); if (syncConfig.url && syncConfig.autoSync && syncConfig.syncSiteConfig) { scheduleSyncUpload(true); } } } if (!syncConfig.url) return; const signature = getHistorySignature(); if (signature !== historySnapshot) { historySnapshot = signature; if (syncConfig.autoSync) scheduleSyncUpload(false); } if (syncConfig.autoSync && !isPlayerPage() && Date.now() - syncConfig.lastSyncAt > 300000) { runSync('auto').catch(function () {}); } }, 10000); } function initSync() { installHistoryHooks(); if (syncConfig.url) { setSyncState('ready', syncConfig.lastSyncAt ? '上次同步 ' + formatSyncTime(syncConfig.lastSyncAt) : '已配置 WebDAV'); } else { setSyncState('off', '未配置 WebDAV'); } startSyncPolling(); if (typeof GM_registerMenuCommand === 'function') { try { GM_registerMenuCommand('WebDAV 云同步设置', openSyncModal); GM_registerMenuCommand('我的收藏与追剧提醒', openFavModal); } catch (e) { // 忽略菜单注册失败 } } window.addEventListener('storage', function (event) { if (event.key === SETTINGS_KEY) { settings = loadSettings(); if (toolbar) syncToolbar(); if (resultsEl) render(true); } if (event.key === HISTORY_KEY || event.key === SEARCH_HISTORY_KEY) { refreshHistorySnapshot(); } if (event.key === FAVORITES_KEY) { updateFavoriteIndicators(); refreshFavoriteButtons(); if (favModal) renderFavList(); refreshHistorySnapshot(); } }); document.addEventListener('visibilitychange', function () { if (!syncConfig.url || !syncConfig.autoSync) return; if (document.visibilityState === 'hidden') { const signature = getHistorySignature(); if (signature !== historySnapshot) { historySnapshot = signature; scheduleSyncUpload(true); } } else if (!isPlayerPage() && Date.now() - syncConfig.lastSyncAt > 300000) { runSync('auto').catch(function () {}); } }); if (syncConfig.url && syncConfig.autoSync && !isPlayerPage()) { setTimeout(function () { runSync('auto').catch(function () {}); }, 1500); } updateFavoriteIndicators(); maybeAutoCheckFavorites(); } function updateSyncIndicators() { document.querySelectorAll('#ltv-sync-btn, #ltv-home-sync-btn').forEach(function (button) { button.dataset.state = syncState; button.classList.toggle('is-on', !!(syncConfig.url && syncConfig.autoSync)); button.title = syncMessage || (syncConfig.url ? 'WebDAV 云同步' : '未配置 WebDAV'); }); if (!syncModal) return; const statusBox = syncModal.querySelector('#ltv-sync-status'); const statusMain = syncModal.querySelector('#ltv-sync-status-main'); const statusSub = syncModal.querySelector('#ltv-sync-status-sub'); if (!statusBox || !statusMain || !statusSub) return; statusBox.classList.toggle('is-error', syncState === 'error'); statusBox.classList.toggle('is-busy', syncState === 'syncing'); if (syncState === 'syncing') { statusMain.textContent = syncMessage || '同步中...'; } else if (syncState === 'error') { statusMain.textContent = '同步错误:' + (syncMessage || '未知错误'); } else if (syncState === 'ready') { statusMain.textContent = syncMessage || (syncConfig.url ? '已配置 WebDAV' : '未配置 WebDAV'); } else { statusMain.textContent = '未配置 WebDAV'; } if (!syncConfig.url) { statusSub.textContent = '填写目录地址后即可测试连接'; return; } const parts = []; if (syncConfig.lastSyncAt) parts.push('上次同步 ' + formatSyncTime(syncConfig.lastSyncAt)); if (syncConfig.remoteUpdatedAt) { parts.push('云端 ' + (syncConfig.remoteDevice || '未知设备') + ' · ' + formatSyncTime(syncConfig.remoteUpdatedAt)); } else { parts.push('云端暂无同步文件'); } if (syncConfig.autoSync) parts.push('自动同步已开启'); statusSub.textContent = parts.join(' · '); } function showSiteSyncNotice() { let notice = document.getElementById('ltv-site-sync-notice'); if (notice) notice.remove(); notice = document.createElement('div'); notice.id = 'ltv-site-sync-notice'; notice.className = 'ltv-site-sync-notice'; notice.innerHTML = [ '云端自定义源配置已更新', '', '' ].join(''); document.body.appendChild(notice); notice.addEventListener('click', function (event) { if (!event.target.closest) return; if (event.target.closest('[data-site-sync-refresh]')) { location.reload(); } else if (event.target.closest('[data-site-sync-close]')) { notice.remove(); } }); } function shouldShowHomeEntry() { return !isSearchPage() && !isPlayerPage(); } function removeHomeEntry() { const entry = document.getElementById(HOME_ENTRY_ID); if (entry) entry.remove(); } function ensureHomeEntry() { if (!shouldShowHomeEntry()) { removeHomeEntry(); return null; } let entry = document.getElementById(HOME_ENTRY_ID); if (entry) return entry; injectStyle(); entry = document.createElement('div'); entry.id = HOME_ENTRY_ID; entry.innerHTML = [ '', '', '' ].join(''); (document.body || document.documentElement).appendChild(entry); entry.querySelector('#ltv-home-fav-btn').addEventListener('click', openFavModal); entry.querySelector('#ltv-home-sync-btn').addEventListener('click', openSyncModal); entry.querySelector('#ltv-home-source-btn').addEventListener('click', function () { openSourceModal('test'); }); updateSyncIndicators(); updateFavoriteIndicators(); return entry; } function updateHomeEntry() { if (shouldShowHomeEntry()) ensureHomeEntry(); else removeHomeEntry(); } function closeSyncModal() { if (!syncModal) return; if (syncModal._ltvKeyHandler) { document.removeEventListener('keydown', syncModal._ltvKeyHandler); } syncModal.remove(); syncModal = null; if (siteSyncNoticePending) { siteSyncNoticePending = false; showSiteSyncNotice(); } } function fillSyncForm() { if (!syncModal) return; const setValue = function (name, value) { const input = syncModal.querySelector('[data-sync="' + name + '"]'); if (input) input.value = value || ''; }; const setChecked = function (name, value) { const input = syncModal.querySelector('[data-sync="' + name + '"]'); if (input) input.checked = !!value; }; setValue('url', syncConfig.url); setValue('username', syncConfig.username); setValue('password', syncConfig.password); setValue('device', syncConfig.device || detectDeviceName()); setChecked('auto', syncConfig.autoSync); setChecked('history', syncConfig.syncHistory); setChecked('searchHistory', syncConfig.syncSearchHistory); setChecked('siteConfig', syncConfig.syncSiteConfig); setChecked('favorites', syncConfig.syncFavorites); setChecked('opMarks', syncConfig.syncOpMarks); } function readSyncForm() { if (!syncModal) return Object.assign({}, syncConfig); const getValue = function (name) { const input = syncModal.querySelector('[data-sync="' + name + '"]'); return input ? input.value.trim() : ''; }; const getRawValue = function (name) { const input = syncModal.querySelector('[data-sync="' + name + '"]'); return input ? input.value : ''; }; const isChecked = function (name) { const input = syncModal.querySelector('[data-sync="' + name + '"]'); return !!(input && input.checked); }; return { url: getValue('url'), username: getValue('username'), password: getRawValue('password'), device: getValue('device') || detectDeviceName(), autoSync: isChecked('auto'), syncHistory: isChecked('history'), syncSearchHistory: isChecked('searchHistory'), syncSiteConfig: isChecked('siteConfig'), syncFavorites: isChecked('favorites'), syncOpMarks: isChecked('opMarks') }; } function persistSyncForm(form) { const previousUrl = normalizeDavUrl(syncConfig.url); const nextUrl = normalizeDavUrl(form.url); const credentialsChanged = previousUrl !== nextUrl || syncConfig.username !== form.username || syncConfig.password !== form.password; syncConfig.url = form.url; syncConfig.username = form.username; syncConfig.password = form.password; syncConfig.device = form.device; syncConfig.autoSync = !!form.autoSync; syncConfig.syncHistory = !!form.syncHistory; syncConfig.syncSearchHistory = !!form.syncSearchHistory; syncConfig.syncSiteConfig = !!form.syncSiteConfig; syncConfig.syncFavorites = !!form.syncFavorites; syncConfig.syncOpMarks = !!form.syncOpMarks; if (credentialsChanged) { syncConfig.lastSyncAt = 0; syncConfig.remoteUpdatedAt = 0; syncConfig.remoteDevice = ''; } saveSyncConfig(); updateSyncIndicators(); } function setSyncButtonsBusy(busy) { if (!syncModal) return; syncModal.querySelectorAll('[data-sync-action]').forEach(function (button) { button.disabled = busy; }); } function clearSyncConfig() { if (!confirmDialog('确定清除本机的 WebDAV 配置?云端同步文件不会被删除。')) return; syncConfig.url = ''; syncConfig.username = ''; syncConfig.password = ''; syncConfig.device = detectDeviceName(); syncConfig.autoSync = true; syncConfig.syncHistory = true; syncConfig.syncSearchHistory = true; syncConfig.syncSiteConfig = true; syncConfig.syncFavorites = true; syncConfig.syncOpMarks = true; syncConfig.lastSyncAt = 0; syncConfig.remoteUpdatedAt = 0; syncConfig.remoteDevice = ''; saveSyncConfig(); closeSyncModal(); setSyncState('off', '未配置 WebDAV'); } async function handleSyncAction(action) { if (!syncModal) return; if (action === 'save') { const form = readSyncForm(); if (form.url && !normalizeDavUrl(form.url)) { setSyncState('error', '请填写有效的 http(s) WebDAV 地址'); return; } persistSyncForm(form); closeSyncModal(); if (syncConfig.url && syncConfig.autoSync) { runSync(isPlayerPage() ? 'upload' : 'auto').catch(function () {}); } else { setSyncState(syncConfig.url ? 'ready' : 'off', syncConfig.url ? '已保存配置' : '未配置 WebDAV'); } return; } if (action === 'test') { const form = readSyncForm(); if (!form.url) { setSyncState('error', '请先填写 WebDAV 目录地址'); return; } if (!normalizeDavUrl(form.url)) { setSyncState('error', '请填写有效的 http(s) WebDAV 地址'); return; } persistSyncForm(form); setSyncButtonsBusy(true); try { await testSyncConnection(form); } catch (e) { // 状态已经由 setSyncState 更新 } finally { setSyncButtonsBusy(false); } return; } if (action === 'restore' || action === 'upload') { const form = readSyncForm(); if (!form.url) { setSyncState('error', '请先填写 WebDAV 目录地址'); return; } if (!normalizeDavUrl(form.url)) { setSyncState('error', '请填写有效的 http(s) WebDAV 地址'); return; } persistSyncForm(form); setSyncButtonsBusy(true); try { await runSync(action === 'restore' ? 'restore' : 'upload-force', form); } catch (e) { // 状态已经由 setSyncState 更新 } finally { setSyncButtonsBusy(false); } } } function openSyncModal() { if (!ensureSiteAccess()) return; injectStyle(); closeSourceModal(); closeSyncModal(); const overlay = document.createElement('div'); overlay.id = 'ltv-sync-overlay'; overlay.className = 'ltv-sync-overlay'; overlay.setAttribute('role', 'dialog'); overlay.setAttribute('aria-modal', 'true'); const panel = document.createElement('div'); panel.className = 'ltv-sync-panel'; panel.innerHTML = [ '
', '
', '
WebDAV 云同步
', '
脚本设置、观看进度、历史与自定义源,多设备共用
', '
', ' ', '
', '
', '
凭据只保存在本机 Tampermonkey 存储,不会写入云端同步文件。建议使用 HTTPS 地址。
', ' ', '
', ' ', ' ', '
', ' ', '
', ' ', ' ', ' ', ' ', ' ', ' ', '
', '
', '
未配置
', '
填写目录地址后即可测试连接
', '
', '
同步文件:libretv-sync.json(也可以直接填完整 .json 地址)', '
自定义源配置变更后,当前页面可能需要刷新才能生效。
', ' ', '
', '
', '
', ' ', ' ', ' ', ' ', '
' ].join(''); overlay.appendChild(panel); document.body.appendChild(overlay); syncModal = overlay; fillSyncForm(); overlay.addEventListener('click', function (event) { if (event.target === overlay) { closeSyncModal(); return; } const closeButton = event.target.closest('[data-sync-close]'); if (closeButton) { closeSyncModal(); return; } const clearButton = event.target.closest('[data-sync-clear]'); if (clearButton) { clearSyncConfig(); return; } const actionButton = event.target.closest('[data-sync-action]'); if (actionButton) { handleSyncAction(actionButton.dataset.syncAction); } }); const keyHandler = function (event) { if (event.key === 'Escape') { event.preventDefault(); closeSyncModal(); } }; document.addEventListener('keydown', keyHandler); overlay._ltvKeyHandler = keyHandler; updateSyncIndicators(); const urlInput = overlay.querySelector('[data-sync="url"]'); const isTouchDevice = /iPhone|iPad|iPod|Android|Mobile/i.test(navigator.userAgent) || navigator.maxTouchPoints > 1; if (urlInput && !isTouchDevice) { setTimeout(function () { urlInput.focus({ preventScroll: true }); }, 50); } } function escapeHtml(value) { return String(value == null ? '' : value).replace(/[&<>"']/g, function (ch) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch]; }); } function getSiteWindow() { try { if (typeof unsafeWindow !== 'undefined' && unsafeWindow) return unsafeWindow; } catch (e) { // 回退到沙箱窗口 } return window; } function siteAccessBlocked() { const win = getSiteWindow(); try { if (typeof win.isPasswordProtected !== 'function') return false; if (!win.isPasswordProtected()) return false; if (typeof win.isPasswordVerified !== 'function') return false; return !win.isPasswordVerified(); } catch (e) { return false; } } function ensureSiteAccess() { if (!siteAccessBlocked()) return true; try { const win = getSiteWindow(); if (typeof win.showPasswordModal === 'function') win.showPasswordModal(); } catch (e) { // 忽略密码弹窗调用失败 } return false; } function readCustomAPIs() { try { const store = getPageStorage(); const parsed = JSON.parse((store && store.getItem('customAPIs')) || '[]'); if (!Array.isArray(parsed)) return []; return parsed.map(function (item) { return { name: String((item && item.name) || ''), url: String((item && item.url) || ''), detail: String((item && item.detail) || ''), isAdult: !!(item && item.isAdult) }; }); } catch (e) { return []; } } function writeCustomAPIs(list) { try { const store = getPageStorage(); if (store) store.setItem('customAPIs', JSON.stringify(list || [])); } catch (e) { // 忽略存储失败 } } function readSelectedAPIs() { try { const store = getPageStorage(); const parsed = JSON.parse((store && store.getItem('selectedAPIs')) || '[]'); return Array.isArray(parsed) ? parsed.filter(function (item) { return typeof item === 'string'; }) : []; } catch (e) { return []; } } function writeSelectedAPIs(list) { try { const store = getPageStorage(); if (store) store.setItem('selectedAPIs', JSON.stringify(list || [])); } catch (e) { // 忽略存储失败 } } function normalizeSourceUrlKey(url) { return normalizeCustomUrl(url).toLowerCase(); } function getSiteConfigUpdatedAt() { try { const store = getPageStorage(); const value = store ? store.getItem(SITE_CONFIG_TIME_KEY) : null; return parseInt(value || '0', 10) || 0; } catch (e) { return 0; } } function setSiteConfigUpdatedAt(timestamp) { try { const store = getPageStorage(); if (store) store.setItem(SITE_CONFIG_TIME_KEY, String(timestamp || 0)); } catch (e) { // 忽略存储失败 } } function getSelectedCustomUrls() { const custom = readCustomAPIs(); const selected = readSelectedAPIs(); const urls = []; custom.forEach(function (item, index) { if (selected.indexOf('custom_' + index) < 0) return; const key = normalizeSourceUrlKey(item.url); if (key && urls.indexOf(key) < 0) urls.push(key); }); return urls; } function getSiteConfigSignature() { return stableStringify({ customAPIs: readCustomAPIs(), selectedUrls: getSelectedCustomUrls() }); } function readSiteConfigState() { const customAPIs = readCustomAPIs(); const selectedAPIs = readSelectedAPIs(); return { customAPIs: customAPIs, selectedAPIs: selectedAPIs, selectedUrls: getSelectedCustomUrls(), builtInSelected: selectedAPIs.filter(function (item) { return item.indexOf('custom_') !== 0; }) }; } function sourceKeyForItem(item, index) { return normalizeSourceUrlKey(item && item.url) || '__empty_' + index; } function normalizeSiteConfigPayload(payload) { const customAPIs = Array.isArray(payload && payload.customAPIs) ? payload.customAPIs.map(function (item) { return { name: String((item && item.name) || ''), url: String((item && item.url) || ''), detail: String((item && item.detail) || ''), isAdult: !!(item && item.isAdult) }; }) : []; const selectedUrls = Array.isArray(payload && payload.selectedUrls) ? payload.selectedUrls.map(function (item) { return normalizeSourceUrlKey(item); }).filter(Boolean) : []; return { customAPIs: customAPIs, selectedUrls: selectedUrls }; } function mergeSiteConfigs(localState, remoteState, remoteWins, unionDefinitions) { const localItems = (localState.customAPIs || []).map(function (item, index) { return { item: item, index: index, key: sourceKeyForItem(item, index) }; }); const remoteItems = (remoteState.customAPIs || []).map(function (item, index) { return { item: item, index: index, key: sourceKeyForItem(item, index) }; }); const localKeys = new Set(localItems.map(function (entry) { return entry.key; })); const remoteKeys = new Set(remoteItems.map(function (entry) { return entry.key; })); const localSelected = new Set(localState.selectedUrls || []); const remoteSelected = new Set(remoteState.selectedUrls || []); if (!unionDefinitions) { const winnerItems = remoteWins ? remoteItems : localItems; const winnerSelected = remoteWins ? remoteSelected : localSelected; const winnerMap = new Map(); const winnerOrder = []; winnerItems.forEach(function (entry) { if (!winnerMap.has(entry.key)) { winnerMap.set(entry.key, entry.item); winnerOrder.push(entry.key); } }); const winnerAPIs = winnerOrder.map(function (key) { return winnerMap.get(key); }); const selectedUrls = winnerOrder.filter(function (key) { return winnerSelected.has(key); }); const selectedAPIs = (localState.builtInSelected || []).slice(); winnerAPIs.forEach(function (item, index) { if (winnerSelected.has(sourceKeyForItem(item, index))) { selectedAPIs.push('custom_' + index); } }); return { customAPIs: winnerAPIs, selectedUrls: selectedUrls, selectedAPIs: selectedAPIs }; } const order = []; const map = new Map(); const primary = remoteWins ? remoteItems : localItems; const secondary = remoteWins ? localItems : remoteItems; primary.forEach(function (entry) { if (!map.has(entry.key)) { map.set(entry.key, entry.item); order.push(entry.key); } }); secondary.forEach(function (entry) { if (!map.has(entry.key)) { map.set(entry.key, entry.item); order.push(entry.key); } }); const selectedKeys = new Set(); order.forEach(function (key) { const inLocal = localKeys.has(key); const inRemote = remoteKeys.has(key); if (inLocal && inRemote) { if (remoteWins) { if (remoteSelected.has(key)) selectedKeys.add(key); } else if (localSelected.has(key)) { selectedKeys.add(key); } } else if (inLocal) { if (localSelected.has(key)) selectedKeys.add(key); } else if (inRemote) { if (remoteSelected.has(key)) selectedKeys.add(key); } }); const customAPIs = order.map(function (key) { return map.get(key); }); const selectedUrls = order.filter(function (key) { return selectedKeys.has(key); }); const selectedAPIs = (localState.builtInSelected || []).slice(); customAPIs.forEach(function (item, index) { if (selectedKeys.has(sourceKeyForItem(item, index))) { selectedAPIs.push('custom_' + index); } }); return { customAPIs: customAPIs, selectedUrls: selectedUrls, selectedAPIs: selectedAPIs }; } function sameSiteConfig(left, right) { return stableStringify({ customAPIs: left.customAPIs || [], selectedUrls: left.selectedUrls || [] }) === stableStringify({ customAPIs: right.customAPIs || [], selectedUrls: right.selectedUrls || [] }); } function applySiteConfigState(state, timestamp) { const current = readSiteConfigState(); const next = { customAPIs: state.customAPIs || [], selectedAPIs: state.selectedAPIs || [], selectedUrls: state.selectedUrls || [] }; if (sameSiteConfig(current, next)) { setSiteConfigUpdatedAt(timestamp); siteConfigSnapshot = getSiteConfigSignature(); syncAdultFilterState(); return false; } siteConfigApplying = true; try { writeCustomAPIs(next.customAPIs); writeSelectedAPIs(next.selectedAPIs); setSiteConfigUpdatedAt(timestamp); } finally { siteConfigApplying = false; } syncAdultFilterState(); siteConfigStale = true; siteConfigSnapshot = getSiteConfigSignature(); return true; } function touchSiteConfig() { setSiteConfigUpdatedAt(Date.now()); siteConfigSnapshot = getSiteConfigSignature(); if (syncConfig.url && syncConfig.autoSync && syncConfig.syncSiteConfig) { scheduleSyncUpload(true); } } function loadSourceKeyword() { try { const store = getPageStorage(); const value = store ? store.getItem(SOURCE_KEYWORD_KEY) : null; return (value || '').trim() || SOURCE_DEFAULT_KEYWORD; } catch (e) { return SOURCE_DEFAULT_KEYWORD; } } function saveSourceKeyword() { try { const store = getPageStorage(); if (store) store.setItem(SOURCE_KEYWORD_KEY, sourceKeyword || SOURCE_DEFAULT_KEYWORD); } catch (e) { // 忽略存储失败 } } function loadSourceShowAdult() { try { const store = getPageStorage(); return !!(store && store.getItem(SOURCE_SHOW_ADULT_KEY) === '1'); } catch (e) { return false; } } function saveSourceShowAdult() { try { const store = getPageStorage(); if (store) store.setItem(SOURCE_SHOW_ADULT_KEY, sourceShowAdult ? '1' : '0'); } catch (e) { // 忽略存储失败 } } function hasEnabledAdultSource() { const selected = readSelectedAPIs(); const custom = readCustomAPIs(); if (custom.some(function (item, index) { return item && item.isAdult && selected.indexOf('custom_' + index) >= 0; })) return true; const builtins = sourceCatalog.length ? sourceCatalog : (builtinSources || []); return builtins.some(function (item) { if (!item || !(item.isAdult || item.adult)) return false; return selected.indexOf(item.key) >= 0; }); } function syncAdultFilterState() { // 站点规则:勾选任意成人源时必须关闭黄色内容过滤,这里同步到站点存储 if (!hasEnabledAdultSource()) return; try { const store = getPageStorage(); if (store && store.getItem('yellowFilterEnabled') !== 'false') { store.setItem('yellowFilterEnabled', 'false'); } } catch (e) { // 忽略存储失败 } try { const win = getSiteWindow(); if (typeof win.checkAdultAPIsSelected === 'function') win.checkAdultAPIsSelected(); } catch (e) { // 站点设置面板不存在时忽略 } } function loadSourceTestCache() { try { const store = getPageStorage(); const parsed = JSON.parse((store && store.getItem(SOURCE_CACHE_KEY)) || '{}'); return parsed && typeof parsed === 'object' ? parsed : {}; } catch (e) { return {}; } } function saveSourceTestCache() { try { const store = getPageStorage(); if (!store) return; const now = Date.now(); const entries = Object.keys(sourceTestCache) .map(function (key) { return { key: key, value: sourceTestCache[key] }; }) .filter(function (item) { return item.value && now - (Number(item.value.time) || 0) < 24 * 60 * 60 * 1000; }) .sort(function (a, b) { return (Number(b.value.time) || 0) - (Number(a.value.time) || 0); }) .slice(0, 100); const pruned = {}; entries.forEach(function (item) { pruned[item.key] = item.value; }); sourceTestCache = pruned; store.setItem(SOURCE_CACHE_KEY, JSON.stringify(pruned)); } catch (e) { // 忽略存储失败 } } function extractApiSitesBlock(text) { const marker = text.indexOf('API_SITES'); if (marker < 0) return ''; const open = text.indexOf('{', marker); if (open < 0) return ''; let depth = 0; for (let i = open; i < text.length; i++) { const ch = text.charAt(i); if (ch === '{') depth++; else if (ch === '}') { depth--; if (depth === 0) return text.slice(open + 1, i); } } return ''; } function parseBuiltinSourcesFromText(text) { // 去掉整行注释,避免把 config.js 里注释掉的数据源也当成可用源;不要动 URL 里的 // const cleaned = String(text || '') .replace(/\/\*[\s\S]*?\*\//g, '') .split('\n') .filter(function (line) { return !/^\s*\/\//.test(line); }) .join('\n'); const block = extractApiSitesBlock(cleaned); const list = []; const entryPattern = /(\w+)\s*:\s*\{([^}]*)\}/g; let match; while ((match = entryPattern.exec(block))) { const key = match[1]; const body = match[2]; const apiMatch = body.match(/api\s*:\s*['"]([^'"]+)['"]/); const nameMatch = body.match(/name\s*:\s*['"]([^'"]+)['"]/); const detailMatch = body.match(/detail\s*:\s*['"]([^'"]+)['"]/); const adult = /adult\s*:\s*true/.test(body); if (!apiMatch || !nameMatch) continue; list.push({ key: key, name: nameMatch[1], url: apiMatch[1], detail: detailMatch ? detailMatch[1] : '', type: 'builtin', adult: adult }); } return list; } async function loadBuiltinSources() { if (builtinSources) return builtinSources; let text = ''; try { const response = await fetch('/js/config.js', { cache: 'no-store' }); if (response.ok) text = await response.text(); } catch (e) { // 配置读取失败时退回到页面里的复选框 } const fromConfig = text ? parseBuiltinSourcesFromText(text) : []; // 新版站点会把 customer_site.js 里的额外源合并进 window.API_SITES, // 直接读运行时对象可以拿到这些动态源的 API 地址 const fromRuntime = []; try { const live = getSiteWindow().API_SITES; if (live && typeof live === 'object') { Object.keys(live).forEach(function (key) { const item = live[key] || {}; if (!item.api) return; fromRuntime.push({ key: key, name: String(item.name || key), url: String(item.api || ''), detail: String(item.detail || ''), type: 'builtin', adult: !!item.adult }); }); } } catch (e) { // 旧版站点未暴露 API_SITES 时忽略 } const fromDom = []; document.querySelectorAll('#apiCheckboxes input[data-api]').forEach(function (input) { const key = input.dataset.api || ''; if (!key) return; const label = input.parentElement && input.parentElement.querySelector('label'); fromDom.push({ key: key, name: (label && label.textContent.trim()) || '', url: '', detail: '', type: 'builtin', adult: input.classList.contains('api-adult') }); }); const merged = new Map(); const mergeItem = function (item) { if (!item || !item.key) return; const current = merged.get(item.key); if (!current) { merged.set(item.key, item); return; } if (item.name) current.name = item.name; if (item.url) current.url = item.url; if (item.detail) current.detail = item.detail; if (item.adult) current.adult = true; }; fromConfig.forEach(mergeItem); fromRuntime.forEach(mergeItem); fromDom.forEach(function (item) { mergeItem(item); const current = merged.get(item.key); if (current && item.name) current.name = item.name; }); builtinSources = Array.from(merged.values()); return builtinSources; } async function refreshSourceCatalog(force) { if (force) builtinSources = null; const builtins = await loadBuiltinSources(); const custom = readCustomAPIs(); const selected = readSelectedAPIs(); const entries = []; builtins.forEach(function (item) { entries.push({ sid: 'b:' + item.key, key: item.key, type: 'builtin', name: item.name, url: item.url, detail: item.detail || '', index: -1, enabled: selected.indexOf(item.key) >= 0, isAdult: !!item.adult }); }); custom.forEach(function (item, index) { const key = 'custom_' + index; entries.push({ sid: 'c:' + index, key: key, type: 'custom', name: item.name, url: item.url, detail: item.detail || '', index: index, enabled: selected.indexOf(key) >= 0, isAdult: !!item.isAdult }); }); sourceCatalog = entries; return entries; } function sourceCacheKey(entry, keyword) { return entry.url + '|' + (keyword || sourceKeyword || SOURCE_DEFAULT_KEYWORD); } function getSourceCached(entry, keyword) { if (!entry || !entry.url) return null; const cache = sourceTestCache[sourceCacheKey(entry, keyword || sourceKeyword)]; if (!cache) return null; if (Date.now() - (Number(cache.time) || 0) > SOURCE_CACHE_TTL) return null; return cache; } function cacheSourceResult(entry, keyword, result) { sourceTestCache[sourceCacheKey(entry, keyword || sourceKeyword)] = Object.assign({ time: Date.now() }, result); saveSourceTestCache(); } function buildSourceTestUrl(base, keyword) { try { const url = new URL(base); url.searchParams.set('ac', 'videolist'); url.searchParams.set('wd', keyword || SOURCE_DEFAULT_KEYWORD); return url.toString(); } catch (e) { return ''; } } async function runTestRequest(entry, keyword) { const testUrl = buildSourceTestUrl(entry.url, keyword || sourceKeyword); if (!testUrl) { return { status: 'error', latency: 0, count: 0, message: '地址无效' }; } let proxyUrl = '/proxy/' + encodeURIComponent(testUrl); try { // 新版站点(libretv-elh)代理要求附带密码哈希鉴权 const win = getSiteWindow(); if (win.ProxyAuth && typeof win.ProxyAuth.addAuthToProxyUrl === 'function') { proxyUrl = await win.ProxyAuth.addAuthToProxyUrl(proxyUrl); } } catch (e) { // 旧版站点没有代理鉴权,保持原地址 } const startedAt = performance.now(); const controller = typeof AbortController === 'function' ? new AbortController() : null; let timer = null; if (controller) { timer = setTimeout(function () { controller.abort(); }, SOURCE_TEST_TIMEOUT); } try { const response = await fetch(proxyUrl, { headers: { 'Accept': 'application/json' }, cache: 'no-store', signal: controller ? controller.signal : undefined }); const latency = Math.round(performance.now() - startedAt); if (!response.ok) { return { status: 'error', latency: latency, count: 0, message: 'HTTP ' + response.status }; } const responseText = await response.text(); let data; try { data = JSON.parse(responseText); } catch (e) { return { status: 'error', latency: latency, count: 0, message: '返回不是 JSON' }; } const list = data && Array.isArray(data.list) ? data.list : []; if (!list.length) { return { status: 'empty', latency: latency, count: 0, message: '接口正常但没有结果' }; } return { status: 'ok', latency: latency, count: list.length, message: '' }; } catch (error) { const latency = Math.round(performance.now() - startedAt); const timeout = error && error.name === 'AbortError'; return { status: 'error', latency: latency, count: 0, message: timeout ? '超时' : '请求失败' }; } finally { // 超时要覆盖响应体读取阶段,避免响应头到达后一直卡住 if (timer) clearTimeout(timer); } } function shortSourceMessage(message) { const text = String(message || ''); return text.length > 24 ? text.slice(0, 24) + '...' : text; } function sourceStatusHtml(status, latency, count, message) { if (status === 'testing') { return '测试中'; } if (status === 'ok') { return '良好' + '' + latency + 'ms · ' + count + '条'; } if (status === 'empty') { return '空结果' + '' + latency + 'ms'; } if (status === 'error') { return '失败' + '' + escapeHtml(shortSourceMessage(message)) + ''; } return '未测'; } function updateSourceRow(entry, result) { if (!sourceModal || !entry) return; const row = sourceModal.querySelector('[data-src-id="' + entry.sid + '"]'); if (!row) return; const statusBox = row.querySelector('[data-src-status]'); if (!statusBox) return; let value = result; if (!value) { const cached = getSourceCached(entry); if (cached) { value = { status: cached.status, latency: cached.latency, count: cached.count, message: cached.message }; } } if (!value) value = { status: 'untested' }; statusBox.innerHTML = sourceStatusHtml(value.status, value.latency, value.count, value.message); } function updateCustomRowStatus(index, result) { if (!sourceModal) return; const row = sourceModal.querySelector('[data-custom-idx="' + index + '"]'); if (!row) return; const statusBox = row.querySelector('[data-custom-status]'); if (!statusBox) return; statusBox.innerHTML = result ? sourceStatusHtml(result.status, result.latency, result.count, result.message) : sourceStatusHtml('untested'); } function updateSourceSummary() { if (!sourceModal) return; const element = sourceModal.querySelector('#ltv-source-summary'); if (!element) return; const keyword = sourceKeyword || SOURCE_DEFAULT_KEYWORD; const enabled = sourceCatalog.filter(function (entry) { return entry.enabled; }).length; const adultTotal = sourceCatalog.filter(function (entry) { return entry.isAdult; }).length; const adultEnabled = sourceCatalog.filter(function (entry) { return entry.isAdult && entry.enabled; }).length; const normalTotal = sourceCatalog.filter(function (entry) { return !entry.isAdult; }).length; const normalEnabled = sourceCatalog.filter(function (entry) { return !entry.isAdult && entry.enabled; }).length; let ok = 0; let empty = 0; let failed = 0; let latencySum = 0; let latencyCount = 0; sourceCatalog.forEach(function (entry) { const cached = getSourceCached(entry, keyword); if (!cached) return; if (cached.status === 'ok') { ok++; latencySum += Number(cached.latency) || 0; latencyCount++; } else if (cached.status === 'empty') { empty++; latencySum += Number(cached.latency) || 0; latencyCount++; } else if (cached.status === 'error') { failed++; } }); const parts = [ '共 ' + sourceCatalog.length + ' 个源', '已启用 ' + enabled ]; if (normalTotal) parts.push('普通 ' + normalEnabled + '/' + normalTotal); if (adultTotal) parts.push('成人 ' + adultEnabled + '/' + adultTotal); parts.push('良好 ' + ok, '空结果 ' + empty, '失败 ' + failed); if (latencyCount) parts.push('平均 ' + Math.round(latencySum / latencyCount) + 'ms'); if (sourceTesting) parts.unshift('测试中'); element.textContent = parts.join(' · '); } function updateSourceButtons() { if (!sourceModal) return; sourceModal.querySelectorAll('[data-source-action="test-enabled"], [data-source-action="test-all"], [data-source-action="test-one"], [data-source-action="test-custom"]').forEach(function (button) { button.disabled = sourceTesting; }); const disableFailed = sourceModal.querySelector('[data-source-action="disable-failed"]'); if (disableFailed) { const keyword = sourceKeyword || SOURCE_DEFAULT_KEYWORD; const hasFailed = sourceCatalog.some(function (entry) { const cached = getSourceCached(entry, keyword); return entry.enabled && cached && cached.status === 'error'; }); disableFailed.disabled = sourceTesting || !hasFailed; } } async function runSourceTests(scope) { if (sourceTesting) return; let targets = sourceCatalog.filter(function (entry) { return entry.url; }); if (scope === 'enabled') targets = targets.filter(function (entry) { return entry.enabled; }); if (!targets.length) { if (sourceModal) { const summary = sourceModal.querySelector('#ltv-source-summary'); if (summary) summary.textContent = '没有可测试的数据源'; } return; } const keyword = sourceKeyword || SOURCE_DEFAULT_KEYWORD; sourceTesting = true; updateSourceButtons(); targets.forEach(function (entry) { updateSourceRow(entry, { status: 'testing', latency: 0, count: 0 }); }); updateSourceSummary(); const queue = targets.slice(); const workerCount = Math.min(4, queue.length); const workers = []; for (let i = 0; i < workerCount; i++) { workers.push((async function () { while (queue.length) { const entry = queue.shift(); const result = await runTestRequest(entry, keyword); cacheSourceResult(entry, keyword, result); updateSourceRow(entry, result); updateSourceSummary(); } })()); } try { await Promise.all(workers); } finally { // 即使某个请求异常也要恢复按钮状态 sourceTesting = false; updateSourceButtons(); updateSourceSummary(); } } async function testSingleSource(entry) { if (sourceTesting || !entry) return; const keyword = sourceKeyword || SOURCE_DEFAULT_KEYWORD; sourceTesting = true; updateSourceButtons(); updateSourceRow(entry, { status: 'testing', latency: 0, count: 0 }); if (entry.type === 'custom') updateCustomRowStatus(entry.index, { status: 'testing', latency: 0, count: 0 }); try { const result = await runTestRequest(entry, keyword); cacheSourceResult(entry, keyword, result); updateSourceRow(entry, result); if (entry.type === 'custom') updateCustomRowStatus(entry.index, result); } finally { sourceTesting = false; updateSourceButtons(); updateSourceSummary(); } } function siteHasSettingsForm() { return !!document.getElementById('addCustomApiForm') && !!document.getElementById('customApiName') && !!document.getElementById('customApiUrl'); } function siteCanManageCustom() { if (siteConfigStale) return false; const win = getSiteWindow(); return siteHasSettingsForm() && typeof win.addCustomApi === 'function' && typeof win.updateCustomApi === 'function' && typeof win.removeCustomApi === 'function'; } function siteCanToggleSelected() { return !siteConfigStale && typeof getSiteWindow().updateSelectedAPIs === 'function' && !!document.getElementById('apiCheckboxes'); } function setSiteCustomForm(api) { const nameInput = document.getElementById('customApiName'); const urlInput = document.getElementById('customApiUrl'); const detailInput = document.getElementById('customApiDetail'); const adultInput = document.getElementById('customApiIsAdult'); if (nameInput) nameInput.value = api.name || ''; if (urlInput) urlInput.value = api.url || ''; if (detailInput) detailInput.value = api.detail || ''; if (adultInput) adultInput.checked = !!api.isAdult; } function siteAddCustomSource(api) { if (!siteCanManageCustom()) return false; try { setSiteCustomForm(api); getSiteWindow().addCustomApi(); return true; } catch (e) { return false; } } function siteUpdateCustomSource(index, api) { if (siteConfigStale) return false; const win = getSiteWindow(); if (!siteHasSettingsForm() || typeof win.updateCustomApi !== 'function') return false; try { setSiteCustomForm(api); win.updateCustomApi(index); return true; } catch (e) { return false; } } function siteRemoveCustomSource(index) { if (siteConfigStale) return false; const win = getSiteWindow(); if (typeof win.removeCustomApi !== 'function') return false; try { win.removeCustomApi(index); return true; } catch (e) { return false; } } function storageToggleSource(entry, enabled) { let selected = readSelectedAPIs(); if (enabled) { if (selected.indexOf(entry.key) < 0) selected.push(entry.key); } else { selected = selected.filter(function (item) { return item !== entry.key; }); } writeSelectedAPIs(selected); } function siteToggleSource(entry, enabled) { if (siteConfigStale) return false; const win = getSiteWindow(); if (typeof win.updateSelectedAPIs !== 'function') return false; const input = entry.type === 'builtin' ? document.querySelector('#apiCheckboxes input[data-api="' + entry.key + '"]') : document.querySelector('#customApisList input[data-custom-index="' + entry.index + '"]'); if (!input) return false; const previous = input.checked; input.checked = !!enabled; try { win.updateSelectedAPIs(); return true; } catch (e) { input.checked = previous; return false; } } function setSourceEnabled(entry, enabled) { const usedSite = siteToggleSource(entry, enabled); if (!usedSite) { storageToggleSource(entry, enabled); sourceNotice = '已写入本地配置;当前页面刷新后生效。'; siteConfigStale = true; } const selected = readSelectedAPIs(); sourceCatalog.forEach(function (item) { item.enabled = selected.indexOf(item.key) >= 0; }); if (enabled && entry.isAdult) syncAdultFilterState(); if (entry.type === 'custom') touchSiteConfig(); return usedSite; } function setNormalSourcesEnabled(enabled) { const targets = sourceCatalog.filter(function (entry) { return !entry.isAdult; }); if (!targets.length) return 0; let usedSite = true; targets.forEach(function (entry) { if (!setSourceEnabled(entry, enabled)) usedSite = false; }); const selected = readSelectedAPIs(); sourceCatalog.forEach(function (item) { item.enabled = selected.indexOf(item.key) >= 0; }); sourceNotice = (enabled ? '已启用 ' : '已停用 ') + targets.length + ' 个普通源。' + (usedSite ? '' : '部分修改需刷新页面后生效。'); return targets.length; } function setAdultSourcesEnabled(enabled) { const targets = sourceCatalog.filter(function (entry) { return entry.isAdult; }); if (!targets.length) return 0; let usedSite = true; targets.forEach(function (entry) { if (!setSourceEnabled(entry, enabled)) usedSite = false; }); syncAdultFilterState(); const selected = readSelectedAPIs(); sourceCatalog.forEach(function (item) { item.enabled = selected.indexOf(item.key) >= 0; }); sourceNotice = (enabled ? '已启用 ' : '已停用 ') + targets.length + ' 个成人源。' + (enabled ? '站点黄色内容过滤已自动关闭。' : '黄色过滤保持关闭,可在站点设置里手动重新开启。') + (usedSite ? '' : ' 部分修改需刷新页面后生效。'); return targets.length; } function addCustomSource(api) { const list = readCustomAPIs(); if (list.length >= CUSTOM_API_MAX) { throw new Error('最多添加 ' + CUSTOM_API_MAX + ' 个自定义站点'); } if (siteAddCustomSource(api)) return { usedSite: true }; list.push(api); writeCustomAPIs(list); const selected = readSelectedAPIs(); selected.push('custom_' + (list.length - 1)); writeSelectedAPIs(selected); siteConfigStale = true; return { usedSite: false }; } function updateCustomSource(index, api) { if (siteUpdateCustomSource(index, api)) return { usedSite: true }; const list = readCustomAPIs(); if (index < 0 || index >= list.length) throw new Error('自定义站点不存在'); list[index] = api; writeCustomAPIs(list); siteConfigStale = true; return { usedSite: false }; } function removeCustomSource(index) { if (siteRemoveCustomSource(index)) return { usedSite: true }; const list = readCustomAPIs(); if (index < 0 || index >= list.length) throw new Error('自定义站点不存在'); list.splice(index, 1); writeCustomAPIs(list); const customApiId = 'custom_' + index; let selected = readSelectedAPIs().filter(function (item) { return item !== customApiId; }); selected = selected.map(function (item) { if (item.indexOf('custom_') === 0) { const currentIndex = parseInt(item.replace('custom_', ''), 10); if (currentIndex > index) return 'custom_' + (currentIndex - 1); } return item; }); writeSelectedAPIs(selected); siteConfigStale = true; return { usedSite: false }; } function closeSourceModal() { if (!sourceModal) return; if (sourceModal._ltvKeyHandler) { document.removeEventListener('keydown', sourceModal._ltvKeyHandler); } sourceModal.remove(); sourceModal = null; } async function openSourceModal(tab) { if (!ensureSiteAccess()) return; injectStyle(); closeSourceModal(); closeSyncModal(); sourceTab = tab === 'custom' ? 'custom' : 'test'; sourceFormMode = null; sourceEditIndex = -1; sourceFormStatus = null; sourceNotice = ''; if (!sourceKeyword) sourceKeyword = loadSourceKeyword(); if (!sourceTestCache || !Object.keys(sourceTestCache).length) { sourceTestCache = loadSourceTestCache(); } const overlay = document.createElement('div'); overlay.id = SOURCE_MODAL_ID; overlay.className = 'ltv-source-overlay'; overlay.setAttribute('role', 'dialog'); overlay.setAttribute('aria-modal', 'true'); const panel = document.createElement('div'); panel.className = 'ltv-sync-panel ltv-source-panel'; panel.innerHTML = [ '
', '
', '
数据源管理
', '
测速、启停和自定义站点
', '
', ' ', '
', '
', ' ', ' ', '
', '
', '
正在读取数据源...
', '
' ].join(''); overlay.appendChild(panel); document.body.appendChild(overlay); sourceModal = overlay; overlay.addEventListener('click', handleSourceModalClick); overlay.addEventListener('change', handleSourceModalChange); const keyHandler = function (event) { if (event.key === 'Escape') { event.preventDefault(); closeSourceModal(); return; } if (event.key === 'Enter' && event.target && event.target.matches && event.target.matches('[data-source-keyword]')) { event.target.blur(); } }; document.addEventListener('keydown', keyHandler); overlay._ltvKeyHandler = keyHandler; try { await refreshSourceCatalog(true); } catch (e) { if (!sourceModal) return; const body = sourceModal.querySelector('#ltv-source-body'); if (body) body.innerHTML = '
读取数据源失败:' + escapeHtml(e.message || '未知错误') + '
'; return; } if (!sourceModal) return; sourceNotice = (!siteCanToggleSelected() || !siteCanManageCustom()) ? '当前页面不能即时更新站点,修改会写入本地,刷新页面后生效。' : ''; renderSourceModal(); } function handleSourceModalClick(event) { if (!sourceModal) return; if (event.target === sourceModal) { closeSourceModal(); return; } const closeButton = event.target.closest('[data-source-close]'); if (closeButton) { closeSourceModal(); return; } const tabButton = event.target.closest('[data-source-tab]'); if (tabButton) { sourceTab = tabButton.dataset.sourceTab === 'custom' ? 'custom' : 'test'; renderSourceModal(); return; } const actionButton = event.target.closest('[data-source-action]'); if (!actionButton) return; event.preventDefault(); const action = actionButton.dataset.sourceAction; const sid = actionButton.dataset.srcId; const index = parseInt(actionButton.dataset.index, 10); if (action === 'test-enabled') { runSourceTests('enabled'); } else if (action === 'test-all') { runSourceTests('all'); } else if (action === 'disable-failed') { disableFailedSources(); } else if (action === 'test-one') { const entry = sourceCatalog.find(function (item) { return item.sid === sid; }); if (entry) testSingleSource(entry); } else if (action === 'add-form') { sourceTab = 'custom'; sourceFormMode = 'add'; sourceEditIndex = -1; sourceFormStatus = null; renderSourceModal(); } else if (action === 'edit') { sourceTab = 'custom'; sourceFormMode = 'edit'; sourceEditIndex = index; sourceFormStatus = null; renderSourceModal(); } else if (action === 'delete') { deleteCustomSource(index); } else if (action === 'cancel-form') { sourceFormMode = null; sourceEditIndex = -1; sourceFormStatus = null; renderSourceModal(); } else if (action === 'save-custom') { saveCustomFromForm(); } else if (action === 'test-form') { testCustomForm(); } else if (action === 'test-custom') { testCustomSourceRow(index); } } function handleSourceModalChange(event) { if (!sourceModal) return; const target = event.target; if (target.matches && target.matches('[data-source-keyword]')) { sourceKeyword = target.value.trim() || SOURCE_DEFAULT_KEYWORD; saveSourceKeyword(); renderSourceModal(); return; } if (target.matches && target.matches('[data-source-adult]')) { sourceShowAdult = !!target.checked; saveSourceShowAdult(); renderSourceModal(); return; } if (target.matches && target.matches('[data-source-normal-master]')) { setNormalSourcesEnabled(!!target.checked); updateSourceSummary(); updateSourceButtons(); renderSourceModal(); return; } if (target.matches && target.matches('[data-source-adult-master]')) { setAdultSourcesEnabled(!!target.checked); updateSourceSummary(); updateSourceButtons(); renderSourceModal(); return; } if (target.matches && target.matches('[data-src-toggle]')) { const entry = sourceCatalog.find(function (item) { return item.sid === target.dataset.srcId; }); if (!entry) return; const usedSite = setSourceEnabled(entry, target.checked); updateSourceSummary(); updateSourceButtons(); if (!usedSite || entry.isAdult) renderSourceModal(); } } function renderSourceModal() { if (!sourceModal) return; sourceModal.querySelectorAll('[data-source-tab]').forEach(function (button) { button.classList.toggle('is-active', button.dataset.sourceTab === sourceTab); }); const body = sourceModal.querySelector('#ltv-source-body'); if (!body) return; body.innerHTML = sourceTab === 'custom' ? renderCustomTab() : renderSourceTestTab(); if (sourceTab === 'test') updateSourceSummary(); updateSourceButtons(); } function renderSourceTestRow(entry) { const cached = getSourceCached(entry); const statusHtml = cached ? sourceStatusHtml(cached.status, cached.latency, cached.count, cached.message) : sourceStatusHtml('untested'); const typeLabel = entry.type === 'custom' ? '自定义' : '内置'; const urlText = entry.url || '未获取到地址'; const adultTag = entry.isAdult ? ' 18+' : ''; return [ '
', ' ', '
', '
' + escapeHtml(entry.name || entry.key) + ' ' + typeLabel + '' + adultTag + '
', '
' + escapeHtml(urlText) + '
', '
', '
', ' ' + statusHtml + '', ' ', '
', '
' ].join(''); } function renderSourceTestTab() { const adultCount = sourceCatalog.filter(function (entry) { return entry.isAdult; }).length; const enabledAdult = sourceCatalog.filter(function (entry) { return entry.isAdult && entry.enabled; }).length; const normalTotal = sourceCatalog.filter(function (entry) { return !entry.isAdult; }).length; const normalEnabled = sourceCatalog.filter(function (entry) { return !entry.isAdult && entry.enabled; }).length; const visible = sourceCatalog.filter(function (entry) { return sourceShowAdult || !entry.isAdult; }); const normalRows = visible .filter(function (entry) { return !entry.isAdult; }) .map(renderSourceTestRow) .join(''); const adultRows = sourceShowAdult && adultCount ? '
成人资源(18+)
' + visible.filter(function (entry) { return entry.isAdult; }).map(renderSourceTestRow).join('') : ''; const rows = sourceCatalog.length ? (normalRows + adultRows || '
成人源已隐藏,勾选“显示成人源”后查看。
') : '
没有读取到数据源。请确认站点设置已加载,或刷新页面后重试。
'; return [ sourceNotice ? '
' + escapeHtml(sourceNotice) + '
' : '', enabledAdult ? '
已启用 ' + enabledAdult + ' 个成人源:站点黄色内容过滤会自动关闭并被锁定。停用所有成人源后,可在站点设置里重新开启过滤。
' : '', '
', ' ', normalTotal ? ' ' : '', adultCount ? ' ' + ' ' : '', ' ', ' ', ' ', '
', '
', '
' + rows + '
', '
测速通过站点 /proxy/ 请求第一页;空结果只代表关键词没有命中,不代表源失效。测试结果缓存 30 分钟。成人源需在站点设置中配合关闭黄色过滤。
' ].join(''); } function renderCustomRow(item, index) { const entry = sourceCatalog.find(function (source) { return source.sid === 'c:' + index; }); const cached = entry ? getSourceCached(entry) : null; const statusHtml = cached ? sourceStatusHtml(cached.status, cached.latency, cached.count, cached.message) : sourceStatusHtml('untested'); const detailLine = item.detail ? '
detail: ' + escapeHtml(item.detail) + '
' : ''; return [ '
', ' ', '
', '
' + escapeHtml(item.name || '未命名') + ' 自定义' + (item.isAdult ? '18+' : '') + '' + statusHtml + '
', '
' + escapeHtml(item.url) + '
', detailLine, '
', '
', ' ', ' ', ' ', '
', '
' ].join(''); } function renderCustomForm(custom) { if (!sourceFormMode) return ''; let item = null; if (sourceFormMode === 'edit') { if (sourceEditIndex < 0 || sourceEditIndex >= custom.length) { sourceFormMode = null; return ''; } item = custom[sourceEditIndex]; } const name = item ? item.name : ''; const url = item ? item.url : ''; const detail = item ? item.detail : ''; const isAdult = !!(item && item.isAdult); const statusClass = sourceFormStatus ? ' is-' + sourceFormStatus.type : ''; const statusText = sourceFormStatus ? escapeHtml(sourceFormStatus.text) : ''; return [ '
', '
' + (sourceFormMode === 'edit' ? '编辑自定义站点' : '添加自定义站点') + '
', ' ', ' ', ' ', ' ', '
' + statusText + '
', '
', ' ', ' ', ' ', '
', '
' ].join(''); } function renderCustomTab() { const custom = readCustomAPIs(); const siteLive = siteCanManageCustom(); const notice = sourceNotice || (siteLive ? '' : '当前页面不能即时更新站点,修改会写入本地,刷新页面后生效。'); const rows = custom.length ? custom.map(renderCustomRow).join('') : '
还没有自定义站点
'; return [ notice ? '
' + escapeHtml(notice) + '
' : '', '
', '
已添加 ' + custom.length + ' / ' + CUSTOM_API_MAX + ' 个自定义站点
', ' ', '
', '
' + rows + '
', renderCustomForm(custom), '
自定义站点需为苹果CMS采集接口,通常以 /api.php/provide/vod 结尾。标记为成人资源(18+)的站点启用后会自动关闭站点的黄色内容过滤。' + (siteLive ? '保存后会立即写入站点设置并参与搜索。' : '') + '
' ].join(''); } function setCustomFormStatus(content, type, isHtml) { if (!sourceModal) return; const element = sourceModal.querySelector('#ltv-custom-form-status'); if (!element) return; element.className = 'ltv-form-status' + (type ? ' is-' + type : ''); if (isHtml) element.innerHTML = content; else element.textContent = content; } function readCustomForm() { if (!sourceModal) return { name: '', url: '', detail: '', adult: false }; const get = function (name) { const input = sourceModal.querySelector('[data-source-form="' + name + '"]'); return input ? input.value.trim() : ''; }; const adultInput = sourceModal.querySelector('[data-source-form="adult"]'); return { name: get('name'), url: get('url'), detail: get('detail'), adult: !!(adultInput && adultInput.checked) }; } function normalizeCustomUrl(value) { let url = String(value || '').trim(); if (url.endsWith('/')) url = url.slice(0, -1); return url; } async function saveCustomFromForm() { if (!sourceModal) return; const form = readCustomForm(); const name = form.name; const url = normalizeCustomUrl(form.url); const detail = normalizeCustomUrl(form.detail); if (!name || !url) { setCustomFormStatus('请输入名称和 API 地址', 'error'); return; } if (!/^https?:\/\/.+/.test(url)) { setCustomFormStatus('API 地址需以 http:// 或 https:// 开头', 'error'); return; } const custom = readCustomAPIs(); const duplicate = custom.some(function (item, index) { return index !== sourceEditIndex && normalizeCustomUrl(item.url).toLowerCase() === url.toLowerCase(); }); if (duplicate) { setCustomFormStatus('这个 API 地址已经添加过了', 'error'); return; } if (sourceFormMode === 'add' && custom.length >= CUSTOM_API_MAX) { setCustomFormStatus('最多添加 ' + CUSTOM_API_MAX + ' 个自定义站点', 'error'); return; } const api = { name: name, url: url, detail: detail, isAdult: !!form.adult }; setCustomFormStatus('正在保存...', 'busy'); try { const result = sourceFormMode === 'edit' ? updateCustomSource(sourceEditIndex, api) : addCustomSource(api); sourceNotice = result.usedSite ? '已保存并立即生效。' : '已写入本地配置;当前页面刷新后生效。'; sourceFormMode = null; sourceEditIndex = -1; sourceFormStatus = null; touchSiteConfig(); await refreshSourceCatalog(false); syncAdultFilterState(); renderSourceModal(); } catch (e) { setCustomFormStatus(e.message || '保存失败', 'error'); } } async function testCustomForm() { if (!sourceModal) return; const form = readCustomForm(); const url = normalizeCustomUrl(form.url); if (!url || !/^https?:\/\/.+/.test(url)) { setCustomFormStatus('请先填写有效的 API 地址', 'error'); return; } setCustomFormStatus('测试中...', 'busy'); const entry = { sid: 'form', key: 'form', type: 'custom', name: form.name || '自定义站点', url: url, detail: form.detail || '', index: -1, isAdult: !!form.adult }; const keyword = sourceKeyword || SOURCE_DEFAULT_KEYWORD; const result = await runTestRequest(entry, keyword); cacheSourceResult(entry, keyword, result); setCustomFormStatus(sourceStatusHtml(result.status, result.latency, result.count, result.message), '', true); } async function testCustomSourceRow(index) { let entry = sourceCatalog.find(function (item) { return item.type === 'custom' && item.index === index; }); if (!entry) { await refreshSourceCatalog(false); entry = sourceCatalog.find(function (item) { return item.type === 'custom' && item.index === index; }); } if (!entry) { updateCustomRowStatus(index, { status: 'error', latency: 0, count: 0, message: '源不存在' }); return; } await testSingleSource(entry); } async function deleteCustomSource(index) { const custom = readCustomAPIs(); const item = custom[index]; if (!item) return; if (!confirmDialog('确定删除自定义站点“' + (item.name || item.url) + '”?')) return; try { const result = removeCustomSource(index); sourceNotice = result.usedSite ? '已删除并立即生效。' : '已写入本地配置;当前页面刷新后生效。'; sourceFormMode = null; sourceEditIndex = -1; sourceFormStatus = null; touchSiteConfig(); await refreshSourceCatalog(false); renderSourceModal(); } catch (e) { sourceNotice = '删除失败:' + (e.message || '未知错误'); renderSourceModal(); } } async function disableFailedSources() { const keyword = sourceKeyword || SOURCE_DEFAULT_KEYWORD; const targets = sourceCatalog.filter(function (entry) { if (!entry.enabled || !entry.url) return false; const cached = getSourceCached(entry, keyword); return cached && cached.status === 'error'; }); if (!targets.length) return; if (!confirmDialog('确定停用 ' + targets.length + ' 个测速失败的源?')) return; let usedSite = true; targets.forEach(function (entry) { if (!setSourceEnabled(entry, false)) usedSite = false; }); sourceNotice = usedSite ? '已停用 ' + targets.length + ' 个失败源。' : '已写入本地配置;当前页面刷新后生效。'; await refreshSourceCatalog(false); renderSourceModal(); } function initSourceManager() { sourceKeyword = loadSourceKeyword(); sourceShowAdult = loadSourceShowAdult(); sourceTestCache = loadSourceTestCache(); if (typeof GM_registerMenuCommand === 'function') { try { GM_registerMenuCommand('数据源管理与测速', function () { openSourceModal('test'); }); } catch (e) { // 忽略菜单注册失败 } } } function safeDecode(value) { try { return decodeURIComponent(value); } catch (e) { return value; } } function getQuery() { const path = safeDecode(location.pathname || ''); if (path.indexOf('/s=') === 0) { return path.slice(3).trim(); } const params = new URLSearchParams(location.search || ''); return (params.get('q') || params.get('s') || params.get('keyword') || '').trim(); } function isSearchPage() { if (getQuery()) return true; return safeDecode(location.pathname || '').indexOf('/s=') === 0; } function kindFromWord(word) { if (/解说|速看|剪辑|混剪/.test(word)) return '解说'; if (/预告|花絮|幕后|特辑|彩蛋|片段/.test(word)) return '预告'; if (word === '短剧') return '短剧'; return '综艺'; } function cnToNumber(value) { const text = String(value || '').trim(); if (!text) return 0; if (/^\d+$/.test(text)) return parseInt(text, 10); const digits = { 零: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 }; if (text.indexOf('十') >= 0) { const parts = text.split('十'); const tens = parts[0] ? (digits[parts[0]] || 0) : 1; const ones = parts[1] ? (digits[parts[1]] || 0) : 0; return tens * 10 + ones; } let number = 0; for (const ch of text) { number = number * 10 + (digits[ch] || 0); } return number; } function normalizeTitle(raw, type, remarks) { let text = String(raw || '').trim(); let kind = ''; for (const word of NOISE_WORDS) { const forms = ['[' + word + ']', '【' + word + '】', '(' + word + ')', '(' + word + ')']; let hit = false; for (const form of forms) { if (text.indexOf(form) >= 0) { text = text.split(form).join(''); hit = true; } } if (hit) { kind = kindFromWord(word); } else if (text.endsWith(word)) { text = text.slice(0, -word.length); kind = kindFromWord(word); } } if (!kind) { const typeText = String(type || ''); const remarkText = String(remarks || ''); if (/解说|速看|剪辑|混剪/.test(typeText)) kind = '解说'; else if (/预告|花絮|特辑|彩蛋|片段/.test(typeText)) kind = '预告'; else if (/短剧/.test(typeText)) kind = '短剧'; else if (/综艺/.test(typeText)) kind = '综艺'; else if (/解说|速看|剪辑|混剪/.test(remarkText)) kind = '解说'; } for (const word of EXTRA_TAGS) { const forms = ['[' + word + ']', '【' + word + '】', '(' + word + ')', '(' + word + ')']; for (const form of forms) { if (text.indexOf(form) >= 0) text = text.split(form).join(''); } if (text.endsWith(word)) text = text.slice(0, -word.length); } // 去掉标题里的年份,避免同一部片因年份写法不同而分不到一组 text = text.replace(/[((]\s*(19|20)\d{2}\s*[))]/g, ''); text = text.replace(/[\[【]\s*(19|20)\d{2}\s*[\]】]/g, ''); text = text.replace(/\s+(19|20)\d{2}\s*$/, ''); // 季数归一化:第一季 -> S1,第二季 -> S2 const seasonStart = text.indexOf('第'); const seasonEnd = text.indexOf('季', seasonStart); if (seasonStart >= 0 && seasonEnd > seasonStart) { const number = cnToNumber(text.slice(seasonStart + 1, seasonEnd)); if (number > 0) { text = text.slice(0, seasonStart) + ' S' + number + text.slice(seasonEnd + 1); } } text = text.replace(/Season\s*(\d+)/gi, ' S$1'); for (const ch of [' ', ' ', ':', ':', '·', '-', '—', '_', ',', ',', '、', '.', '。', '!', '!', '?', '?', '/', '|', '《', '》', '“', '”', '‘', '’']) { text = text.split(ch).join(''); } return { norm: text.toLowerCase(), kind: kind }; } function relevanceRank(norm, queryNorm) { if (!queryNorm) return 0; if (!norm) return 3; if (norm === queryNorm) return 0; if (norm.indexOf(queryNorm) === 0) return 1; if (norm.indexOf(queryNorm) >= 0) return 2; return 3; } function parseShowDetailsArgs(attr) { const start = attr.indexOf('('); const end = attr.lastIndexOf(')'); if (start < 0 || end <= start) return []; const body = attr.slice(start + 1, end); const args = []; let current = ''; let quote = null; for (let i = 0; i < body.length; i++) { const ch = body[i]; if (quote) { if (ch === '\\') { current += body[++i] || ''; } else if (ch === quote) { quote = null; } else { current += ch; } } else if (ch === "'" || ch === '"') { quote = ch; } else if (ch === ',') { args.push(current); current = ''; } else { current += ch; } } args.push(current); return args.map(function (item) { return item.trim(); }); } function extractCardPoster(card) { const image = card.querySelector('.search-card-img-container img, img'); if (image) { const src = image.currentSrc || image.getAttribute('src') || image.dataset.src || ''; if (src) return src; } const container = card.querySelector('.search-card-img-container'); if (container) { const match = /url\(['"]?([^'")]+)/.exec(container.style.backgroundImage || ''); if (match) return match[1]; } return ''; } function parseCard(card) { // 首次出现顺序作为站点原始顺序,后续重排不能覆盖它 if (!originalIndexMap.has(card)) originalIndexMap.set(card, nextOriginalIndex++); const originalIndex = originalIndexMap.get(card); const onclick = card.getAttribute('onclick') || ''; const heading = card.querySelector('h3'); const headingText = heading ? heading.textContent.trim() : ''; // 搜索结果卡片内容基本不变,缓存解析结果,避免每次渲染都重复查询 DOM 和做标题归一化 const cached = parsedCardMap.get(card); if (cached && cached.onclick === onclick && cached.title === headingText) { return cached.parsed; } const args = parseShowDetailsArgs(onclick); const title = headingText || args[1] || ''; const id = args[0] || ''; const sourceCode = args[2] || ''; const tags = Array.from(card.querySelectorAll('.flex.flex-wrap span')) .map(function (node) { return node.textContent.trim(); }) .filter(Boolean); const year = tags.find(function (item) { return /^(19|20)\d{2}$/.test(item); }) || ''; const type = tags.find(function (item) { return item !== year; }) || ''; const remarks = (card.querySelector('p') ? card.querySelector('p').textContent : '').trim(); const sourceLabel = (card.querySelector('.border-t span') ? card.querySelector('.border-t span').textContent : '').trim() || sourceCode; const normalized = normalizeTitle(title, type, remarks); const episodeInfo = parseEpisodeInfo(remarks); const parsed = { card: card, index: originalIndex, id: id, title: title, sourceCode: sourceCode, sourceLabel: sourceLabel, type: type, year: year, remarks: remarks, poster: extractCardPoster(card), episode: episodeInfo.episode, finished: episodeInfo.finished, norm: normalized.norm, kind: normalized.kind, yearNum: year ? parseInt(year, 10) : 0, key: [normalized.norm, year || '?', normalized.kind].join('|'), hide: false }; parsedCardMap.set(card, { onclick: onclick, title: headingText, parsed: parsed }); return parsed; } function buildGroups(cards, queryNorm) { const map = new Map(); for (const card of cards) { if (!map.has(card.key)) map.set(card.key, []); map.get(card.key).push(card); } const groups = []; for (const entry of map) { const members = entry[1]; members.sort(function (a, b) { return a.index - b.index; }); // 优先用归一化标题最短的那条作为主卡片,标题更干净 const primary = members.slice().sort(function (a, b) { if (a.norm.length !== b.norm.length) return a.norm.length - b.norm.length; return a.index - b.index; })[0]; const sourceNames = new Set(members.map(function (item) { return item.sourceLabel || item.sourceCode; })); groups.push({ key: entry[0], members: members, primary: primary, title: primary.title, norm: primary.norm, kind: primary.kind, year: primary.year, yearNum: primary.yearNum, index: members[0].index, sourceCount: sourceNames.size, rank: relevanceRank(primary.norm, queryNorm), gid: '', hide: false }); } return groups; } function shouldHideKind(kind, query) { if (!kind) return false; if (kind === '解说' || kind === '预告') { if (!settings.filterNoise) return false; // 用户主动搜“解说/预告”时不隐藏 if (kind === '解说' && /解说|速看|剪辑|混剪/.test(query)) return false; if (kind === '预告' && /预告|花絮|特辑|彩蛋|片段/.test(query)) return false; return true; } if (kind === '短剧' || kind === '综艺') { if (!settings.filterVariety) return false; if (kind === '短剧' && /短剧/.test(query)) return false; if (kind === '综艺' && /综艺/.test(query)) return false; return true; } return false; } function applyState(groups, query) { let hiddenNoise = 0; let hiddenRelevant = 0; let hiddenDup = 0; let relevant = 0; let total = 0; for (const group of groups) { total += group.members.length; const noiseHidden = shouldHideKind(group.kind, query); const relevanceHidden = settings.onlyRelevant && group.rank > 2; const groupHidden = noiseHidden || relevanceHidden; group.hide = groupHidden; if (groupHidden) { for (const member of group.members) member.hide = true; if (noiseHidden) hiddenNoise += group.members.length; else hiddenRelevant += group.members.length; continue; } if (group.rank <= 2) relevant++; if (settings.dedupe) { for (const member of group.members) member.hide = member !== group.primary; const duplicates = group.members.length - 1; hiddenDup += duplicates; } else { for (const member of group.members) member.hide = false; } } return { total: total, groups: groups.length, relevant: relevant, merged: hiddenDup, hiddenNoise: hiddenNoise, hiddenRelevant: hiddenRelevant, hidden: hiddenNoise + hiddenRelevant }; } function orderGroups(groups) { const list = groups.slice(); list.sort(function (a, b) { if (settings.sort === 'relevance') { if (a.rank !== b.rank) return a.rank - b.rank; // 同为前缀匹配时,标题更短的更可能是正片而不是衍生短剧 if (a.rank > 0 && a.norm.length !== b.norm.length) { return a.norm.length - b.norm.length; } return a.index - b.index; } if (settings.sort === 'year') { const left = a.yearNum || -1; const right = b.yearNum || -1; if (left !== right) return right - left; if (a.rank !== b.rank) return a.rank - b.rank; return a.index - b.index; } if (settings.sort === 'title') { const compared = a.norm.localeCompare(b.norm, 'zh-CN'); if (compared) return compared; return a.index - b.index; } return a.index - b.index; }); return list; } function clearDecoration(card) { const deco = decorationMap.get(card); if (!deco) return; if (deco.badge) deco.badge.remove(); if (deco.switchButton) deco.switchButton.remove(); if (deco.favButton) deco.favButton.remove(); decorationMap.delete(card); } function ensureCardDecoration(card) { let deco = decorationMap.get(card); if (!deco) { deco = { badge: null, switchButton: null, favButton: null, stamp: 0 }; decorationMap.set(card, deco); } deco.stamp = renderStamp; decoratedCards.push(card); return deco; } function refreshFavoriteButton(deco, key, norm) { if (!deco || !deco.favButton) return; const favorite = renderFavoriteMap.get(key) || (norm ? renderFavoriteNormMap.get(norm) : null) || findFavorite(key); deco.favButton.dataset.ltvFavKey = key; deco.favButton.dataset.ltvFavNorm = norm || ''; deco.favButton.textContent = favorite ? '★' : '☆'; deco.favButton.classList.toggle('is-on', !!favorite); deco.favButton.classList.toggle('has-update', !!(favorite && favorite.hasUpdate)); deco.favButton.title = favorite ? (favorite.hasUpdate ? '有更新 · 点击取消收藏' : '已收藏 · 点击取消') : '加入收藏'; } function decorateGroup(group) { if (group.hide) return; const primary = group.primary; const card = primary.card; const merged = settings.dedupe && group.members.length > 1; const names = []; for (const member of group.members) { const name = member.sourceLabel || member.sourceCode; if (name && names.indexOf(name) < 0) names.push(name); } // 复用已创建的徽章、切换源和收藏按钮,避免每次渲染都先删除再重建 const deco = ensureCardDecoration(card); if (merged) { const badgeText = group.sourceCount > 1 ? group.sourceCount + ' 源' : group.members.length + ' 条'; if (!deco.badge) { const poster = card.querySelector('.search-card-img-container'); if (poster) { const badge = document.createElement('button'); badge.type = 'button'; badge.className = 'ltv-badge'; poster.appendChild(badge); deco.badge = badge; } } if (deco.badge) { deco.badge.dataset.ltvGroup = group.gid; deco.badge.textContent = badgeText; deco.badge.title = names.join(' / '); } if (!deco.switchButton) { const labelBox = card.querySelector('.border-t > div'); if (labelBox) { const switchButton = document.createElement('button'); switchButton.type = 'button'; switchButton.className = 'ltv-switch'; switchButton.textContent = '切换源'; labelBox.appendChild(switchButton); deco.switchButton = switchButton; } } if (deco.switchButton) deco.switchButton.dataset.ltvGroup = group.gid; } else { if (deco.badge) { deco.badge.remove(); deco.badge = null; } if (deco.switchButton) { deco.switchButton.remove(); deco.switchButton = null; } } if (!deco.favButton) { const poster = card.querySelector('.search-card-img-container'); const button = document.createElement('button'); button.type = 'button'; button.className = 'ltv-fav'; (poster || card).appendChild(button); deco.favButton = button; } refreshFavoriteButton(deco, primary.key, primary.norm); } function refreshFavoriteButtons() { const map = new Map(); const normMap = new Map(); readFavorites().forEach(function (item) { map.set(item.key, item); if (item.norm && !item.year && !normMap.has(item.norm)) normMap.set(item.norm, item); }); document.querySelectorAll('.ltv-fav').forEach(function (button) { const key = button.dataset.ltvFavKey; if (!key) return; const norm = button.dataset.ltvFavNorm || ''; const favorite = map.get(key) || (norm ? normMap.get(norm) : null); button.textContent = favorite ? '★' : '☆'; button.classList.toggle('is-on', !!favorite); button.classList.toggle('has-update', !!(favorite && favorite.hasUpdate)); button.title = favorite ? (favorite.hasUpdate ? '有更新 · 点击取消收藏' : '已收藏 · 点击取消') : '加入收藏'; }); } function supportsCssOrder() { if (orderSupported === null) { try { const display = window.getComputedStyle(resultsEl).display; orderSupported = display.indexOf('grid') >= 0 || display.indexOf('flex') >= 0; } catch (e) { orderSupported = false; } } return orderSupported; } function applyCardOrder(card, order) { const value = String(order); if (card.style.order !== value) card.style.order = value; } function reorderGroups(groups) { if (!resultsEl || !groups.length) return; // 网格/弹性容器用 CSS order 实现视觉重排,避免移动大量 DOM 节点触发重排卡顿 if (supportsCssOrder()) { let order = 0; for (const group of orderGroups(groups)) { applyCardOrder(group.primary.card, order++); for (const member of group.members) { if (member !== group.primary) applyCardOrder(member.card, order++); } } return; } const fragment = document.createDocumentFragment(); for (const group of orderGroups(groups)) { fragment.appendChild(group.primary.card); for (const member of group.members) { if (member !== group.primary) fragment.appendChild(member.card); } } resultsEl.appendChild(fragment); } function signatureOf(cards) { let signature = ''; for (const card of cards) { signature += [ card.index, card.id, card.title, card.sourceCode, card.sourceLabel, card.type, card.year, card.remarks ].join('\u0001') + '\u0002'; } return signature; } function syncToolbar() { if (!toolbar) return; toolbar.querySelectorAll('[data-ltv]').forEach(function (input) { const key = input.dataset.ltv; if (key === 'sort') input.value = settings.sort; else input.checked = !!settings[key]; }); } function ensureToolbar() { let existing = document.getElementById(TOOLBAR_ID); if (existing) { toolbar = existing; return existing; } if (!resultsEl || !resultsEl.parentElement) return null; const bar = document.createElement('div'); bar.id = TOOLBAR_ID; bar.innerHTML = [ '
', ' 搜索净化', ' 同片合并 · 相关结果优先', '
', ' ', ' ', ' ', '
', '
', '
', ' ', ' ', ' ', ' ', ' ', ' 等待结果...', '
' ].join(''); resultsEl.parentElement.insertBefore(bar, resultsEl); toolbar = bar; bar.addEventListener('change', onToolbarChange); const syncButton = bar.querySelector('#ltv-sync-btn'); if (syncButton) syncButton.addEventListener('click', openSyncModal); const favButton = bar.querySelector('#ltv-fav-btn'); if (favButton) favButton.addEventListener('click', openFavModal); const sourceButton = bar.querySelector('#ltv-source-btn'); if (sourceButton) { sourceButton.addEventListener('click', function () { openSourceModal('test'); }); } syncToolbar(); updateSyncIndicators(); updateFavoriteIndicators(); return bar; } function onToolbarChange(event) { const target = event.target; if (!target || !target.dataset || !target.dataset.ltv) return; const key = target.dataset.ltv; if (key === 'sort') { settings.sort = SORT_VALUES.indexOf(target.value) >= 0 ? target.value : 'relevance'; } else { settings[key] = !!target.checked; } saveSettings(); render(true); scheduleSyncUpload(true); } function updateStats(stats) { const element = document.getElementById(STATS_ID); if (!element) return; if (!stats || stats.total === 0) { element.textContent = '暂无结果'; return; } const parts = ['共 ' + stats.total + ' 条', stats.groups + ' 部']; if (stats.merged) parts.push('合并 ' + stats.merged + ' 条'); if (stats.relevant) parts.push('相关 ' + stats.relevant + ' 部'); if (stats.hidden) parts.push('隐藏 ' + stats.hidden + ' 条'); element.textContent = parts.join(' · '); } function closePicker() { const element = pickerOverlay || document.getElementById(OVERLAY_ID); if (!element) return; if (element._ltvKeyHandler) { document.removeEventListener('keydown', element._ltvKeyHandler); } element.remove(); pickerOverlay = null; } function openPicker(gid) { const group = groupMap.get(gid); if (!group) return; closePicker(); const overlay = document.createElement('div'); overlay.id = OVERLAY_ID; overlay.setAttribute('role', 'dialog'); overlay.setAttribute('aria-modal', 'true'); const panel = document.createElement('div'); panel.className = 'ltv-panel'; const head = document.createElement('div'); head.className = 'ltv-panel-head'; const headMain = document.createElement('div'); headMain.className = 'ltv-panel-head-main'; const title = document.createElement('div'); title.className = 'ltv-panel-title'; title.textContent = group.title; const sub = document.createElement('div'); sub.className = 'ltv-panel-sub'; sub.textContent = '共 ' + group.members.length + ' 条 · ' + group.sourceCount + ' 个源'; headMain.appendChild(title); headMain.appendChild(sub); const closeButton = document.createElement('button'); closeButton.type = 'button'; closeButton.className = 'ltv-panel-close'; closeButton.textContent = '×'; closeButton.setAttribute('aria-label', '关闭'); closeButton.addEventListener('click', closePicker); head.appendChild(headMain); head.appendChild(closeButton); const body = document.createElement('div'); body.className = 'ltv-panel-body'; for (const member of group.members) { const row = document.createElement('button'); row.type = 'button'; row.className = 'ltv-source-row'; const line = document.createElement('div'); line.className = 'ltv-source-line'; const name = document.createElement('span'); name.className = 'ltv-source-name'; name.textContent = member.sourceLabel || member.sourceCode || '未知来源'; line.appendChild(name); if (member === group.primary) { const current = document.createElement('span'); current.className = 'ltv-source-current'; current.textContent = '首选'; line.appendChild(current); } const meta = document.createElement('div'); meta.className = 'ltv-source-meta'; meta.textContent = [member.type, member.year, member.remarks] .filter(Boolean) .join(' · ') || '无简介'; row.appendChild(line); row.appendChild(meta); row.addEventListener('click', function () { closePicker(); member.card.click(); }); body.appendChild(row); } const foot = document.createElement('div'); foot.className = 'ltv-panel-foot'; foot.textContent = '点击来源会打开该片的详情页'; panel.appendChild(head); panel.appendChild(body); panel.appendChild(foot); overlay.appendChild(panel); document.body.appendChild(overlay); overlay.addEventListener('click', function (event) { if (event.target === overlay) closePicker(); }); const keyHandler = function (event) { if (event.key === 'Escape') { event.preventDefault(); closePicker(); } }; document.addEventListener('keydown', keyHandler); overlay._ltvKeyHandler = keyHandler; pickerOverlay = overlay; closeButton.focus({ preventScroll: true }); } function onResultsClickCapture(event) { const target = event.target; if (!target || !target.closest) return; const favTrigger = target.closest('.ltv-fav'); if (favTrigger && resultsEl && resultsEl.contains(favTrigger)) { event.preventDefault(); event.stopPropagation(); toggleFavoriteByKey(favTrigger.dataset.ltvFavKey); return; } const trigger = target.closest('.ltv-badge, .ltv-switch'); if (!trigger || !resultsEl || !resultsEl.contains(trigger)) return; const gid = trigger.dataset.ltvGroup; if (!gid) return; event.preventDefault(); event.stopPropagation(); openPicker(gid); } function favoriteFromCard(card, now) { return { key: card.key, title: card.title, norm: card.norm, kind: card.kind, year: card.year, type: card.type, remarks: card.remarks, poster: card.poster, episode: card.episode, finished: card.finished, latestEpisode: card.episode, latestFinished: card.finished, latestRemarks: card.remarks, hasUpdate: false, follow: true, sourceCode: card.sourceCode, id: card.id, addedAt: now, updatedAt: now, checkedAt: 0 }; } function detectFavoriteUpdate(favorite, card, now) { let changed = false; if (card.episode > (favorite.latestEpisode || 0)) { favorite.latestEpisode = card.episode; favorite.latestRemarks = card.remarks; changed = true; } if (card.finished && !favorite.latestFinished) { favorite.latestFinished = true; if (card.remarks) favorite.latestRemarks = card.remarks; changed = true; } if (!favorite.latestRemarks && card.remarks) { favorite.latestRemarks = card.remarks; changed = true; } if ((favorite.latestEpisode || 0) > (favorite.episode || 0) || (favorite.latestFinished && !favorite.finished)) { if (!favorite.hasUpdate) { favorite.hasUpdate = true; changed = true; } } if (changed) favorite.updatedAt = now; return changed; } function syncFavoritesFromCards(cards) { if (!cards || !cards.length) return; const list = readFavorites(); if (!list.length) return; const map = new Map(list.map(function (item) { return [item.key, item]; })); const now = Date.now(); let changed = false; cards.forEach(function (card) { const favorite = map.get(card.key); if (favorite && detectFavoriteUpdate(favorite, card, now)) changed = true; }); if (!changed) return; writeFavorites(list); updateFavoriteIndicators(); refreshFavoriteButtons(); if (favModal) renderFavList(); scheduleFavoriteUpload(); } function toggleFavoriteByKey(key) { if (!key) return; const card = parsedCards.find(function (item) { return item.key === key; }); if (!card) return; const list = readFavorites(); let index = list.findIndex(function (item) { return item.key === key; }); if (index < 0 && card.norm) { index = list.findIndex(function (item) { return item.norm === card.norm && !item.year; }); } if (index >= 0) { const removedKey = list[index].key; list.splice(index, 1); writeFavorites(list); recordFavoriteDeletion(removedKey); } else { const now = Date.now(); const entry = favoriteFromCard(card, now); // 同一分组里其他来源可能已经更新到更多集,收藏时以当前已知最大集数为基线 parsedCards.forEach(function (item) { if (item.key !== key) return; if (item.episode > entry.episode) { entry.episode = item.episode; entry.latestEpisode = item.episode; entry.latestRemarks = item.remarks; } if (item.finished) { entry.finished = true; entry.latestFinished = true; } }); list.unshift(entry); writeFavorites(list); scheduleFavoriteUpload(); } updateFavoriteIndicators(); refreshFavoriteButtons(); if (favModal) renderFavList(); } function updateFavoriteIndicators() { const stats = favoriteStats(); document.querySelectorAll('#ltv-fav-btn, #ltv-home-fav-btn').forEach(function (button) { const label = button.querySelector('.ltv-fav-label'); const text = stats.count ? '收藏 ' + stats.count + (stats.updates ? ' · ' + stats.updates + '新' : '') : '收藏'; if (label) label.textContent = text; else button.textContent = text; button.classList.toggle('has-update', stats.updates > 0); button.title = stats.updates ? stats.updates + ' 部收藏有更新' : (stats.count ? '共 ' + stats.count + ' 部收藏' : '我的收藏'); }); } function setFavStatus(message) { const element = document.getElementById('ltv-fav-status'); if (element) element.textContent = message || ''; } function setFavButtonsBusy(busy) { if (!favModal) return; favModal.querySelectorAll('[data-fav-action]').forEach(function (button) { button.disabled = !!busy; }); } function closeFavModal() { const overlay = favModal || document.getElementById('ltv-fav-overlay'); if (!overlay) return; if (overlay._ltvKeyHandler) document.removeEventListener('keydown', overlay._ltvKeyHandler); overlay.remove(); favModal = null; } function buildFavRow(favorite) { const row = document.createElement('div'); row.className = 'ltv-fav-row'; const cover = document.createElement('div'); cover.className = 'ltv-fav-cover'; if (favorite.poster) { cover.style.backgroundImage = 'url("' + favorite.poster.replace(/"/g, '%22') + '")'; } const main = document.createElement('div'); main.className = 'ltv-fav-main'; const title = document.createElement('div'); title.className = 'ltv-fav-title'; title.textContent = favorite.title; main.appendChild(title); const tags = document.createElement('div'); tags.className = 'ltv-fav-tags'; if (favorite.hasUpdate) { const updateTag = document.createElement('span'); updateTag.className = 'ltv-fav-tag update'; updateTag.textContent = '有更新'; tags.appendChild(updateTag); } const stateTag = document.createElement('span'); stateTag.className = 'ltv-fav-tag'; stateTag.textContent = (favorite.finished || favorite.latestFinished) ? '已完结' : '追更中'; tags.appendChild(stateTag); if (favorite.year) { const yearTag = document.createElement('span'); yearTag.className = 'ltv-fav-tag'; yearTag.textContent = favorite.year; tags.appendChild(yearTag); } if (favorite.type) { const typeTag = document.createElement('span'); typeTag.className = 'ltv-fav-tag'; typeTag.textContent = favorite.type; tags.appendChild(typeTag); } main.appendChild(tags); const meta = document.createElement('div'); meta.className = 'ltv-fav-meta'; const metaParts = []; if (favorite.latestRemarks) metaParts.push(favorite.latestRemarks); if (favorite.latestEpisode > favorite.episode) { metaParts.push('收藏时 ' + (favorite.episode ? '第 ' + favorite.episode + ' 集' : favorite.remarks || '未知')); } metaParts.push('收藏 ' + formatSyncTime(favorite.addedAt)); if (favorite.checkedAt) metaParts.push('检查 ' + formatSyncTime(favorite.checkedAt)); meta.textContent = metaParts.filter(Boolean).join(' · '); main.appendChild(meta); const ops = document.createElement('div'); ops.className = 'ltv-fav-ops'; const openButton = document.createElement('button'); openButton.type = 'button'; openButton.className = 'ltv-fav-op'; openButton.dataset.favRowAction = 'open'; openButton.dataset.favKey = favorite.key; openButton.textContent = '打开'; ops.appendChild(openButton); if (favorite.hasUpdate) { const readButton = document.createElement('button'); readButton.type = 'button'; readButton.className = 'ltv-fav-op'; readButton.dataset.favRowAction = 'read'; readButton.dataset.favKey = favorite.key; readButton.textContent = '标记已看'; ops.appendChild(readButton); } const removeButton = document.createElement('button'); removeButton.type = 'button'; removeButton.className = 'ltv-fav-op danger'; removeButton.dataset.favRowAction = 'remove'; removeButton.dataset.favKey = favorite.key; removeButton.textContent = '移除'; ops.appendChild(removeButton); main.appendChild(ops); row.appendChild(cover); row.appendChild(main); return row; } function renderFavList() { const body = document.getElementById('ltv-fav-list'); if (!body) return; const list = readFavorites(); const stats = favoriteStats(); const sub = document.getElementById('ltv-fav-sub'); if (sub) { sub.textContent = list.length ? '共 ' + list.length + ' 部' + (stats.updates ? ' · ' + stats.updates + ' 部有更新' : ' · 暂无更新') : '收藏喜欢的片,有更新会在这里提醒'; } body.innerHTML = ''; if (!list.length) { const empty = document.createElement('div'); empty.className = 'ltv-fav-empty'; empty.textContent = '还没有收藏。在搜索结果卡片左上角点 ☆ 即可收藏。'; body.appendChild(empty); return; } list.forEach(function (favorite) { body.appendChild(buildFavRow(favorite)); }); } function openFavModal() { if (!ensureSiteAccess()) return; injectStyle(); closeSyncModal(); closeSourceModal(); closePicker(); closeFavModal(); const overlay = document.createElement('div'); overlay.id = 'ltv-fav-overlay'; overlay.className = 'ltv-sync-overlay'; overlay.setAttribute('role', 'dialog'); overlay.setAttribute('aria-modal', 'true'); const panel = document.createElement('div'); panel.className = 'ltv-sync-panel ltv-fav-panel'; panel.innerHTML = [ '
', '
', '
我的收藏
', '
收藏喜欢的片,有更新会在这里提醒
', '
', ' ', '
', '
', '', '
', '
', ' ', ' ', ' ', '
' ].join(''); overlay.appendChild(panel); document.body.appendChild(overlay); favModal = overlay; const autoInput = overlay.querySelector('[data-fav-auto]'); if (autoInput) { try { const store = getPageStorage(); autoInput.checked = !store || store.getItem(FAV_AUTO_CHECK_KEY) !== '0'; } catch (e) { autoInput.checked = true; } } renderFavList(); overlay.addEventListener('click', function (event) { if (event.target === overlay) { closeFavModal(); return; } if (event.target.closest('[data-fav-close]')) { closeFavModal(); return; } const autoToggle = event.target.closest('[data-fav-auto]'); if (autoToggle) { try { const store = getPageStorage(); if (store) store.setItem(FAV_AUTO_CHECK_KEY, autoToggle.checked ? '1' : '0'); } catch (e) { // 忽略存储失败 } return; } const action = event.target.closest('[data-fav-action]'); if (action) { handleFavAction(action.dataset.favAction); return; } const rowAction = event.target.closest('[data-fav-row-action]'); if (rowAction) { const key = rowAction.dataset.favKey; if (rowAction.dataset.favRowAction === 'open') openFavoriteByKey(key); else if (rowAction.dataset.favRowAction === 'remove') removeFavoriteByKey(key); else if (rowAction.dataset.favRowAction === 'read') markFavoriteRead(key); } }); const keyHandler = function (event) { if (event.key === 'Escape') { event.preventDefault(); closeFavModal(); } }; document.addEventListener('keydown', keyHandler); overlay._ltvKeyHandler = keyHandler; } function handleFavAction(action) { if (action === 'check') { checkFavoriteUpdates(false); return; } if (action === 'clear') { if (!readFavorites().length) { setFavStatus('还没有收藏'); return; } if (!confirmDialog('确定清空全部收藏?云端同步后其他设备也会清空。')) return; writeFavorites([]); recordFavoriteClear(); updateFavoriteIndicators(); refreshFavoriteButtons(); renderFavList(); setFavStatus('已清空收藏'); } } function openFavoriteByKey(key) { const favorite = findFavorite(key); if (!favorite) return; const win = getSiteWindow(); if (favorite.id && favorite.sourceCode && typeof win.showDetails === 'function') { closeFavModal(); win.showDetails(favorite.id, favorite.title, favorite.sourceCode); return; } setFavStatus('这条收藏缺少片源信息,请到搜索页重新搜索:' + favorite.title); } function removeFavoriteByKey(key) { const list = readFavorites(); const index = list.findIndex(function (item) { return item.key === key; }); if (index < 0) return; const removed = list[index]; list.splice(index, 1); writeFavorites(list); recordFavoriteDeletion(key); updateFavoriteIndicators(); refreshFavoriteButtons(); renderFavList(); setFavStatus('已移除「' + removed.title + '」'); } function markFavoriteRead(key) { const list = readFavorites(); const favorite = list.find(function (item) { return item.key === key; }); if (!favorite) return; favorite.episode = Math.max(favorite.episode || 0, favorite.latestEpisode || 0); favorite.finished = favorite.finished || favorite.latestFinished; favorite.hasUpdate = false; favorite.updatedAt = Date.now(); writeFavorites(list); updateFavoriteIndicators(); refreshFavoriteButtons(); renderFavList(); scheduleFavoriteUpload(); setFavStatus('已把「' + favorite.title + '」标记为已看,有新集会再次提醒'); } async function fetchSourceListFor(entry, keyword) { const requestUrl = buildSourceTestUrl(entry.url, keyword); if (!requestUrl) return []; let proxyUrl = '/proxy/' + encodeURIComponent(requestUrl); try { const win = getSiteWindow(); if (win.ProxyAuth && typeof win.ProxyAuth.addAuthToProxyUrl === 'function') { proxyUrl = await win.ProxyAuth.addAuthToProxyUrl(proxyUrl); } } catch (e) { // 旧版站点没有代理鉴权 } const controller = typeof AbortController === 'function' ? new AbortController() : null; const timer = controller ? setTimeout(function () { controller.abort(); }, FAV_CHECK_TIMEOUT) : null; try { const response = await fetch(proxyUrl, { headers: { 'Accept': 'application/json' }, cache: 'no-store', signal: controller ? controller.signal : undefined }); if (!response.ok) return []; const text = await response.text(); const data = JSON.parse(text); return data && Array.isArray(data.list) ? data.list : []; } catch (e) { return []; } finally { if (timer) clearTimeout(timer); } } function matchFavoriteInItems(favorite, items) { let best = null; for (const item of items || []) { const title = String(item.vod_name || '').trim(); if (!title) continue; const remarks = String(item.vod_remarks || '').trim(); const normalized = normalizeTitle(title, String(item.type_name || ''), remarks); let matched = normalized.norm === favorite.norm; if (!matched && favorite.norm && normalized.norm.indexOf(favorite.norm) === 0 && normalized.norm.length - favorite.norm.length <= 6) { matched = true; } if (!matched) continue; const info = parseEpisodeInfo(remarks); if (!best || info.episode > best.episode || (info.finished && !best.finished)) { best = { episode: info.episode, finished: info.finished, remarks: remarks }; } } return best; } async function checkFavoriteUpdates(silent) { if (favChecking) return; const list = readFavorites(); if (!list.length) { if (!silent) setFavStatus('还没有收藏'); return; } favChecking = true; if (!silent) { setFavStatus('正在加载数据源...'); setFavButtonsBusy(true); } try { await refreshSourceCatalog(true); const sources = sourceCatalog .filter(function (item) { return item.enabled && item.url; }) .slice(0, FAV_CHECK_SOURCE_LIMIT); if (!sources.length) { if (!silent) setFavStatus('没有已启用的数据源,请先在源管理中启用'); return; } const targets = list .filter(function (item) { return item.follow !== false; }) .slice(0, FAV_CHECK_FAVORITE_LIMIT); const startedAt = Date.now(); let checked = 0; for (let index = 0; index < targets.length; index++) { if (Date.now() - startedAt > FAV_CHECK_TOTAL_TIMEOUT) break; const favorite = targets[index]; if (!silent) { setFavStatus('正在检查 ' + (index + 1) + '/' + targets.length + ':' + favorite.title); } const results = await Promise.all(sources.map(async function (source) { const items = await fetchSourceListFor(source, favorite.title); return matchFavoriteInItems(favorite, items); })); let best = null; results.forEach(function (match) { if (!match) return; if (!best || match.episode > best.episode || (match.finished && !best.finished)) { best = match; } }); const now = Date.now(); favorite.checkedAt = now; let changed = false; if (best) { if (best.episode > (favorite.latestEpisode || 0)) { favorite.latestEpisode = best.episode; changed = true; } if (best.remarks && best.remarks !== favorite.latestRemarks) { favorite.latestRemarks = best.remarks; changed = true; } if (best.finished && !favorite.latestFinished) { favorite.latestFinished = true; changed = true; } } if ((favorite.latestEpisode || 0) > (favorite.episode || 0) || (favorite.latestFinished && !favorite.finished)) { if (!favorite.hasUpdate) { favorite.hasUpdate = true; changed = true; } } if (changed) favorite.updatedAt = now; checked++; writeFavorites(list); if (!silent && favModal) renderFavList(); } updateFavoriteIndicators(); refreshFavoriteButtons(); if (favModal) renderFavList(); scheduleFavoriteUpload(); if (!silent) { const stats = favoriteStats(); setFavStatus('检查完成:已检查 ' + checked + ' 部,共 ' + stats.updates + ' 部有更新'); } } finally { favChecking = false; setFavButtonsBusy(false); } } function maybeAutoCheckFavorites() { try { const store = getPageStorage(); if (!store) return; if (store.getItem(FAV_AUTO_CHECK_KEY) === '0') return; if (isPlayerPage()) return; const lastAt = parseInt(store.getItem(FAV_AUTO_CHECK_KEY + '_at') || '0', 10) || 0; if (Date.now() - lastAt < FAV_CHECK_INTERVAL) return; const list = readFavorites(); if (!list.length) return; store.setItem(FAV_AUTO_CHECK_KEY + '_at', String(Date.now())); setTimeout(function () { checkFavoriteUpdates(true).catch(function () {}); }, 8000); } catch (e) { // 忽略自动检查失败 } } function bindResults() { if (!resultsEl || boundResultsEl === resultsEl) return; if (boundResultsEl) { boundResultsEl.removeEventListener('click', onResultsClickCapture, true); } resultsEl.addEventListener('click', onResultsClickCapture, true); boundResultsEl = resultsEl; } function scheduleRender() { if (renderTimer) return; // 结果很多时适当拉长合并间隔,减少重复整理次数 const count = resultsEl && resultsEl.children ? resultsEl.children.length : 0; const delay = count > 1200 ? 450 : (count > 600 ? 260 : 120); renderTimer = setTimeout(function () { renderTimer = null; render(false); }, delay); } function render(force) { if (renderTimer) { clearTimeout(renderTimer); renderTimer = null; } if (!resultsEl || !resultsEl.isConnected) return; const rawCards = Array.from(resultsEl.children).filter(function (child) { return child.classList && child.classList.contains('card-hover'); }); const cards = rawCards.map(function (card) { return parseCard(card); }); parsedCards = cards; const signature = signatureOf(cards); const settingsKey = JSON.stringify(settings); if (!force && signature === lastSignature && settingsKey === lastSettingsKey) { if (!document.getElementById(TOOLBAR_ID)) ensureToolbar(); return; } lastSignature = signature; lastSettingsKey = settingsKey; if (observer) observer.disconnect(); try { ensureToolbar(); syncToolbar(); const query = getQuery(); const queryNorm = normalizeTitle(query, '', '').norm; const groups = buildGroups(cards, queryNorm); groups.forEach(function (group, index) { group.gid = 'g' + index; }); groupMap = new Map(groups.map(function (group) { return [group.gid, group]; })); renderStamp++; const previousDecorated = decoratedCards; decoratedCards = []; renderFavoriteMap = new Map(readFavorites().map(function (item) { return [item.key, item]; })); renderFavoriteNormMap = new Map(); renderFavoriteMap.forEach(function (item) { if (item.norm && !item.year && !renderFavoriteNormMap.has(item.norm)) { renderFavoriteNormMap.set(item.norm, item); } }); const stats = applyState(groups, query); for (const card of cards) { const shouldHide = !!card.hide; if (card.card.classList.contains(HIDDEN_CLASS) !== shouldHide) { card.card.classList.toggle(HIDDEN_CLASS, shouldHide); } } for (const group of groups) decorateGroup(group); // 搜索结果里出现收藏的片时,顺手检查集数是否有变化 syncFavoritesFromCards(cards); updateFavoriteIndicators(); // 清理本次不再需要装饰的卡片(例如关闭去重或分组被隐藏) previousDecorated.forEach(function (card) { const deco = decorationMap.get(card); if (deco && deco.stamp !== renderStamp) clearDecoration(card); }); reorderGroups(groups); updateStats(stats); } finally { if (observer && resultsEl) { observer.observe(resultsEl, { childList: true }); } } } function injectStyle() { if (document.getElementById(STYLE_ID)) return; const style = document.createElement('style'); style.id = STYLE_ID; style.textContent = [ '#ltv-cleaner-toolbar {', ' --ltv-accent: #00ccff;', ' margin: 0 0 12px;', ' padding: 10px 12px;', ' background: #101010;', ' border: 1px solid #2a2a2a;', ' border-radius: 10px;', ' color: #d1d5db;', ' font-size: 12px;', ' line-height: 1.5;', ' font-family: inherit;', '}', '#ltv-cleaner-toolbar .ltv-bar-head {', ' display: flex;', ' align-items: center;', ' gap: 8px;', ' flex-wrap: wrap;', ' margin-bottom: 8px;', '}', '#ltv-cleaner-toolbar .ltv-brand {', ' color: #fff;', ' font-size: 13px;', ' font-weight: 600;', '}', '#ltv-cleaner-toolbar .ltv-hint {', ' color: #9ca3af;', ' font-size: 11px;', '}', '#ltv-cleaner-toolbar .ltv-bar-controls {', ' display: flex;', ' align-items: center;', ' gap: 10px 14px;', ' flex-wrap: wrap;', '}', '#ltv-cleaner-toolbar label {', ' display: inline-flex;', ' align-items: center;', ' gap: 5px;', ' white-space: nowrap;', ' cursor: pointer;', ' user-select: none;', '}', '#ltv-cleaner-toolbar input[type="checkbox"] {', ' width: 14px;', ' height: 14px;', ' margin: 0;', ' accent-color: var(--ltv-accent);', ' cursor: pointer;', '}', '#ltv-cleaner-toolbar select {', ' padding: 3px 6px;', ' background: #0b0b0b;', ' border: 1px solid #333;', ' border-radius: 6px;', ' color: #e5e7eb;', ' font-size: 12px;', ' outline: none;', '}', '#ltv-cleaner-toolbar .ltv-stats {', ' margin-left: auto;', ' color: #9ca3af;', ' font-size: 12px;', '}', '@media (max-width: 640px) {', ' #ltv-cleaner-toolbar .ltv-stats { margin-left: 0; flex-basis: 100%; }', '}', '.ltv-cleaner-hidden { display: none !important; }', '.ltv-badge {', ' position: absolute;', ' top: 6px;', ' right: 6px;', ' z-index: 6;', ' display: inline-flex;', ' align-items: center;', ' justify-content: center;', ' min-width: 34px;', ' height: 20px;', ' padding: 0 8px;', ' background: rgba(0, 0, 0, .78);', ' border: 1px solid rgba(0, 204, 255, .45);', ' border-radius: 999px;', ' color: #00ccff;', ' font-size: 11px;', ' line-height: 1;', ' cursor: pointer;', '}', '.ltv-badge:hover { background: rgba(0, 204, 255, .18); }', '.ltv-fav {', ' position: absolute;', ' top: 6px;', ' left: 6px;', ' z-index: 6;', ' display: inline-flex;', ' align-items: center;', ' justify-content: center;', ' width: 24px;', ' height: 24px;', ' padding: 0;', ' background: rgba(0, 0, 0, .72);', ' border: 1px solid rgba(255, 255, 255, .18);', ' border-radius: 50%;', ' color: #d1d5db;', ' font-size: 14px;', ' line-height: 1;', ' cursor: pointer;', '}', '.ltv-fav:hover { color: #fbbf24; border-color: rgba(251, 191, 36, .5); }', '.ltv-fav.is-on { color: #fbbf24; border-color: rgba(251, 191, 36, .55); background: rgba(0, 0, 0, .82); }', '.ltv-fav.has-update::after {', ' content: "";', ' position: absolute;', ' top: -1px;', ' right: -1px;', ' width: 7px;', ' height: 7px;', ' border-radius: 50%;', ' background: #f472b6;', ' box-shadow: 0 0 0 1px #000;', '}', '.ltv-switch {', ' margin-left: 6px;', ' padding: 0;', ' background: none;', ' border: 0;', ' color: #00ccff;', ' font-size: 11px;', ' cursor: pointer;', ' text-decoration: underline;', ' text-underline-offset: 2px;', '}', '#ltv-cleaner-overlay {', ' position: fixed;', ' inset: 0;', ' z-index: 10000;', ' display: flex;', ' align-items: center;', ' justify-content: center;', ' padding: 16px;', ' background: rgba(0, 0, 0, .72);', '}', '#ltv-cleaner-overlay .ltv-panel {', ' display: flex;', ' flex-direction: column;', ' width: min(460px, 94vw);', ' max-height: 72vh;', ' overflow: hidden;', ' background: #141414;', ' border: 1px solid #333;', ' border-radius: 12px;', ' box-shadow: 0 16px 48px rgba(0, 0, 0, .55);', ' color: #e5e7eb;', ' font-size: 13px;', ' font-family: inherit;', '}', '#ltv-cleaner-overlay .ltv-panel-head {', ' display: flex;', ' align-items: flex-start;', ' gap: 10px;', ' padding: 14px 16px;', ' border-bottom: 1px solid #262626;', '}', '#ltv-cleaner-overlay .ltv-panel-head-main { flex: 1; min-width: 0; }', '#ltv-cleaner-overlay .ltv-panel-title {', ' color: #fff;', ' font-size: 15px;', ' font-weight: 600;', ' line-height: 1.4;', ' word-break: break-word;', '}', '#ltv-cleaner-overlay .ltv-panel-sub {', ' margin-top: 3px;', ' color: #9ca3af;', ' font-size: 11px;', '}', '#ltv-cleaner-overlay .ltv-panel-close {', ' flex: none;', ' width: 28px;', ' height: 28px;', ' background: #1a1a1a;', ' border: 1px solid #333;', ' border-radius: 8px;', ' color: #d1d5db;', ' font-size: 16px;', ' line-height: 1;', ' cursor: pointer;', '}', '#ltv-cleaner-overlay .ltv-panel-close:hover { background: #262626; }', '#ltv-cleaner-overlay .ltv-panel-body { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 4px 0 8px; }', '#ltv-cleaner-overlay .ltv-source-row {', ' display: block;', ' width: 100%;', ' padding: 10px 16px;', ' background: none;', ' border: 0;', ' border-bottom: 1px solid #222;', ' color: #e5e7eb;', ' font: inherit;', ' text-align: left;', ' cursor: pointer;', '}', '#ltv-cleaner-overlay .ltv-source-row:hover { background: #1c1c1c; }', '#ltv-cleaner-overlay .ltv-source-row:last-child { border-bottom: 0; }', '#ltv-cleaner-overlay .ltv-source-line { display: flex; align-items: center; gap: 8px; }', '#ltv-cleaner-overlay .ltv-source-name { color: #fff; font-weight: 600; }', '#ltv-cleaner-overlay .ltv-source-current {', ' padding: 1px 6px;', ' background: rgba(0, 204, 255, .12);', ' border: 1px solid rgba(0, 204, 255, .35);', ' border-radius: 999px;', ' color: #00ccff;', ' font-size: 10px;', '}', '#ltv-cleaner-overlay .ltv-source-meta {', ' margin-top: 3px;', ' color: #9ca3af;', ' font-size: 11px;', ' line-height: 1.45;', ' word-break: break-word;', '}', '#ltv-cleaner-overlay .ltv-panel-foot {', ' padding: 8px 16px;', ' border-top: 1px solid #262626;', ' color: #6b7280;', ' font-size: 10px;', '}', '@media (max-width: 640px) {', ' #ltv-cleaner-overlay { align-items: flex-end; padding: 0; }', ' #ltv-cleaner-overlay .ltv-panel {', ' width: 100%;', ' max-height: 80vh;', ' max-height: 85dvh;', ' border-radius: 14px 14px 0 0;', ' border-left: 0;', ' border-right: 0;', ' border-bottom: 0;', ' padding-bottom: env(safe-area-inset-bottom);', ' }', '}', '#ltv-cleaner-toolbar .ltv-head-actions {', ' margin-left: auto;', ' display: flex;', ' align-items: center;', ' gap: 6px;', ' flex-wrap: wrap;', '}', '#ltv-cleaner-toolbar .ltv-sync-btn,', '#ltv-cleaner-toolbar .ltv-source-btn,', '#ltv-cleaner-toolbar .ltv-fav-btn {', ' display: inline-flex;', ' align-items: center;', ' gap: 5px;', ' min-height: 26px;', ' padding: 2px 9px;', ' background: #0b0b0b;', ' border: 1px solid #333;', ' border-radius: 999px;', ' color: #d1d5db;', ' font-size: 11px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '#ltv-cleaner-toolbar .ltv-sync-btn:hover,', '#ltv-cleaner-toolbar .ltv-source-btn:hover,', '#ltv-cleaner-toolbar .ltv-fav-btn:hover { border-color: #00ccff; color: #fff; }', '#ltv-cleaner-toolbar .ltv-fav-btn .ltv-fav-icon { color: #fbbf24; font-size: 12px; line-height: 1; }', '#ltv-cleaner-toolbar .ltv-fav-btn.has-update {', ' border-color: rgba(244, 114, 182, .55);', ' color: #fbcfe8;', '}', '#ltv-cleaner-toolbar .ltv-fav-btn.has-update .ltv-fav-icon { color: #f472b6; }', '#ltv-cleaner-toolbar .ltv-sync-btn.is-on { border-color: rgba(0, 204, 255, .45); }', '.ltv-sync-dot {', ' width: 7px;', ' height: 7px;', ' border-radius: 50%;', ' background: #6b7280;', ' flex: none;', '}', '#ltv-cleaner-toolbar .ltv-sync-btn[data-state="ready"] .ltv-sync-dot { background: #00ccff; }', '#ltv-cleaner-toolbar .ltv-sync-btn[data-state="syncing"] .ltv-sync-dot { background: #f59e0b; }', '#ltv-cleaner-toolbar .ltv-sync-btn[data-state="error"] .ltv-sync-dot { background: #ef4444; }', '#ltv-sync-overlay {', ' position: fixed;', ' inset: 0;', ' z-index: 10001;', ' display: flex;', ' align-items: center;', ' justify-content: center;', ' padding: 16px;', ' background: rgba(0, 0, 0, .76);', '}', '.ltv-sync-panel {', ' display: flex;', ' flex-direction: column;', ' width: min(520px, 96vw);', ' max-height: 86vh;', ' max-height: 90dvh;', ' overflow: hidden;', ' background: #141414;', ' border: 1px solid #333;', ' border-radius: 12px;', ' box-shadow: 0 16px 48px rgba(0, 0, 0, .55);', ' color: #e5e7eb;', ' font-size: 13px;', ' font-family: inherit;', '}', '.ltv-sync-head {', ' display: flex;', ' align-items: flex-start;', ' gap: 10px;', ' padding: 14px 16px;', ' border-bottom: 1px solid #262626;', '}', '.ltv-sync-head-main { flex: 1; min-width: 0; }', '.ltv-sync-title { color: #fff; font-size: 16px; font-weight: 600; line-height: 1.4; }', '.ltv-sync-sub { margin-top: 3px; color: #9ca3af; font-size: 11px; line-height: 1.5; }', '.ltv-sync-head .ltv-panel-close {', ' flex: none;', ' width: 30px;', ' height: 30px;', ' background: #1a1a1a;', ' border: 1px solid #333;', ' border-radius: 8px;', ' color: #d1d5db;', ' font-size: 17px;', ' line-height: 1;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-sync-head .ltv-panel-close:hover { background: #262626; }', '.ltv-sync-body {', ' display: flex;', ' flex: 1 1 auto;', ' flex-direction: column;', ' gap: 12px;', ' min-height: 0;', ' padding: 14px 16px;', ' overflow: auto;', '}', '.ltv-sync-note {', ' padding: 8px 10px;', ' background: rgba(0, 204, 255, .06);', ' border: 1px solid rgba(0, 204, 255, .22);', ' border-radius: 8px;', ' color: #a5f3fc;', ' font-size: 11px;', ' line-height: 1.55;', '}', '.ltv-field { display: flex; flex-direction: column; gap: 5px; min-width: 0; }', '.ltv-field > span { color: #9ca3af; font-size: 11px; }', '.ltv-field input {', ' width: 100%;', ' box-sizing: border-box;', ' min-height: 36px;', ' padding: 7px 10px;', ' background: #0b0b0b;', ' border: 1px solid #333;', ' border-radius: 8px;', ' color: #e5e7eb;', ' font-size: 13px;', ' font-family: inherit;', ' outline: none;', '}', '.ltv-field input:focus { border-color: #00ccff; }', '.ltv-field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }', '.ltv-sync-toggles { display: flex; flex-wrap: wrap; gap: 8px 14px; padding: 2px 0; }', '.ltv-sync-toggles label {', ' display: inline-flex;', ' align-items: center;', ' gap: 6px;', ' color: #d1d5db;', ' cursor: pointer;', ' font-size: 12px;', ' touch-action: manipulation;', '}', '.ltv-sync-toggles input { width: 15px; height: 15px; margin: 0; accent-color: #00ccff; }', '.ltv-sync-status-box {', ' padding: 10px 12px;', ' background: #0e0e0e;', ' border: 1px solid #2a2a2a;', ' border-radius: 8px;', '}', '.ltv-sync-status-main { color: #e5e7eb; font-size: 13px; line-height: 1.5; word-break: break-word; }', '.ltv-sync-status-sub { margin-top: 3px; color: #9ca3af; font-size: 11px; line-height: 1.5; word-break: break-word; }', '.ltv-sync-status-box.is-error { border-color: rgba(239, 68, 68, .55); }', '.ltv-sync-status-box.is-error .ltv-sync-status-main { color: #fca5a5; }', '.ltv-sync-status-box.is-busy { border-color: rgba(245, 158, 11, .5); }', '.ltv-sync-file { color: #6b7280; font-size: 11px; line-height: 1.6; }', '.ltv-sync-file code { color: #9ca3af; }', '.ltv-sync-clear {', ' margin-left: 6px;', ' padding: 0;', ' background: none;', ' border: 0;', ' color: #9ca3af;', ' font-size: 11px;', ' text-decoration: underline;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-sync-actions {', ' display: grid;', ' grid-template-columns: repeat(4, 1fr);', ' gap: 8px;', ' padding: 12px 16px;', ' border-top: 1px solid #262626;', ' background: #141414;', '}', '.ltv-sync-actions button {', ' min-height: 38px;', ' border-radius: 8px;', ' font-size: 12px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-sync-btn-secondary { background: #1a1a1a; border: 1px solid #333; color: #d1d5db; }', '.ltv-sync-btn-secondary:hover { background: #262626; }', '.ltv-sync-btn-primary { background: #00a3cc; border: 1px solid #00a3cc; color: #001318; font-weight: 600; }', '.ltv-sync-btn-primary:hover { background: #00bde8; }', '.ltv-sync-actions button:disabled { opacity: .55; cursor: wait; }', '@media (max-width: 820px) {', ' .ltv-field-row { grid-template-columns: 1fr; }', ' .ltv-sync-actions { grid-template-columns: 1fr 1fr; }', '}', '@media (max-width: 640px) {', ' #ltv-cleaner-toolbar .ltv-sync-btn,', ' #ltv-cleaner-toolbar .ltv-source-btn { min-height: 30px; padding: 2px 10px; }', ' #ltv-sync-overlay { align-items: flex-end; padding: 0; }', ' .ltv-sync-panel {', ' width: 100%;', ' max-height: 90vh;', ' max-height: 90dvh;', ' border-radius: 14px 14px 0 0;', ' border-left: 0;', ' border-right: 0;', ' border-bottom: 0;', ' }', ' .ltv-sync-head { padding: 14px 16px 10px; }', ' .ltv-sync-body { padding: 12px 16px; gap: 10px; }', ' .ltv-field input { min-height: 42px; font-size: 16px; }', ' .ltv-sync-toggles { flex-direction: column; gap: 8px; }', ' .ltv-sync-toggles label { min-height: 32px; font-size: 13px; }', ' .ltv-sync-actions { padding: 10px 16px calc(10px + env(safe-area-inset-bottom)); }', ' .ltv-sync-actions button { min-height: 44px; font-size: 13px; }', ' #ltv-cleaner-toolbar { padding: 10px; font-size: 13px; }', ' #ltv-cleaner-toolbar .ltv-bar-controls { gap: 8px 12px; }', ' #ltv-cleaner-toolbar label { min-height: 32px; font-size: 13px; }', ' #ltv-cleaner-toolbar input[type="checkbox"] { width: 16px; height: 16px; }', ' #ltv-cleaner-toolbar select { min-height: 36px; font-size: 13px; }', ' .ltv-badge { height: 24px; min-height: 24px; padding: 0 8px; }', ' .ltv-switch { min-height: 28px; font-size: 12px; }', '}', '#ltv-source-overlay {', ' position: fixed;', ' inset: 0;', ' z-index: 10002;', ' display: flex;', ' align-items: center;', ' justify-content: center;', ' padding: 16px;', ' background: rgba(0, 0, 0, .76);', '}', '.ltv-source-panel { width: min(680px, 96vw); }', '.ltv-source-tabs {', ' display: flex;', ' gap: 4px;', ' padding: 8px 16px 0;', ' background: #141414;', ' border-bottom: 1px solid #262626;', '}', '.ltv-source-tab {', ' padding: 8px 10px;', ' background: none;', ' border: 0;', ' border-bottom: 2px solid transparent;', ' color: #9ca3af;', ' font-size: 12px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-source-tab.is-active { color: #00ccff; border-bottom-color: #00ccff; }', '.ltv-source-body {', ' flex: 1 1 auto;', ' min-height: 0;', ' overflow: auto;', ' padding: 12px 16px 16px;', '}', '.ltv-source-notice {', ' margin-bottom: 10px;', ' padding: 8px 10px;', ' background: rgba(245, 158, 11, .08);', ' border: 1px solid rgba(245, 158, 11, .3);', ' border-radius: 8px;', ' color: #fcd34d;', ' font-size: 11px;', ' line-height: 1.5;', '}', '.ltv-source-adult-notice {', ' margin-bottom: 10px;', ' padding: 8px 10px;', ' background: rgba(236, 72, 153, .08);', ' border: 1px solid rgba(236, 72, 153, .32);', ' border-radius: 8px;', ' color: #f9a8d4;', ' font-size: 11px;', ' line-height: 1.5;', '}', '.ltv-src-normal-toggle {', ' display: inline-flex;', ' align-items: center;', ' gap: 5px;', ' padding: 2px 8px;', ' background: rgba(0, 204, 255, .08);', ' border: 1px solid rgba(0, 204, 255, .3);', ' border-radius: 999px;', ' color: #67e8f9;', ' font-size: 11px;', ' font-weight: 600;', ' white-space: nowrap;', '}', '.ltv-src-normal-toggle input {', ' width: 14px;', ' height: 14px;', ' margin: 0;', ' accent-color: #00ccff;', ' cursor: pointer;', '}', '.ltv-src-adult-toggle {', ' display: inline-flex;', ' align-items: center;', ' gap: 5px;', ' color: #f9a8d4;', ' font-size: 11px;', ' white-space: nowrap;', '}', '.ltv-src-adult-toggle input {', ' width: 14px;', ' height: 14px;', ' margin: 0;', ' accent-color: #ec4899;', ' cursor: pointer;', '}', '.ltv-src-adult-toggle.is-master {', ' padding: 2px 8px;', ' background: rgba(236, 72, 153, .1);', ' border: 1px solid rgba(236, 72, 153, .35);', ' border-radius: 999px;', ' color: #f472b6;', ' font-weight: 600;', '}', '.ltv-source-subtitle {', ' margin-top: 12px;', ' padding: 6px 0 4px;', ' color: #9ca3af;', ' font-size: 11px;', ' font-weight: 600;', ' border-top: 1px solid #222;', '}', '.ltv-source-subtitle.is-adult { color: #f9a8d4; }', '.ltv-src-row.is-adult {', ' border-left: 2px solid rgba(236, 72, 153, .45);', ' padding-left: 8px;', '}', '.ltv-source-adult-check {', ' display: flex;', ' align-items: center;', ' gap: 7px;', ' color: #f9a8d4;', ' font-size: 12px;', ' line-height: 1.5;', '}', '.ltv-source-adult-check input {', ' width: 15px;', ' height: 15px;', ' margin: 0;', ' accent-color: #ec4899;', ' cursor: pointer;', '}', '.ltv-source-toolbar {', ' display: flex;', ' flex-wrap: wrap;', ' align-items: center;', ' gap: 8px;', ' margin-bottom: 8px;', '}', '.ltv-source-keyword-label {', ' display: flex;', ' align-items: center;', ' gap: 6px;', ' color: #9ca3af;', ' font-size: 11px;', '}', '.ltv-source-keyword-label input {', ' width: 120px;', ' min-height: 32px;', ' padding: 4px 8px;', ' background: #0b0b0b;', ' border: 1px solid #333;', ' border-radius: 8px;', ' color: #e5e7eb;', ' font-size: 13px;', ' font-family: inherit;', ' outline: none;', '}', '.ltv-source-keyword-label input:focus { border-color: #00ccff; }', '.ltv-source-action-btn {', ' min-height: 32px;', ' padding: 3px 10px;', ' background: #1a1a1a;', ' border: 1px solid #333;', ' border-radius: 8px;', ' color: #d1d5db;', ' font-size: 12px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-source-action-btn:hover { background: #262626; }', '.ltv-source-action-btn.is-primary {', ' background: #00a3cc;', ' border-color: #00a3cc;', ' color: #001318;', ' font-weight: 600;', '}', '.ltv-source-action-btn.is-primary:hover { background: #00bde8; }', '.ltv-source-action-btn:disabled { opacity: .5; cursor: wait; }', '.ltv-source-summary { margin-bottom: 8px; color: #9ca3af; font-size: 11px; line-height: 1.5; }', '.ltv-source-list { border-top: 1px solid #222; }', '.ltv-src-row {', ' display: grid;', ' grid-template-columns: 20px minmax(0, 1fr) auto;', ' align-items: center;', ' gap: 8px 10px;', ' padding: 9px 0;', ' border-bottom: 1px solid #222;', '}', '.ltv-src-check { width: 16px; height: 16px; margin: 0; accent-color: #00ccff; cursor: pointer; flex: none; }', '.ltv-src-main { min-width: 0; }', '.ltv-src-name {', ' display: flex;', ' align-items: center;', ' gap: 6px;', ' flex-wrap: wrap;', ' color: #fff;', ' font-size: 13px;', ' font-weight: 600;', ' line-height: 1.4;', '}', '.ltv-src-url {', ' margin-top: 2px;', ' color: #6b7280;', ' font-size: 10px;', ' line-height: 1.4;', ' white-space: nowrap;', ' overflow: hidden;', ' text-overflow: ellipsis;', '}', '.ltv-src-side { display: flex; align-items: center; justify-content: flex-end; gap: 6px; flex-wrap: wrap; }', '.ltv-type-badge {', ' padding: 1px 6px;', ' background: #222;', ' border: 1px solid #333;', ' border-radius: 999px;', ' color: #9ca3af;', ' font-size: 10px;', ' font-weight: 400;', '}', '.ltv-type-badge.is-adult { color: #f9a8d4; border-color: rgba(236, 72, 153, .35); }', '.ltv-status-badge {', ' padding: 1px 6px;', ' border: 1px solid transparent;', ' border-radius: 999px;', ' font-size: 10px;', ' line-height: 1.5;', ' white-space: nowrap;', '}', '.ltv-status-badge.is-ok { color: #86efac; background: rgba(34, 197, 94, .12); border-color: rgba(34, 197, 94, .35); }', '.ltv-status-badge.is-empty { color: #fcd34d; background: rgba(245, 158, 11, .12); border-color: rgba(245, 158, 11, .35); }', '.ltv-status-badge.is-error { color: #fca5a5; background: rgba(239, 68, 68, .12); border-color: rgba(239, 68, 68, .35); }', '.ltv-status-badge.is-testing { color: #93c5fd; background: rgba(59, 130, 246, .12); border-color: rgba(59, 130, 246, .35); }', '.ltv-status-badge.is-untested { color: #9ca3af; background: #1a1a1a; border-color: #333; }', '.ltv-src-latency {', ' display: inline-block;', ' max-width: 150px;', ' color: #9ca3af;', ' font-size: 10px;', ' white-space: nowrap;', ' overflow: hidden;', ' text-overflow: ellipsis;', ' vertical-align: middle;', '}', '.ltv-src-test-btn {', ' min-height: 28px;', ' padding: 2px 8px;', ' background: #1a1a1a;', ' border: 1px solid #333;', ' border-radius: 6px;', ' color: #d1d5db;', ' font-size: 11px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-src-test-btn:hover { background: #262626; }', '.ltv-src-test-btn:disabled { opacity: .5; cursor: wait; }', '.ltv-src-test-btn.is-danger { color: #fca5a5; border-color: rgba(239, 68, 68, .3); }', '.ltv-source-empty { padding: 24px 0; color: #9ca3af; font-size: 12px; text-align: center; }', '.ltv-source-loading { padding: 32px 0; color: #9ca3af; font-size: 12px; text-align: center; }', '.ltv-source-hint { margin-top: 10px; color: #6b7280; font-size: 10px; line-height: 1.6; }', '.ltv-custom-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; margin-bottom: 6px; }', '.ltv-custom-list { border-top: 1px solid #222; }', '.ltv-custom-row { display: flex; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid #222; }', '.ltv-custom-main { flex: 1; min-width: 0; }', '.ltv-custom-actions { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }', '.ltv-source-form {', ' display: flex;', ' flex-direction: column;', ' gap: 10px;', ' margin-top: 12px;', ' padding: 12px;', ' background: #0f0f0f;', ' border: 1px solid #262626;', ' border-radius: 10px;', '}', '.ltv-source-form-title { color: #fff; font-size: 13px; font-weight: 600; }', '.ltv-source-form-actions { display: flex; gap: 8px; flex-wrap: wrap; }', '.ltv-form-status { min-height: 16px; color: #9ca3af; font-size: 11px; line-height: 1.5; word-break: break-word; }', '.ltv-form-status.is-error { color: #fca5a5; }', '.ltv-form-status.is-ok { color: #86efac; }', '.ltv-form-status.is-warn { color: #fcd34d; }', '.ltv-form-status.is-busy { color: #93c5fd; }', '@media (max-width: 820px) {', ' .ltv-source-panel { width: min(560px, 96vw); }', ' .ltv-source-toolbar { gap: 6px; }', '}', '@media (max-width: 640px) {', ' #ltv-source-overlay { align-items: flex-end; padding: 0; }', ' .ltv-source-panel {', ' width: 100%;', ' max-height: 90vh;', ' max-height: 90dvh;', ' border-radius: 14px 14px 0 0;', ' border-left: 0;', ' border-right: 0;', ' border-bottom: 0;', ' }', ' .ltv-source-tabs { padding: 6px 12px 0; }', ' .ltv-source-body { padding: 10px 12px 16px; }', ' .ltv-source-toolbar { align-items: stretch; }', ' .ltv-source-keyword-label { flex-basis: 100%; }', ' .ltv-source-keyword-label input { flex: 1; width: auto; min-height: 40px; font-size: 16px; }', ' .ltv-source-action-btn { flex: 1 1 45%; min-height: 38px; }', ' .ltv-src-row { grid-template-columns: 20px minmax(0, 1fr); align-items: start; }', ' .ltv-src-side { grid-column: 2; justify-content: flex-start; }', ' .ltv-src-test-btn { min-height: 32px; }', ' .ltv-custom-row { align-items: flex-start; flex-wrap: wrap; }', ' .ltv-custom-actions { width: 100%; justify-content: flex-end; }', ' .ltv-source-form .ltv-field input { min-height: 42px; font-size: 16px; }', '}', '#ltv-fav-overlay {', ' position: fixed;', ' inset: 0;', ' z-index: 10002;', ' display: flex;', ' align-items: center;', ' justify-content: center;', ' padding: 16px;', ' background: rgba(0, 0, 0, .76);', '}', '.ltv-fav-panel { width: min(560px, 96vw); }', '.ltv-fav-body { flex: 1 1 auto; min-height: 0; overflow: auto; }', '.ltv-fav-empty { padding: 28px 16px; text-align: center; color: #9ca3af; font-size: 12px; line-height: 1.7; }', '.ltv-fav-row {', ' display: flex;', ' gap: 10px;', ' padding: 10px 16px;', ' border-bottom: 1px solid #222;', '}', '.ltv-fav-row:last-child { border-bottom: 0; }', '.ltv-fav-cover {', ' width: 56px;', ' height: 78px;', ' flex: none;', ' border-radius: 6px;', ' border: 1px solid #2a2a2a;', ' background: #1a1a1a center / cover no-repeat;', '}', '.ltv-fav-main { flex: 1; min-width: 0; }', '.ltv-fav-title {', ' color: #fff;', ' font-weight: 600;', ' font-size: 13px;', ' line-height: 1.45;', ' word-break: break-word;', '}', '.ltv-fav-tags { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 5px; }', '.ltv-fav-tag {', ' padding: 1px 6px;', ' border: 1px solid #333;', ' border-radius: 999px;', ' color: #9ca3af;', ' font-size: 10px;', ' line-height: 1.6;', '}', '.ltv-fav-tag.update {', ' color: #fbcfe8;', ' border-color: rgba(244, 114, 182, .45);', ' background: rgba(236, 72, 153, .1);', '}', '.ltv-fav-meta {', ' margin-top: 5px;', ' color: #9ca3af;', ' font-size: 11px;', ' line-height: 1.5;', ' word-break: break-word;', '}', '.ltv-fav-ops { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 7px; }', '.ltv-fav-op {', ' min-height: 26px;', ' padding: 2px 9px;', ' border: 1px solid #333;', ' border-radius: 6px;', ' background: #141414;', ' color: #d1d5db;', ' font-size: 11px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-fav-op:hover { border-color: #00ccff; color: #fff; }', '.ltv-fav-op.danger:hover { border-color: #ef4444; color: #fca5a5; }', '.ltv-fav-auto {', ' display: flex;', ' align-items: center;', ' gap: 6px;', ' padding: 8px 16px;', ' border-top: 1px solid #222;', ' color: #9ca3af;', ' font-size: 11px;', '}', '.ltv-fav-status {', ' padding: 8px 16px;', ' border-top: 1px solid #222;', ' color: #9ca3af;', ' font-size: 11px;', ' line-height: 1.5;', ' min-height: 16px;', '}', '.ltv-fav-status:empty { display: none; }', '@media (max-width: 640px) {', ' #ltv-fav-overlay { align-items: flex-end; padding: 0; }', ' .ltv-fav-panel {', ' width: 100%;', ' max-height: 92vh;', ' max-height: 92dvh;', ' border-radius: 14px 14px 0 0;', ' border-left: 0;', ' border-right: 0;', ' border-bottom: 0;', ' }', ' .ltv-fav { width: 26px; height: 26px; font-size: 15px; }', ' .ltv-fav-row { padding: 10px 12px; }', ' .ltv-fav-cover { width: 48px; height: 68px; }', ' .ltv-fav-op { min-height: 32px; }', ' .ltv-fav-auto { font-size: 12px; }', '}', '#ltv-home-entry {', ' position: fixed;', ' right: 16px;', ' bottom: calc(16px + env(safe-area-inset-bottom));', ' z-index: 30;', ' display: flex;', ' align-items: center;', ' gap: 6px;', ' padding: 5px;', ' background: rgba(16, 16, 16, .92);', ' border: 1px solid #2a2a2a;', ' border-radius: 999px;', ' box-shadow: 0 8px 24px rgba(0, 0, 0, .45);', ' backdrop-filter: blur(6px);', ' font-family: inherit;', '}', '#ltv-home-entry .ltv-home-btn {', ' display: inline-flex;', ' align-items: center;', ' gap: 5px;', ' min-height: 30px;', ' padding: 3px 10px;', ' background: #0b0b0b;', ' border: 1px solid #333;', ' border-radius: 999px;', ' color: #d1d5db;', ' font-size: 12px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '#ltv-home-entry .ltv-home-btn:hover { border-color: #00ccff; color: #fff; }', '#ltv-home-entry .ltv-home-btn.is-on { border-color: rgba(0, 204, 255, .45); }', '#ltv-home-entry .ltv-fav-icon { color: #fbbf24; font-size: 12px; line-height: 1; }', '#ltv-home-entry .ltv-home-btn.has-update { border-color: rgba(244, 114, 182, .55); color: #fbcfe8; }', '#ltv-home-entry .ltv-home-btn.has-update .ltv-fav-icon { color: #f472b6; }', '#ltv-home-entry .ltv-home-btn[data-state="ready"] .ltv-sync-dot { background: #00ccff; }', '#ltv-home-entry .ltv-home-btn[data-state="syncing"] .ltv-sync-dot { background: #f59e0b; }', '#ltv-home-entry .ltv-home-btn[data-state="error"] .ltv-sync-dot { background: #ef4444; }', '@media (max-width: 640px) {', ' #ltv-home-entry { right: 12px; bottom: calc(12px + env(safe-area-inset-bottom)); }', ' #ltv-home-entry .ltv-home-btn { min-height: 36px; font-size: 13px; }', '}', '.ltv-site-sync-notice {', ' position: fixed;', ' right: 16px;', ' bottom: 16px;', ' z-index: 64;', ' display: flex;', ' align-items: center;', ' gap: 10px;', ' padding: 10px 12px;', ' background: #101010;', ' border: 1px solid rgba(0, 204, 255, .45);', ' border-radius: 10px;', ' color: #d1d5db;', ' font-size: 12px;', ' box-shadow: 0 8px 24px rgba(0, 0, 0, .4);', '}', '.ltv-site-sync-notice button {', ' min-height: 28px;', ' padding: 2px 9px;', ' border-radius: 6px;', ' font-size: 11px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-site-sync-notice [data-site-sync-refresh] {', ' background: #00a3cc;', ' border: 1px solid #00a3cc;', ' color: #001318;', ' font-weight: 600;', '}', '.ltv-site-sync-notice [data-site-sync-close] {', ' background: none;', ' border: 0;', ' color: #9ca3af;', ' font-size: 14px;', ' padding: 0 2px;', '}', '@media (max-width: 640px) {', ' .ltv-site-sync-notice { left: 12px; right: 12px; bottom: calc(12px + env(safe-area-inset-bottom)); justify-content: space-between; }', '}' ].join('\n'); (document.head || document.documentElement).appendChild(style); } function waitForResults() { if (waitTimer) return; let tries = 0; waitTimer = setInterval(function () { tries++; if (tries > 50 || !isSearchPage()) { clearInterval(waitTimer); waitTimer = null; return; } if (document.querySelector('#results')) { clearInterval(waitTimer); waitTimer = null; boot(); } }, 300); } function setup() { injectStyle(); ensureToolbar(); bindResults(); if (!observer) { observer = new MutationObserver(function () { scheduleRender(); }); } render(true); } function teardown() { if (observer) { observer.disconnect(); observer = null; } if (renderTimer) { clearTimeout(renderTimer); renderTimer = null; } if (waitTimer) { clearInterval(waitTimer); waitTimer = null; } closePicker(); siteSyncNoticePending = false; closeSyncModal(); closeSourceModal(); closeFavModal(); closeOpPanel(); removeHomeEntry(); if (boundResultsEl) { boundResultsEl.removeEventListener('click', onResultsClickCapture, true); boundResultsEl = null; } const toolbarNode = document.getElementById(TOOLBAR_ID); if (toolbarNode) toolbarNode.remove(); const siteSyncNotice = document.getElementById('ltv-site-sync-notice'); if (siteSyncNotice) siteSyncNotice.remove(); const styleNode = document.getElementById(STYLE_ID); if (styleNode) styleNode.remove(); toolbar = null; if (resultsEl) { Array.from(resultsEl.children).forEach(function (card) { if (!card.classList || !card.classList.contains('card-hover')) return; card.classList.remove(HIDDEN_CLASS); card.style.order = ''; card.querySelectorAll('.ltv-badge, .ltv-switch, .ltv-fav').forEach(function (node) { node.remove(); }); delete card.dataset.ltvGroup; }); } groupMap.clear(); originalIndexMap = new WeakMap(); parsedCardMap = new WeakMap(); decorationMap = new WeakMap(); decoratedCards = []; renderStamp = 0; orderSupported = null; nextOriginalIndex = 0; lastSignature = ''; lastSettingsKey = ''; parsedCards = []; renderFavoriteMap = new Map(); renderFavoriteNormMap = new Map(); resultsEl = null; } function findFavoriteByNorm(norm) { if (!norm) return null; const list = readFavorites(); return list.find(function (item) { return item.norm === norm; }) || null; } function readShowProgress() { try { const store = getPageStorage(); const parsed = JSON.parse((store && store.getItem(SHOW_PROGRESS_KEY)) || '{}'); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; } catch (e) { return {}; } } function writeShowProgress(data) { try { const store = getPageStorage(); if (!store) return; const sorted = Object.keys(data || {}) .map(function (key) { return { key: key, updatedAt: Number(data[key] && data[key].updatedAt) || 0 }; }) .sort(function (a, b) { return b.updatedAt - a.updatedAt; }) .slice(0, SHOW_PROGRESS_LIMIT); const trimmed = {}; sorted.forEach(function (item) { const entry = data[item.key]; if (!entry || typeof entry !== 'object' || !entry.episodes) return; const episodeKeys = Object.keys(entry.episodes) .map(function (key) { return { key: key, at: Number(entry.episodes[key] && entry.episodes[key].updatedAt) || 0 }; }) .sort(function (a, b) { return a.at - b.at; }) .slice(-500); const episodes = {}; episodeKeys.forEach(function (ep) { episodes[ep.key] = entry.episodes[ep.key]; }); trimmed[item.key] = Object.assign({}, entry, { episodes: episodes }); }); store.setItem(SHOW_PROGRESS_KEY, JSON.stringify(trimmed)); } catch (e) { // 忽略存储失败 } } function getPlayerContext() { const params = new URLSearchParams(location.search || ''); const titleEl = document.getElementById('videoTitle'); const infoEl = document.getElementById('episodeInfo'); const title = (params.get('title') || (titleEl ? titleEl.textContent : '') || '').trim(); const normalized = normalizeTitle(title, '', ''); let episodes = []; try { const raw = params.get('episodes'); if (raw) { const parsed = JSON.parse(decodeURIComponent(raw)); if (Array.isArray(parsed)) episodes = parsed; } } catch (e) { // 集数参数解析失败时忽略 } const infoMatch = /第\s*(\d+)\s*(?:\/\s*(\d+))?\s*集/.exec((infoEl && infoEl.textContent) || ''); const urlIndex = parseInt(params.get('index') || '0', 10) || 0; const episodeNo = infoMatch ? (parseInt(infoMatch[1], 10) || 0) : urlIndex + 1; const total = infoMatch && infoMatch[2] ? (parseInt(infoMatch[2], 10) || 0) : episodes.length; const unknownTitle = !title || title === '未知视频'; return { title: title, norm: unknownTitle ? '' : normalized.norm, kind: normalized.kind, source: (params.get('source') || '').trim(), id: (params.get('id') || '').trim(), episodeNo: episodeNo, total: total, hasEpisodes: !!infoMatch || episodes.length > 0, episodes: episodes }; } function resolveSourceLabel(code) { if (!code) return '未知来源'; try { const live = getSiteWindow().API_SITES; if (live && live[code] && live[code].name) return String(live[code].name); } catch (e) { // 忽略 } const matched = /^custom[_-]?(\d+)$/.exec(code); if (matched) { const custom = readCustomAPIs(); const item = custom[parseInt(matched[1], 10)]; if (item && item.name) return String(item.name); } const custom = readCustomAPIs(); const byName = custom.find(function (item) { return item && (item.name === code || item.key === code); }); if (byName && byName.name) return String(byName.name); return code; } function formatClock(seconds) { const total = Math.max(0, Math.floor(Number(seconds) || 0)); const hours = Math.floor(total / 3600); const minutes = Math.floor((total % 3600) / 60); const secs = total % 60; const pad = function (value) { return value < 10 ? '0' + value : String(value); }; if (hours > 0) return hours + ':' + pad(minutes) + ':' + pad(secs); return minutes + ':' + pad(secs); } function normalizeOpSegment(raw) { if (!raw || typeof raw !== 'object') return null; const from = parseInt(raw.from, 10); if (!from || from < 1) return null; const toRaw = raw.to === null || raw.to === undefined ? null : parseInt(raw.to, 10); const to = toRaw && toRaw >= from ? toRaw : null; const noOp = !!raw.noOp; const start = Math.max(0, Number(raw.start) || 0); const end = Math.max(0, Number(raw.end) || 0); if (!noOp && end <= start) return null; return { id: String(raw.id || ('s' + from)), from: from, to: to, start: noOp ? 0 : Math.round(start), end: noOp ? 0 : Math.round(end), noOp: noOp, source: raw.source === 'learned' ? 'learned' : 'manual', updatedAt: Number(raw.updatedAt) || 0 }; } function normalizeOpShow(raw) { if (!raw || typeof raw !== 'object') return null; const list = []; const seen = {}; (Array.isArray(raw.segments) ? raw.segments : []).forEach(function (item) { const segment = normalizeOpSegment(item); if (!segment || seen[segment.id]) return; seen[segment.id] = true; list.push(segment); }); list.sort(function (a, b) { return a.from - b.from; }); if (list.length > OP_SEGMENT_LIMIT) list.length = OP_SEGMENT_LIMIT; return { title: String(raw.title || ''), episodeOffset: parseInt(raw.episodeOffset, 10) || 0, updatedAt: Number(raw.updatedAt) || 0, segments: list }; } function normalizeOpMarks(raw) { const result = { version: 1, shows: {}, removed: {} }; if (!raw || typeof raw !== 'object') return result; const shows = raw.shows && typeof raw.shows === 'object' ? raw.shows : {}; Object.keys(shows).forEach(function (key) { const show = normalizeOpShow(shows[key]); if (show && key) result.shows[key] = show; }); const removed = raw.removed && typeof raw.removed === 'object' ? raw.removed : {}; Object.keys(removed).forEach(function (key) { const at = Number(removed[key]) || 0; if (key && at > 0) result.removed[key] = at; }); return result; } function readOpMarks() { try { const store = getPageStorage(); return normalizeOpMarks(JSON.parse((store && store.getItem(OP_MARKS_KEY)) || '{}')); } catch (e) { return normalizeOpMarks(null); } } function writeOpMarks(data) { try { const store = getPageStorage(); if (!store) return; const normalized = normalizeOpMarks(data); const keys = Object.keys(normalized.shows); if (keys.length > OP_SHOW_LIMIT) { keys.sort(function (a, b) { return normalized.shows[b].updatedAt - normalized.shows[a].updatedAt; }).slice(OP_SHOW_LIMIT).forEach(function (key) { delete normalized.shows[key]; }); } store.setItem(OP_MARKS_KEY, JSON.stringify(normalized)); } catch (e) { // 忽略存储失败 } } function sameOpMarks(left, right) { return stableStringify(normalizeOpMarks(left)) === stableStringify(normalizeOpMarks(right)); } function mergeOpMarks(localRaw, remoteRaw) { const local = normalizeOpMarks(localRaw); const remote = normalizeOpMarks(remoteRaw); const result = { version: 1, shows: {}, removed: {} }; Object.keys(local.removed).concat(Object.keys(remote.removed)).forEach(function (id) { result.removed[id] = Math.max( result.removed[id] || 0, local.removed[id] || 0, remote.removed[id] || 0 ); }); const keys = Object.keys(local.shows).concat(Object.keys(remote.shows)); keys.forEach(function (key) { if (result.shows[key]) return; const a = local.shows[key]; const b = remote.shows[key]; if (!a && !b) return; const base = !a ? b : (!b ? a : (a.updatedAt >= b.updatedAt ? a : b)); const other = base === a ? b : a; const map = new Map(); (other ? other.segments : []).forEach(function (segment) { map.set(segment.id, segment); }); (base ? base.segments : []).forEach(function (segment) { const existing = map.get(segment.id); if (!existing || segment.updatedAt >= existing.updatedAt) map.set(segment.id, segment); }); const segments = []; map.forEach(function (segment) { const removedAt = result.removed[segment.id] || 0; if (removedAt && removedAt >= segment.updatedAt) return; segments.push(segment); }); segments.sort(function (x, y) { return x.from - y.from; }); result.shows[key] = { title: (base && base.title) || (other && other.title) || '', episodeOffset: (base && base.episodeOffset) || (other && other.episodeOffset) || 0, updatedAt: Math.max( (base && base.updatedAt) || 0, (other && other.updatedAt) || 0 ), segments: segments.slice(0, OP_SEGMENT_LIMIT) }; }); return result; } function scheduleOpMarksUpload() { if (!syncConfig.url || !syncConfig.autoSync || !syncConfig.syncOpMarks) return; scheduleSyncUpload(true); } function getOpOffset(context) { if (!context || !context.norm) return 0; const show = readOpMarks().shows[context.norm]; return show ? (Number(show.episodeOffset) || 0) : 0; } function getOpEpisodeNo(context) { if (!context || !context.episodeNo) return 0; return context.episodeNo + getOpOffset(context); } function resolveOpSegment(context) { if (!context || !context.norm || !context.episodeNo) { return { status: 'unknown', episode: 0, segment: null }; } const show = readOpMarks().shows[context.norm]; const episode = getOpEpisodeNo(context); if (!show || !show.segments.length) { return { status: 'none', episode: episode, segment: null, show: show || null }; } const exact = show.segments.find(function (segment) { return episode >= segment.from && (segment.to === null || episode <= segment.to); }); if (exact) { return { status: exact.noOp ? 'noop' : 'exact', episode: episode, segment: exact, show: show }; } let nearest = null; let distance = Infinity; show.segments.forEach(function (segment) { const current = Math.abs(episode - segment.from); if (current < distance) { distance = current; nearest = segment; } }); if (nearest && distance <= OP_GUESS_RANGE) { return { status: nearest.noOp ? 'noop' : 'guess', episode: episode, segment: nearest, distance: distance, show: show }; } if (nearest && distance <= OP_FAR_RANGE) { return { status: 'far', episode: episode, segment: nearest, distance: distance, show: show }; } return { status: 'none', episode: episode, segment: null, show: show }; } function closeOpSegmentsBefore(show, episode, now) { show.segments.forEach(function (segment) { if (segment.from < episode && (segment.to === null || segment.to >= episode)) { segment.to = episode - 1; segment.updatedAt = now; } }); show.segments = show.segments.filter(function (segment) { return segment.to === null || segment.to >= segment.from; }); } function saveOpSegment(context, endSeconds) { if (!context || !context.norm || !context.episodeNo) return null; const end = Math.round(Number(endSeconds)); if (!end || end < 5) return null; const data = readOpMarks(); const now = Date.now(); let show = data.shows[context.norm]; if (!show) { show = { title: context.title, episodeOffset: 0, updatedAt: now, segments: [] }; data.shows[context.norm] = show; } const episode = getOpEpisodeNo(context); closeOpSegmentsBefore(show, episode, now); const existing = show.segments.find(function (segment) { return segment.from === episode; }); if (existing) { existing.to = null; existing.start = 0; existing.end = end; existing.noOp = false; existing.source = 'manual'; existing.updatedAt = now; } else { show.segments.push({ id: 's' + episode + '_' + now.toString(36), from: episode, to: null, start: 0, end: end, noOp: false, source: 'manual', updatedAt: now }); } show.title = context.title || show.title; show.updatedAt = now; writeOpMarks(data); scheduleOpMarksUpload(); return { episode: episode, end: end }; } function markOpNoOp(context) { if (!context || !context.norm || !context.episodeNo) return null; const data = readOpMarks(); const now = Date.now(); let show = data.shows[context.norm]; if (!show) { show = { title: context.title, episodeOffset: 0, updatedAt: now, segments: [] }; data.shows[context.norm] = show; } const episode = getOpEpisodeNo(context); closeOpSegmentsBefore(show, episode, now); const existing = show.segments.find(function (segment) { return segment.from === episode; }); if (existing) { existing.to = null; existing.start = 0; existing.end = 0; existing.noOp = true; existing.source = 'manual'; existing.updatedAt = now; } else { show.segments.push({ id: 's' + episode + '_' + now.toString(36), from: episode, to: null, start: 0, end: 0, noOp: true, source: 'manual', updatedAt: now }); } show.title = context.title || show.title; show.updatedAt = now; writeOpMarks(data); scheduleOpMarksUpload(); return { episode: episode }; } function removeOpSegment(context, segmentId) { if (!context || !context.norm || !segmentId) return false; const data = readOpMarks(); const show = data.shows[context.norm]; if (!show) return false; const before = show.segments.length; show.segments = show.segments.filter(function (segment) { return segment.id !== segmentId; }); if (show.segments.length === before) return false; show.updatedAt = Date.now(); data.removed[segmentId] = Date.now(); if (!show.segments.length) delete data.shows[context.norm]; writeOpMarks(data); scheduleOpMarksUpload(); return true; } function setOpOffset(context, offset) { if (!context || !context.norm) return false; const value = parseInt(offset, 10) || 0; const data = readOpMarks(); const now = Date.now(); let show = data.shows[context.norm]; if (!show) { show = { title: context.title, episodeOffset: value, updatedAt: now, segments: [] }; data.shows[context.norm] = show; } else { show.episodeOffset = value; show.updatedAt = now; } writeOpMarks(data); scheduleOpMarksUpload(); return true; } function isOpLearnEnabled() { try { const store = getPageStorage(); return !!store && store.getItem(OP_LEARN_ON_KEY) === '1'; } catch (e) { return false; } } function setOpLearnEnabled(enabled) { try { const store = getPageStorage(); if (store) store.setItem(OP_LEARN_ON_KEY, enabled ? '1' : '0'); } catch (e) { // 忽略存储失败 } } function readOpLearn() { try { const store = getPageStorage(); const parsed = JSON.parse((store && store.getItem(OP_LEARN_KEY)) || '{}'); return parsed && typeof parsed === 'object' ? parsed : {}; } catch (e) { return {}; } } function writeOpLearn(data) { try { const store = getPageStorage(); if (store) store.setItem(OP_LEARN_KEY, JSON.stringify(data || {})); } catch (e) { // 忽略存储失败 } } function trackOpLearning(previous, next, context) { if (!isOpLearnEnabled()) return; if (!context || !context.norm || !context.episodeNo) return; if (!previous || !next) return; if (previous > 60) return; if (next < 60 || next > 300) return; if (next - previous < 30) return; const data = readOpLearn(); const entry = data[context.norm] && typeof data[context.norm] === 'object' ? data[context.norm] : { title: context.title, candidates: [] }; entry.title = context.title || entry.title; entry.candidates = Array.isArray(entry.candidates) ? entry.candidates : []; entry.candidates.push({ episode: context.episodeNo, target: Math.round(next), at: Date.now() }); entry.candidates = entry.candidates.slice(-8); data[context.norm] = entry; writeOpLearn(data); maybeSuggestLearnedOp(context); } function maybeSuggestLearnedOp(context) { if (!context || !context.norm) return; const data = readOpLearn(); const entry = data[context.norm]; if (!entry || !Array.isArray(entry.candidates)) return; const latest = entry.candidates[entry.candidates.length - 1]; if (!latest) return; const matched = entry.candidates.filter(function (item) { return Math.abs(item.target - latest.target) <= 3; }); const episodes = {}; matched.forEach(function (item) { episodes[item.episode] = true; }); if (Object.keys(episodes).length < 3) return; const resolved = resolveOpSegment(context); if (resolved.segment && !resolved.segment.noOp && Math.abs(resolved.segment.end - latest.target) <= 3) { return; } if (entry.learnedTarget && Math.abs(entry.learnedTarget - latest.target) <= 3 && Date.now() - (Number(entry.learnedAt) || 0) < 6 * 60 * 60 * 1000) { return; } showOpLearnToast(latest.target, context, data); } function showOpLearnToast(target, context, learnData) { const root = playerOverlayRoot; if (!root) return; if (opLearnToast && root.contains(opLearnToast)) return; const toast = document.createElement('div'); toast.className = 'ltv-resume-toast ltv-op-learn-toast'; const text = document.createElement('div'); text.className = 'ltv-resume-text'; text.textContent = '检测到片头大约 ' + formatClock(target) + ',是否记录为本剧片头?'; toast.appendChild(text); const actions = document.createElement('div'); actions.className = 'ltv-resume-actions'; const confirmButton = document.createElement('button'); confirmButton.type = 'button'; confirmButton.className = 'ltv-resume-primary'; confirmButton.textContent = '记录'; confirmButton.addEventListener('click', function () { saveOpSegment(context, target); const data = learnData || readOpLearn(); if (data[context.norm]) { data[context.norm].learnedTarget = target; data[context.norm].learnedAt = Date.now(); data[context.norm].candidates = []; writeOpLearn(data); } toast.remove(); opLearnToast = null; refreshOpPlayerUi(true); if (opPanel) renderOpPanel(); playerNotice('已记录片头 ' + formatClock(target)); }); const ignoreButton = document.createElement('button'); ignoreButton.type = 'button'; ignoreButton.className = 'ltv-resume-secondary'; ignoreButton.textContent = '忽略'; ignoreButton.addEventListener('click', function () { const data = learnData || readOpLearn(); if (data[context.norm]) { data[context.norm].candidates = []; writeOpLearn(data); } toast.remove(); opLearnToast = null; }); const closeButton = document.createElement('button'); closeButton.type = 'button'; closeButton.className = 'ltv-resume-close'; closeButton.setAttribute('aria-label', '关闭'); closeButton.textContent = '×'; closeButton.addEventListener('click', function () { toast.remove(); opLearnToast = null; }); actions.appendChild(confirmButton); actions.appendChild(ignoreButton); actions.appendChild(closeButton); toast.appendChild(actions); root.appendChild(toast); opLearnToast = toast; setTimeout(function () { if (toast.isConnected) toast.remove(); if (opLearnToast === toast) opLearnToast = null; }, 20000); } function showOpUndoToast(previousPosition) { const root = playerOverlayRoot; if (!root) return; const old = root.querySelector('.ltv-op-undo'); if (old) old.remove(); const toast = document.createElement('div'); toast.className = 'ltv-resume-toast ltv-op-undo'; const text = document.createElement('div'); text.className = 'ltv-resume-text'; text.textContent = '已跳过片头'; toast.appendChild(text); const actions = document.createElement('div'); actions.className = 'ltv-resume-actions'; const undoButton = document.createElement('button'); undoButton.type = 'button'; undoButton.className = 'ltv-resume-secondary'; undoButton.textContent = '撤销'; undoButton.addEventListener('click', function () { try { playerVideo.currentTime = previousPosition; } catch (e) { /* 忽略 */ } toast.remove(); refreshOpPlayerUi(true); }); actions.appendChild(undoButton); toast.appendChild(actions); root.appendChild(toast); setTimeout(function () { if (toast.isConnected) toast.remove(); }, 6000); } function findProgressElement() { return document.querySelector('#player .art-progress') || document.querySelector('.art-progress') || document.querySelector('.art-bottom .art-progress'); } function removeOpMarkers() { if (opMarkBand) { opMarkBand.remove(); opMarkBand = null; } if (opMarkLine) { opMarkLine.remove(); opMarkLine = null; } } function updateOpMarkers(resolved) { const progress = findProgressElement(); const segment = resolved && resolved.segment; const duration = playerVideo ? (Number(playerVideo.duration) || 0) : 0; if (!progress || !segment || segment.noOp || !duration || (resolved.status !== 'exact' && resolved.status !== 'guess')) { removeOpMarkers(); return; } if (!opMarkBand || !progress.contains(opMarkBand)) { removeOpMarkers(); opMarkBand = document.createElement('div'); opMarkBand.className = 'ltv-op-band'; progress.appendChild(opMarkBand); } if (!opMarkLine || !progress.contains(opMarkLine)) { opMarkLine = document.createElement('div'); opMarkLine.className = 'ltv-op-line'; progress.appendChild(opMarkLine); } const startPercent = Math.max(0, Math.min(100, (segment.start / duration) * 100)); const endPercent = Math.max(0, Math.min(100, (segment.end / duration) * 100)); opMarkBand.style.left = startPercent + '%'; opMarkBand.style.width = Math.max(0, endPercent - startPercent) + '%'; opMarkLine.style.left = endPercent + '%'; } function updateOpSkipButton(resolved) { if (!opSkipButton) return; const segment = resolved && resolved.segment; const time = playerVideo ? Number(playerVideo.currentTime) || 0 : 0; const visible = !!segment && !segment.noOp && (resolved.status === 'exact' || resolved.status === 'guess') && time < segment.end && time >= Math.max(0, segment.start - 2); if (!visible) { opSkipButton.hidden = true; opSkipButton.dataset.opEnd = ''; return; } opSkipButton.hidden = false; opSkipButton.dataset.opEnd = String(segment.end); opSkipButton.textContent = '跳过片头 ' + formatClock(segment.end) + (resolved.status === 'guess' ? '(推测)' : ''); opSkipButton.title = '跳到 ' + formatClock(segment.end); } function refreshOpPlayerUi(force) { if (!isPlayerPage()) return; const now = Date.now(); if (!force && now - opLastUiAt < 600) return; opLastUiAt = now; const context = getPlayerContext(); const resolved = resolveOpSegment(context); updateOpSkipButton(resolved); updateOpMarkers(resolved); if (opPanel) updateOpPanelNow(); } function onOpSkipClick(event) { if (event) { event.preventDefault(); event.stopPropagation(); } if (!playerVideo) return; const end = Number(opSkipButton && opSkipButton.dataset.opEnd) || 0; if (!end) return; const duration = Number(playerVideo.duration) || 0; const target = duration ? Math.min(end, Math.max(0, duration - 2)) : end; const from = Number(playerVideo.currentTime) || 0; if (target <= from + 1) return; try { playerVideo.currentTime = target; playerVideo.play().catch(function () {}); } catch (e) { return; } showOpUndoToast(from); refreshOpPlayerUi(true); } function setOpStatus(message) { const node = opPanel && opPanel.querySelector('#ltv-op-status'); if (node) node.textContent = message || ''; } function closeOpPanel() { const overlay = opPanel || document.getElementById('ltv-op-overlay'); if (!overlay) return; if (overlay._ltvKeyHandler) document.removeEventListener('keydown', overlay._ltvKeyHandler); overlay.remove(); opPanel = null; // 关闭面板后重新计时,让播放页 UI 继续自动隐藏 wakePlayerUi(); } function openOpPanel() { if (!ensureSiteAccess()) return; injectStyle(); injectPlayerStyle(); closeOpPanel(); const overlay = document.createElement('div'); overlay.id = 'ltv-op-overlay'; overlay.className = 'ltv-sync-overlay'; overlay.setAttribute('role', 'dialog'); overlay.setAttribute('aria-modal', 'true'); overlay.innerHTML = [ '
', '
', '
', '
片头设置
', '
', '
', ' ', '
', '
', '
', '
', ' 本集片头', ' 未配置', '
', ' 未配置', '
', '
', ' ', ' ', '
', '
', '
已配置区间
', '
', '
', '
', '
', ' ', ' ', ' ', '
', ' ', '
', '
', '
片头只会显示「跳过」按钮,不会自动跳转;换 OP 时在新的一集重新标记即可。
', '
', '
' ].join(''); document.body.appendChild(overlay); opPanel = overlay; renderOpPanel(); overlay.addEventListener('click', function (event) { if (event.target === overlay || event.target.closest('[data-op-close]')) { closeOpPanel(); return; } const removeButton = event.target.closest('[data-op-del]'); if (removeButton) { const context = getPlayerContext(); if (removeOpSegment(context, removeButton.dataset.opDel)) { setOpStatus('已删除该区间'); renderOpPanel(); refreshOpPlayerUi(true); } return; } const action = event.target.closest('[data-op-action]'); if (!action) return; const context = getPlayerContext(); if (action.dataset.opAction === 'mark-end') { if (!playerVideo || !context.episodeNo) { setOpStatus('无法识别当前集数,请确认页面已加载集数信息'); return; } const end = Number(playerVideo.currentTime) || 0; if (end < 5) { setOpStatus('当前播放位置太靠前,请播放到片头结束后再标记'); return; } const saved = saveOpSegment(context, end); if (saved) { setOpStatus('已记录:第 ' + saved.episode + ' 集起,片头 0:00 → ' + formatClock(saved.end)); renderOpPanel(); refreshOpPlayerUi(true); } else { setOpStatus('标记失败,请稍后重试'); } return; } if (action.dataset.opAction === 'mark-noop') { const saved = markOpNoOp(context); if (saved) { setOpStatus('已标记第 ' + saved.episode + ' 集无片头'); renderOpPanel(); refreshOpPlayerUi(true); } else { setOpStatus('无法识别当前集数'); } return; } if (action.dataset.opAction === 'save-offset') { const input = opPanel.querySelector('#ltv-op-offset'); const value = parseInt((input && input.value) || '0', 10) || 0; if (setOpOffset(context, value)) { setOpStatus('已保存集数偏移:' + value); renderOpPanel(); refreshOpPlayerUi(true); } return; } }); overlay.addEventListener('change', function (event) { if (event.target && event.target.id === 'ltv-op-learn') { setOpLearnEnabled(!!event.target.checked); setOpStatus(event.target.checked ? '学习模式已开启' : '学习模式已关闭'); } }); const keyHandler = function (event) { if (event.key === 'Escape') { event.preventDefault(); closeOpPanel(); } }; document.addEventListener('keydown', keyHandler); overlay._ltvKeyHandler = keyHandler; } function updateOpPanelNow() { if (!opPanel) return; const node = opPanel.querySelector('#ltv-op-now-time'); if (!node) return; const time = playerVideo ? (Number(playerVideo.currentTime) || 0) : 0; node.textContent = '当前 ' + formatClock(time); } function renderOpPanel() { if (!opPanel) return; const context = getPlayerContext(); const data = readOpMarks(); const show = context.norm ? data.shows[context.norm] : null; const offset = show ? (Number(show.episodeOffset) || 0) : 0; const episode = context.episodeNo ? context.episodeNo + offset : 0; const resolved = resolveOpSegment(context); const sub = opPanel.querySelector('#ltv-op-sub'); if (sub) { if (!context.norm) { sub.textContent = '无法识别当前片名,暂时不能配置片头'; } else if (!context.episodeNo) { sub.textContent = context.title + ' · 无法识别集数'; } else { sub.textContent = context.title + ' · 第 ' + context.episodeNo + (context.total ? '/' + context.total : '') + ' 集' + (offset ? '(配置为第 ' + episode + ' 集)' : ''); } } const nowValue = opPanel.querySelector('#ltv-op-now-value'); const nowPill = opPanel.querySelector('#ltv-op-now-pill'); if (nowValue && nowPill) { let value = '未配置'; let pill = '未配置'; let pillClass = 'ltv-op-pill'; nowValue.classList.add('is-muted'); if (resolved.status === 'unknown') { value = '无法识别'; pill = '不可用'; } else if (resolved.status === 'noop') { value = '本集无片头'; pill = '不跳过'; pillClass += ' is-hit'; } else if (resolved.segment) { value = '0:00 → ' + formatClock(resolved.segment.end); nowValue.classList.remove('is-muted'); if (resolved.status === 'exact') { pill = '命中本集区间'; pillClass += ' is-hit'; } else if (resolved.status === 'guess') { pill = '推算 · 差 ' + resolved.distance + ' 集'; pillClass += ' is-hit'; } else { pill = '建议重新标记'; pillClass += ' is-missing'; } } nowValue.textContent = value; nowPill.textContent = pill; nowPill.className = pillClass; } const segments = show ? show.segments : []; const count = opPanel.querySelector('#ltv-op-count'); if (count) count.textContent = segments.length ? '共 ' + segments.length + ' 段' : '暂无'; const list = opPanel.querySelector('#ltv-op-list'); if (list) { list.innerHTML = ''; if (!segments.length) { const empty = document.createElement('div'); empty.className = 'ltv-op-empty'; empty.textContent = '播放到片头结束后,点上方「用当前位置设为片头结束」记录一次,后续集数会自动沿用。'; list.appendChild(empty); } else { segments.forEach(function (segment) { const hit = !!episode && episode >= segment.from && (segment.to === null || episode <= segment.to); const row = document.createElement('div'); row.className = 'ltv-op-row' + (hit ? ' is-hit' : ''); const main = document.createElement('div'); main.className = 'ltv-op-row-main'; const range = document.createElement('div'); range.className = 'ltv-op-range'; range.textContent = '第 ' + segment.from + '–' + (segment.to === null ? '当前集' : segment.to + ' 集'); if (!segment.noOp) { const time = document.createElement('span'); time.className = 'ltv-op-range-time'; time.textContent = '0:00 → ' + formatClock(segment.end); range.appendChild(time); } main.appendChild(range); const tags = document.createElement('div'); tags.className = 'ltv-op-tags'; if (hit) { const tag = document.createElement('span'); tag.className = 'ltv-op-tag hit'; tag.textContent = '命中本集'; tags.appendChild(tag); } if (segment.noOp) { const tag = document.createElement('span'); tag.className = 'ltv-op-tag'; tag.textContent = '无片头'; tags.appendChild(tag); } if (segment.source === 'learned') { const tag = document.createElement('span'); tag.className = 'ltv-op-tag'; tag.textContent = '学习'; tags.appendChild(tag); } if (tags.children.length) main.appendChild(tags); const del = document.createElement('button'); del.type = 'button'; del.className = 'ltv-op-del'; del.dataset.opDel = segment.id; del.textContent = '删除'; row.appendChild(main); row.appendChild(del); list.appendChild(row); }); const hint = document.createElement('div'); hint.className = 'ltv-op-hint'; if (resolved.status === 'guess') { hint.textContent = '本集未精确配置,按最近的区间推算(相差 ' + resolved.distance + ' 集)。'; } else if (resolved.status === 'far') { hint.textContent = '本集距离最近区间 ' + resolved.distance + ' 集,可能是新 OP,建议重新标记。'; } else if (resolved.status === 'none') { hint.textContent = '本集没有匹配到任何区间,可能是新 OP,建议重新标记。'; } if (hint.textContent) list.appendChild(hint); } } const offsetInput = opPanel.querySelector('#ltv-op-offset'); if (offsetInput) offsetInput.value = String(offset); const learnInput = opPanel.querySelector('#ltv-op-learn'); if (learnInput) learnInput.checked = isOpLearnEnabled(); updateOpPanelNow(); } function getPlayerOverlayRoot() { // 优先放进 Artplayer 的容器,全屏时状态条和收藏按钮才会一起显示 const artRoot = document.querySelector('#player .art-video-player'); if (artRoot) return artRoot; const player = document.getElementById('player'); if (player) { try { if (window.getComputedStyle(player).position === 'static') { player.style.position = 'relative'; } } catch (e) { // 忽略 } return player; } return document.querySelector('#playerContainer .relative') || document.getElementById('playerContainer'); } function playerNotice(text) { if (!playerOverlayRoot) return; const old = playerOverlayRoot.querySelector('.ltv-player-notice'); if (old) old.remove(); const notice = document.createElement('div'); notice.className = 'ltv-player-notice'; notice.textContent = text; playerOverlayRoot.appendChild(notice); setTimeout(function () { notice.remove(); }, 2600); } function savePlayerProgress(force) { if (!playerVideo) return; const context = getPlayerContext(); if (!context.norm || !context.episodeNo) return; const duration = Number(playerVideo.duration) || 0; const position = Number(playerVideo.currentTime) || 0; if (!duration || duration < 30) return; if (position < 3) return; const now = Date.now(); if (!force && now - playerLastSaveAt < PLAYER_PROGRESS_SAVE_GAP) return; playerLastSaveAt = now; const store = readShowProgress(); const entry = store[context.norm] && typeof store[context.norm] === 'object' ? store[context.norm] : { title: context.title, episodes: {} }; entry.title = context.title; entry.norm = context.norm; entry.updatedAt = now; if (!entry.episodes || typeof entry.episodes !== 'object') entry.episodes = {}; entry.episodes[String(context.episodeNo)] = { position: Math.round(position), duration: Math.round(duration), source: context.source, updatedAt: now }; entry.lastEpisode = context.episodeNo; store[context.norm] = entry; writeShowProgress(store); } function showResumeToast(position, source, duration) { const root = playerOverlayRoot; if (!root || !playerVideo) return; const old = root.querySelector('.ltv-resume-toast'); if (old) old.remove(); const toast = document.createElement('div'); toast.className = 'ltv-resume-toast'; const text = document.createElement('div'); text.className = 'ltv-resume-text'; const sourceLabel = source ? resolveSourceLabel(source) : ''; text.textContent = '上次看到 ' + formatClock(position) + (sourceLabel ? '(' + sourceLabel + ')' : '') + ',是否继续?'; toast.appendChild(text); const actions = document.createElement('div'); actions.className = 'ltv-resume-actions'; const continueButton = document.createElement('button'); continueButton.type = 'button'; continueButton.className = 'ltv-resume-primary'; continueButton.textContent = '继续播放'; continueButton.addEventListener('click', function () { const max = Number(playerVideo.duration) || 0; const target = max ? Math.min(position, Math.max(0, max - 5)) : position; try { playerVideo.currentTime = target; playerVideo.play().catch(function () {}); } catch (e) { // 忽略 seek 失败 } toast.remove(); }); const restartButton = document.createElement('button'); restartButton.type = 'button'; restartButton.className = 'ltv-resume-secondary'; restartButton.textContent = '从头播放'; restartButton.addEventListener('click', function () { try { playerVideo.currentTime = 0; } catch (e) { /* 忽略 */ } toast.remove(); }); const closeButton = document.createElement('button'); closeButton.type = 'button'; closeButton.className = 'ltv-resume-close'; closeButton.setAttribute('aria-label', '关闭'); closeButton.textContent = '×'; closeButton.addEventListener('click', function () { toast.remove(); }); actions.appendChild(continueButton); actions.appendChild(restartButton); actions.appendChild(closeButton); toast.appendChild(actions); root.appendChild(toast); setTimeout(function () { toast.remove(); }, 15000); } function maybeRestorePlayerProgress() { if (!playerVideo) return; const context = getPlayerContext(); if (!context.norm || !context.episodeNo) return; const promptKey = context.norm + '#' + context.episodeNo; if (playerPromptedEpisodes[promptKey]) return; const entry = readShowProgress()[context.norm]; const record = entry && entry.episodes && entry.episodes[String(context.episodeNo)]; if (!record) { playerPromptedEpisodes[promptKey] = true; return; } const duration = Number(playerVideo.duration) || Number(record.duration) || 0; const saved = Number(record.position) || 0; if (saved < 15 || (duration && saved >= duration - 10)) { playerPromptedEpisodes[promptKey] = true; return; } const current = Number(playerVideo.currentTime) || 0; const urlPosition = parseInt(new URLSearchParams(location.search).get('position') || '0', 10) || 0; // 站点自己已经恢复过进度时不再打扰 if (urlPosition > 15 || (current > 15 && Math.abs(current - saved) < 30)) { playerPromptedEpisodes[promptKey] = true; return; } playerPromptedEpisodes[promptKey] = true; showResumeToast(saved, record.source, duration); } function updatePlayerStatusBar(force) { if (!playerStatusBar || !playerVideo) return; const now = Date.now(); if (!force && now - playerLastStatusAt < 500) return; playerLastStatusAt = now; const context = getPlayerContext(); const video = playerVideo; const ended = !!video.ended; const paused = !!video.paused; const buffering = !paused && !ended && video.readyState < 3; const stateText = ended ? '已结束' : (paused ? '已暂停' : (buffering ? '缓冲中' : '播放中')); const setText = function (name, value) { const node = playerStatusBar.querySelector('[data-ps="' + name + '"]'); if (node) node.textContent = value || ''; }; setText('state', stateText); setText('source', context.source ? resolveSourceLabel(context.source) : ''); setText('episode', context.hasEpisodes && context.episodeNo ? '第 ' + context.episodeNo + (context.total ? '/' + context.total : '') + ' 集' : ''); let ahead = 0; try { const buffered = video.buffered; for (let index = 0; index < buffered.length; index++) { if (buffered.start(index) <= video.currentTime && video.currentTime <= buffered.end(index)) { ahead = buffered.end(index) - video.currentTime; } } } catch (e) { ahead = 0; } setText('buffer', ahead > 0.5 ? '缓冲 ' + ahead.toFixed(0) + 's' : ''); const rate = Number(video.playbackRate) || 1; setText('rate', Math.abs(rate - 1) > 0.01 ? rate.toFixed(1).replace(/\.0$/, '') + 'x' : ''); const dot = playerStatusBar.querySelector('[data-ps="dot"]'); if (dot) { dot.className = 'ltv-ps-dot' + (ended ? ' is-ended' : (paused ? ' is-paused' : (buffering ? ' is-buffering' : ''))); } playerStatusBar.querySelectorAll('.ltv-ps-sep').forEach(function (sep) { sep.style.display = ''; }); playerStatusBar.querySelectorAll('[data-ps]').forEach(function (node) { if (node.dataset.ps === 'dot' || node.dataset.ps === 'state' || node.dataset.ps === 'sep') return; if (!node.textContent) { node.style.display = 'none'; const previous = node.previousElementSibling; if (previous && previous.classList.contains('ltv-ps-sep')) previous.style.display = 'none'; } else { node.style.display = ''; } }); } function wakePlayerStatus() { if (!playerStatusBar) return; playerStatusBar.classList.add('is-visible'); if (playerStatusTimer) clearTimeout(playerStatusTimer); playerStatusTimer = setTimeout(function () { if (playerStatusBar) playerStatusBar.classList.remove('is-visible'); }, 4000); } function wakePlayerUi() { // 手机端让状态条、收藏、片头按钮跟播放器控制条一起自动隐藏 if (!playerUiAutoHide || !document.body) return; document.body.classList.add('ltv-ui-autohide'); document.body.classList.add('ltv-ui-visible'); wakePlayerStatus(); if (playerUiTimer) clearTimeout(playerUiTimer); playerUiTimer = setTimeout(function () { if (playerVideo && playerVideo.paused) return; if (opPanel) return; if (document.body) document.body.classList.remove('ltv-ui-visible'); }, 3000); } function updatePlayerFavoriteButton() { if (!playerFavButton) return; const context = getPlayerContext(); const favorite = findFavoriteByNorm(context.norm); const icon = playerFavButton.querySelector('.ltv-pf-icon'); const label = playerFavButton.querySelector('.ltv-pf-label'); if (icon) icon.textContent = favorite ? '★' : '☆'; if (label) label.textContent = favorite ? '已收藏' : '收藏'; playerFavButton.classList.toggle('is-on', !!favorite); playerFavButton.classList.toggle('has-update', !!(favorite && favorite.hasUpdate)); playerFavButton.title = favorite ? (favorite.hasUpdate ? '收藏中有更新 · 点击取消收藏' : '已收藏 · 点击取消') : '收藏当前剧'; playerFavButton.disabled = !context.norm; } function togglePlayerFavorite() { const context = getPlayerContext(); if (!context.norm) { playerNotice('无法识别当前片名,暂时不能收藏'); return; } const existing = findFavoriteByNorm(context.norm); if (existing) { removeFavoriteByKey(existing.key); playerNotice('已取消收藏'); updatePlayerFavoriteButton(); return; } const now = Date.now(); const total = context.total || 0; const baseline = total || context.episodeNo || 0; const entry = { key: context.norm + '|?|' + context.kind, title: context.title, norm: context.norm, kind: context.kind, year: '', type: '', remarks: total ? '共 ' + total + ' 集' : '', poster: '', episode: baseline, finished: false, latestEpisode: baseline, latestFinished: false, latestRemarks: total ? '共 ' + total + ' 集' : '', hasUpdate: false, follow: true, sourceCode: context.source, id: context.id, addedAt: now, updatedAt: now, checkedAt: 0 }; const list = readFavorites(); if (!list.some(function (item) { return item.norm === context.norm; })) { list.unshift(entry); writeFavorites(list); updateFavoriteIndicators(); refreshFavoriteButtons(); if (favModal) renderFavList(); scheduleFavoriteUpload(); } playerNotice('已收藏,可在收藏面板查看'); updatePlayerFavoriteButton(); } function ensurePlayerOverlay() { const root = getPlayerOverlayRoot(); if (!root) return null; playerOverlayRoot = root; // Artplayer 初始化完成后容器会变化,把旧节点迁到新容器 if (playerStatusBar && !root.contains(playerStatusBar)) { playerStatusBar.remove(); playerStatusBar = null; } if (playerFavButton && !root.contains(playerFavButton)) { playerFavButton.remove(); playerFavButton = null; } if (!playerStatusBar || !root.contains(playerStatusBar)) { const bar = document.createElement('div'); bar.className = 'ltv-player-status'; bar.innerHTML = [ '', '播放中', '·', '', '·', '', '·', '', '·', '' ].join(''); root.appendChild(bar); playerStatusBar = bar; } if (!playerFavButton || !root.contains(playerFavButton)) { const button = document.createElement('button'); button.type = 'button'; button.className = 'ltv-player-fav'; button.innerHTML = '☆收藏'; ['pointerdown', 'mousedown', 'touchstart'].forEach(function (eventName) { button.addEventListener(eventName, function (event) { event.stopPropagation(); }); }); button.addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); togglePlayerFavorite(); }); root.appendChild(button); playerFavButton = button; } if (opToolsRow && !root.contains(opToolsRow)) { opToolsRow.remove(); opToolsRow = null; opSkipButton = null; } if (!opToolsRow || !root.contains(opToolsRow)) { const row = document.createElement('div'); row.className = 'ltv-player-tools'; row.innerHTML = [ '', '' ].join(''); const skip = row.querySelector('.ltv-op-skip'); const config = row.querySelector('.ltv-op-config'); ['pointerdown', 'mousedown', 'touchstart'].forEach(function (eventName) { row.addEventListener(eventName, function (event) { event.stopPropagation(); }); }); skip.addEventListener('click', onOpSkipClick); config.addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); openOpPanel(); }); root.appendChild(row); opToolsRow = row; opSkipButton = skip; } if (!root._ltvPlayerBound) { root._ltvPlayerBound = true; ['mousemove', 'touchstart', 'pointerdown'].forEach(function (eventName) { root.addEventListener(eventName, wakePlayerStatus, { passive: true }); }); } wakePlayerStatus(); return root; } function handlePlayerEpisodeChange() { const context = getPlayerContext(); const changed = context.episodeNo && context.episodeNo !== playerEpisodeNo; if (changed) playerEpisodeNo = context.episodeNo; updatePlayerStatusBar(true); updatePlayerFavoriteButton(); refreshOpPlayerUi(true); if (changed) { setTimeout(maybeRestorePlayerProgress, 1500); } } function setupPlayerVideo(video) { playerVideo = video; ensurePlayerOverlay(); playerEpisodeNo = getPlayerContext().episodeNo || 0; if (!video._ltvPlayerBound) { video._ltvPlayerBound = true; ['loadedmetadata', 'durationchange'].forEach(function (eventName) { video.addEventListener(eventName, function () { updatePlayerStatusBar(true); wakePlayerUi(); setTimeout(maybeRestorePlayerProgress, 1200); }); }); video.addEventListener('timeupdate', function () { updatePlayerStatusBar(false); savePlayerProgress(false); refreshOpPlayerUi(false); const current = Number(video.currentTime) || 0; if (current > 0) opLastTime = current; }); video.addEventListener('seeked', function () { const current = Number(video.currentTime) || 0; if (opLastTime > 0 && current > opLastTime) { trackOpLearning(opLastTime, current, getPlayerContext()); } refreshOpPlayerUi(true); wakePlayerUi(); }); ['play', 'pause', 'waiting', 'playing', 'ended', 'ratechange', 'progress', 'canplay', 'seeking'].forEach(function (eventName) { video.addEventListener(eventName, function () { updatePlayerStatusBar(true); // 只在用户操作或播放状态变化时唤出 UI, // progress/timeupdate 这类高频事件不再让 UI 一直停留。 if (eventName === 'play' || eventName === 'pause' || eventName === 'seeking' || eventName === 'ended' || eventName === 'ratechange') { wakePlayerUi(); } }); }); video.addEventListener('pause', function () { savePlayerProgress(true); }); video.addEventListener('ended', function () { savePlayerProgress(true); }); } updatePlayerFavoriteButton(); updatePlayerStatusBar(true); refreshOpPlayerUi(true); wakePlayerUi(); if (video.readyState >= 1) { setTimeout(maybeRestorePlayerProgress, 1200); } } function getUserscriptSource() { try { if (typeof GM_info !== 'undefined' && GM_info && typeof GM_info.scriptSource === 'string' && GM_info.scriptSource) { return GM_info.scriptSource; } } catch (e) { // 部分管理器不提供 scriptSource } return ''; } function findPlayerFrame() { if (!IS_TOP_FRAME) return null; const named = document.getElementById('VideoPlayerFrame'); if (named) return named; const frames = document.querySelectorAll('iframe'); for (let i = 0; i < frames.length; i++) { try { const doc = frames[i].contentDocument; if (doc && doc.getElementById('player')) return frames[i]; } catch (e) { // 跨域 iframe 无法访问 } } return null; } function shouldPromotePlayerFrame() { return /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent || ''); } function promotePlayerFrame(frame) { // 手机端无法向 iframe 补注入时,直接把播放器提升为顶层页面, // 脚本管理器对普通页面导航通常都能正常注入。 if (!frame || frame._ltvPromoted) return; frame._ltvPromoted = true; let url = ''; try { url = frame.contentWindow && frame.contentWindow.location ? frame.contentWindow.location.href : ''; } catch (e) { url = ''; } if (!url) url = frame.src || ''; if (!url || url.indexOf('about:') === 0 || url.indexOf('javascript:') === 0) return; try { location.href = url; } catch (e) { // 忽略 } } function installMobilePlayerBridge() { // 手机端直接接管站点的 showVideoPlayer:点击历史记录时顶层跳转到 // 播放页,而不是先开一个注入不了脚本的 iframe,避免二次加载。 if (!IS_TOP_FRAME || !shouldPromotePlayerFrame()) return; const win = getSiteWindow(); if (!win) return; try { if (win.__ltvMobilePlayerBridge) return; if (typeof win.showVideoPlayer !== 'function') return; const original = win.showVideoPlayer; win.showVideoPlayer = function (url) { try { if (url) { location.href = url; return; } } catch (e) { // 回退到站点原逻辑 } return original.apply(this, arguments); }; win.__ltvMobilePlayerBridge = true; } catch (e) { // 沙箱不允许覆盖时忽略 } } function bridgePlayerFrame() { // 有的手机端脚本管理器不会向动态创建的 iframe 注入脚本, // 这里由顶层页面检测同一 iframe 里没有脚本时,手动注入一份; // 拿不到脚本源码时则退化为把播放器提升为独立页面。 if (!IS_TOP_FRAME) return; const frame = findPlayerFrame(); if (!frame) return; if (frame._ltvPromoted) return; let doc = null; let win = null; try { doc = frame.contentDocument; win = frame.contentWindow; } catch (e) { return; } if (!doc || !win || !doc.getElementById('player')) return; if (doc.readyState !== 'complete') return; if (win.__ltvCleanerLoaded || doc.getElementById('ltv-player-style')) return; // 给油猴自身的 iframe 注入留出时间,避免重复运行 if (frame._ltvBridgeDoc !== doc) { frame._ltvBridgeDoc = doc; frame._ltvBridgeAt = Date.now(); frame._ltvBridgeTried = false; frame._ltvBridgeOk = false; return; } if (!frame._ltvBridgeTried) { if (Date.now() - frame._ltvBridgeAt < 4000) return; const source = getUserscriptSource(); if (!source) { if (shouldPromotePlayerFrame()) promotePlayerFrame(frame); return; } frame._ltvBridgeTried = true; try { const script = doc.createElement('script'); script.textContent = source; (doc.body || doc.documentElement).appendChild(script); script.remove(); } catch (e) { // 注入失败,下一轮检测后提升为独立播放页 } return; } if (frame._ltvBridgeOk) return; if (win.__ltvCleanerLoaded || doc.getElementById('ltv-player-style')) { frame._ltvBridgeOk = true; return; } if (Date.now() - frame._ltvBridgeAt > 6500 && shouldPromotePlayerFrame()) { promotePlayerFrame(frame); } } function normalizePlayerFrame(frame) { if (!frame || !frame.style) return; // 有的移动端浏览器/旧缓存里全屏 iframe 的 class 不生效, // 这里兜底写死样式,保证播放器一定铺满屏幕。 frame.style.position = 'fixed'; frame.style.top = '0'; frame.style.left = '0'; frame.style.width = '100%'; frame.style.height = '100%'; frame.style.border = '0'; frame.style.zIndex = '40'; frame.style.background = '#000'; } function cleanupPlayerFrames() { const frames = document.querySelectorAll('#VideoPlayerFrame'); if (!frames.length) return; for (let i = 0; i < frames.length; i++) normalizePlayerFrame(frames[i]); if (frames.length > 1) { for (let i = 0; i < frames.length - 1; i++) frames[i].remove(); } } function parseHistoryOnClick(item) { const attr = (item && item.getAttribute && item.getAttribute('onclick')) || ''; const match = /playFromHistory\('([\s\S]*?)',\s*'([\s\S]*?)',\s*(-?\d+),\s*(-?\d+)\)/.exec(attr); if (!match) return null; return { url: match[1], title: match[2], index: parseInt(match[3], 10) || 0, position: parseInt(match[4], 10) || 0 }; } function buildFallbackPlayerUrl(info) { if (!info || !info.url) return ''; let target = info.url; let realUrl = target; let index = info.index; let source = ''; let sourceCode = ''; let id = ''; try { const parsed = new URL(target, location.origin); if (/(player|watch)\.html$/.test(parsed.pathname)) { realUrl = parsed.searchParams.get('url') || target; index = parseInt(parsed.searchParams.get('index') || String(index), 10) || 0; source = parsed.searchParams.get('source') || ''; sourceCode = parsed.searchParams.get('source_code') || ''; id = parsed.searchParams.get('id') || ''; } } catch (e) { // 使用原始 URL } if (!realUrl) return ''; const params = new URLSearchParams(); params.set('url', realUrl); params.set('title', info.title || ''); params.set('index', String(index)); params.set('position', String(info.position || 0)); if (source) params.set('source', source); if (sourceCode) params.set('source_code', sourceCode); if (id) params.set('id', id); params.set('returnUrl', location.href); return 'player.html?' + params.toString(); } function createPlayerFrame(url) { const frame = document.createElement('iframe'); frame.id = 'VideoPlayerFrame'; frame.src = url; normalizePlayerFrame(frame); (document.body || document.documentElement).appendChild(frame); return frame; } function openFallbackPlayer(item) { const info = parseHistoryOnClick(item); if (!info) return; const url = buildFallbackPlayerUrl(info); if (!url) return; let opened = false; try { const win = getSiteWindow(); if (typeof win.showVideoPlayer === 'function') { win.showVideoPlayer(url); opened = true; } } catch (e) { opened = false; } if (!opened) { try { createPlayerFrame(url); } catch (e) { // 忽略 } } cleanupPlayerFrames(); } function installHistoryClickFallback() { // 正常情况由站点自己打开播放器;这里只在点击历史记录 3 秒后 // 仍未出现播放 iframe 时兜底,避免移动端一直停在历史面板。 if (!IS_TOP_FRAME) return; document.addEventListener('click', function (event) { const target = event.target; if (!target || !target.closest) return; const item = target.closest('#historyList .history-item'); if (!item || target.closest('button')) return; setTimeout(function () { if (document.getElementById('VideoPlayerFrame')) return; const panel = document.getElementById('historyPanel'); if (panel && !panel.classList.contains('show')) return; const frames = document.querySelectorAll('iframe'); for (let i = 0; i < frames.length; i++) { if (String(frames[i].src || '').indexOf('player.html') >= 0) return; } openFallbackPlayer(item); }, 3000); }, true); } function initPlayerFeatures() { // 不按 URL 提前退出:新版播放器可能在根路径渲染,改为等待播放器 DOM 出现 injectStyle(); injectPlayerStyle(); // 手机端:状态条、收藏、片头按钮跟随播放器控制条自动隐藏 playerUiAutoHide = shouldPromotePlayerFrame(); if (playerUiAutoHide) { if (!playerUiBound) { playerUiBound = true; ['pointermove', 'pointerdown', 'touchstart', 'click', 'keydown', 'wheel'].forEach(function (name) { document.addEventListener(name, wakePlayerUi, { passive: true, capture: true }); }); } if (hasPlayerDom()) wakePlayerUi(); } // 只在真正有播放器 DOM 的文档里注册菜单,避免顶层和 iframe 出现重复菜单 if (typeof GM_registerMenuCommand === 'function' && hasPlayerDom()) { try { GM_registerMenuCommand('片头设置(播放页)', openOpPanel); } catch (e) { // 忽略菜单注册失败 } } if (playerWatchTimer) clearInterval(playerWatchTimer); playerWatchTimer = setInterval(function () { installMobilePlayerBridge(); cleanupPlayerFrames(); bridgePlayerFrame(); if (!hasPlayerDom()) return; ensurePlayerFloatButton(); bindPlayerEpisodeWatcher(); const video = document.querySelector('#player video, #playerContainer video, video'); if (!video) return; if (video !== playerVideo) setupPlayerVideo(video); else if (!playerStatusBar || !document.contains(playerStatusBar) || !opToolsRow || !document.contains(opToolsRow)) { ensurePlayerOverlay(); } }, 1000); window.addEventListener('beforeunload', function () { savePlayerProgress(true); }); window.addEventListener('pagehide', function () { savePlayerProgress(true); }); document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'hidden') savePlayerProgress(true); else updatePlayerFavoriteButton(); }); window.addEventListener('storage', function (event) { if (event.key === FAVORITES_KEY) updatePlayerFavoriteButton(); if (event.key === OP_MARKS_KEY) { refreshOpPlayerUi(true); if (opPanel) renderOpPanel(); if (IS_TOP_FRAME) scheduleOpMarksUpload(); } }); refreshOpPlayerUi(true); } function bindPlayerEpisodeWatcher() { if (playerMutationObserver) return; const episodeInfo = document.getElementById('episodeInfo'); if (!episodeInfo || typeof MutationObserver !== 'function') return; playerMutationObserver = new MutationObserver(function () { handlePlayerEpisodeChange(); }); playerMutationObserver.observe(episodeInfo, { childList: true, characterData: true, subtree: true }); } function ensurePlayerFloatButton() { let button = document.getElementById('ltv-op-float'); if (button) return button; injectPlayerStyle(); button = document.createElement('button'); button.id = 'ltv-op-float'; button.type = 'button'; button.className = 'ltv-op-float'; button.title = '片头设置'; button.innerHTML = '⚙片头'; button.addEventListener('click', function (event) { event.preventDefault(); event.stopPropagation(); openOpPanel(); }); (document.body || document.documentElement).appendChild(button); return button; } function injectPlayerStyle() { if (document.getElementById('ltv-player-style')) return; const style = document.createElement('style'); style.id = 'ltv-player-style'; style.textContent = [ '.ltv-player-status {', ' position: absolute;', ' top: 10px;', ' left: 10px;', ' z-index: 20;', ' display: flex;', ' align-items: center;', ' gap: 6px;', ' flex-wrap: wrap;', ' max-width: calc(100% - 96px);', ' padding: 4px 9px;', ' border-radius: 999px;', ' background: rgba(0, 0, 0, .62);', ' border: 1px solid rgba(255, 255, 255, .12);', ' color: #e5e7eb;', ' font-size: 11px;', ' line-height: 1.4;', ' font-family: inherit;', ' pointer-events: none;', ' opacity: 0;', ' transform: translateY(-4px);', ' transition: opacity .2s ease, transform .2s ease;', '}', '.ltv-player-status.is-visible { opacity: 1; transform: translateY(0); }', '.ltv-ps-dot { width: 6px; height: 6px; border-radius: 50%; background: #22c55e; flex: none; }', '.ltv-ps-dot.is-buffering { background: #f59e0b; }', '.ltv-ps-dot.is-paused { background: #9ca3af; }', '.ltv-ps-dot.is-ended { background: #ef4444; }', '.ltv-ps-sep { opacity: .35; }', '.ltv-player-fav {', ' position: absolute;', ' top: 10px;', ' right: 10px;', ' z-index: 21;', ' display: inline-flex;', ' align-items: center;', ' gap: 5px;', ' min-height: 28px;', ' padding: 3px 10px;', ' border-radius: 999px;', ' background: rgba(0, 0, 0, .66);', ' border: 1px solid rgba(255, 255, 255, .16);', ' color: #e5e7eb;', ' font-size: 12px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-player-fav:hover { border-color: #fbbf24; color: #fff; }', '.ltv-player-fav.is-on { color: #fbbf24; border-color: rgba(251, 191, 36, .55); }', '.ltv-player-fav.has-update { border-color: rgba(244, 114, 182, .6); }', '.ltv-player-fav.has-update .ltv-pf-icon { color: #f472b6; }', '.ltv-player-fav:disabled { opacity: .5; cursor: default; }', '.ltv-player-tools {', ' position: absolute;', ' left: 10px;', ' bottom: 62px;', ' z-index: 22;', ' display: flex;', ' align-items: center;', ' gap: 6px;', '}', '.ltv-op-skip {', ' min-height: 28px;', ' padding: 3px 11px;', ' border-radius: 999px;', ' background: rgba(0, 0, 0, .72);', ' border: 1px solid rgba(0, 204, 255, .55);', ' color: #7dd3fc;', ' font-size: 12px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-op-skip:hover { background: rgba(0, 204, 255, .18); color: #fff; }', '.ltv-op-skip[hidden] { display: none !important; }', '.ltv-op-config {', ' width: 28px;', ' height: 28px;', ' padding: 0;', ' border-radius: 50%;', ' background: rgba(0, 0, 0, .66);', ' border: 1px solid rgba(255, 255, 255, .16);', ' color: #d1d5db;', ' font-size: 13px;', ' line-height: 1;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-op-config:hover { border-color: #00ccff; color: #fff; }', '.ltv-op-float {', ' position: fixed;', ' left: 16px;', ' bottom: calc(18px + env(safe-area-inset-bottom));', ' z-index: 40;', ' display: inline-flex;', ' align-items: center;', ' gap: 5px;', ' min-height: 34px;', ' padding: 5px 12px;', ' border-radius: 999px;', ' background: rgba(16, 16, 16, .92);', ' border: 1px solid rgba(0, 204, 255, .45);', ' box-shadow: 0 8px 24px rgba(0, 0, 0, .45);', ' color: #d1d5db;', ' font-size: 12px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-op-float:hover { border-color: #00ccff; color: #fff; }', '.ltv-op-float-icon { color: #00ccff; font-size: 13px; line-height: 1; }', 'body.ltv-ui-autohide .ltv-player-status { opacity: 0 !important; }', 'body.ltv-ui-autohide.ltv-ui-visible .ltv-player-status.is-visible { opacity: 1 !important; }', 'body.ltv-ui-autohide .ltv-player-fav,', 'body.ltv-ui-autohide .ltv-player-tools,', 'body.ltv-ui-autohide .ltv-op-float {', ' opacity: 0;', ' pointer-events: none;', ' transition: opacity .2s ease;', '}', 'body.ltv-ui-autohide.ltv-ui-visible .ltv-player-fav,', 'body.ltv-ui-autohide.ltv-ui-visible .ltv-player-tools,', 'body.ltv-ui-autohide.ltv-ui-visible .ltv-op-float {', ' opacity: 1;', ' pointer-events: auto;', '}', '#player .art-progress { position: relative; }', '.ltv-op-band {', ' position: absolute;', ' top: 0;', ' bottom: 0;', ' background: rgba(0, 204, 255, .22);', ' pointer-events: none;', ' z-index: 3;', '}', '.ltv-op-line {', ' position: absolute;', ' top: -2px;', ' bottom: -2px;', ' width: 2px;', ' margin-left: -1px;', ' background: #00ccff;', ' box-shadow: 0 0 6px rgba(0, 204, 255, .85);', ' pointer-events: none;', ' z-index: 4;', '}', '#ltv-op-overlay {', ' position: fixed;', ' inset: 0;', ' z-index: 10002;', ' display: flex;', ' align-items: center;', ' justify-content: center;', ' padding: 16px;', ' background: rgba(0, 0, 0, .74);', '}', '.ltv-op-panel {', ' display: flex;', ' flex-direction: column;', ' width: min(560px, 96vw);', ' max-height: min(86vh, 720px);', ' overflow: hidden;', ' background: #131313;', ' border: 1px solid #2f2f2f;', ' border-radius: 14px;', ' box-shadow: 0 24px 64px rgba(0, 0, 0, .6);', ' color: #e5e7eb;', ' font-size: 13px;', ' font-family: inherit;', '}', '.ltv-op-head {', ' display: flex;', ' align-items: flex-start;', ' gap: 10px;', ' padding: 16px 18px 12px;', ' border-bottom: 1px solid #242424;', '}', '.ltv-op-head-main { flex: 1; min-width: 0; }', '.ltv-op-title { color: #fff; font-size: 16px; font-weight: 600; line-height: 1.4; }', '.ltv-op-sub { margin-top: 4px; color: #8b949e; font-size: 11px; line-height: 1.5; word-break: break-word; }', '.ltv-op-close {', ' flex: none;', ' width: 30px;', ' height: 30px;', ' background: #1a1a1a;', ' border: 1px solid #333;', ' border-radius: 8px;', ' color: #d1d5db;', ' font-size: 17px;', ' line-height: 1;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-op-close:hover { background: #262626; }', '.ltv-op-body { flex: 1 1 auto; min-height: 0; overflow: auto; padding: 14px 18px 18px; }', '.ltv-op-now {', ' display: flex;', ' align-items: center;', ' gap: 10px;', ' padding: 11px 12px;', ' border: 1px solid #2a2a2a;', ' border-radius: 10px;', ' background: #181818;', '}', '.ltv-op-now-main { flex: 1; min-width: 0; }', '.ltv-op-now-label { display: block; color: #8b949e; font-size: 11px; line-height: 1.4; }', '.ltv-op-now-value {', ' display: block;', ' margin-top: 2px;', ' color: #fff;', ' font-size: 15px;', ' font-weight: 600;', ' line-height: 1.4;', ' font-variant-numeric: tabular-nums;', '}', '.ltv-op-now-value.is-muted { color: #9ca3af; font-weight: 500; }', '.ltv-op-pill {', ' flex: none;', ' max-width: 50%;', ' padding: 3px 9px;', ' border: 1px solid #333;', ' border-radius: 999px;', ' color: #9ca3af;', ' font-size: 10px;', ' line-height: 1.6;', ' white-space: nowrap;', ' overflow: hidden;', ' text-overflow: ellipsis;', '}', '.ltv-op-pill.is-hit { color: #7dd3fc; border-color: rgba(0, 204, 255, .45); background: rgba(0, 204, 255, .1); }', '.ltv-op-pill.is-missing { color: #fcd34d; border-color: rgba(252, 211, 77, .4); background: rgba(252, 211, 77, .08); }', '.ltv-op-actions {', ' display: grid;', ' grid-template-columns: 1fr auto;', ' gap: 8px;', ' margin-top: 12px;', '}', '.ltv-op-action {', ' min-height: 38px;', ' padding: 6px 14px;', ' border: 1px solid #333;', ' border-radius: 9px;', ' background: #1a1a1a;', ' color: #d1d5db;', ' font-size: 12px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-op-action:hover { border-color: #00ccff; color: #fff; }', '.ltv-op-action.primary {', ' display: flex;', ' align-items: center;', ' justify-content: space-between;', ' gap: 10px;', ' background: #00a3cc;', ' border-color: #00a3cc;', ' color: #001318;', ' font-weight: 600;', '}', '.ltv-op-action.primary:hover { border-color: #33c6e6; color: #001318; }', '.ltv-op-now-time { font-size: 11px; font-weight: 500; opacity: .75; font-variant-numeric: tabular-nums; white-space: nowrap; }', '.ltv-op-section { margin-top: 16px; }', '.ltv-op-section-head {', ' display: flex;', ' align-items: center;', ' justify-content: space-between;', ' gap: 8px;', ' margin-bottom: 6px;', ' color: #8b949e;', ' font-size: 11px;', '}', '.ltv-op-count { color: #6b7280; }', '.ltv-op-list {', ' border: 1px solid #262626;', ' border-radius: 10px;', ' overflow: hidden;', ' background: #161616;', '}', '.ltv-op-empty { padding: 14px 12px; color: #8b949e; font-size: 11px; line-height: 1.7; }', '.ltv-op-row {', ' display: flex;', ' align-items: center;', ' gap: 10px;', ' padding: 10px 12px;', ' border-bottom: 1px solid #232323;', '}', '.ltv-op-row:last-child { border-bottom: 0; }', '.ltv-op-row.is-hit { background: rgba(0, 204, 255, .06); }', '.ltv-op-row-main { flex: 1; min-width: 0; }', '.ltv-op-range { color: #e5e7eb; font-size: 12px; line-height: 1.5; word-break: break-word; }', '.ltv-op-range-time { margin-left: 6px; color: #7dd3fc; font-variant-numeric: tabular-nums; }', '.ltv-op-tags { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 5px; }', '.ltv-op-tag {', ' padding: 1px 7px;', ' border: 1px solid #333;', ' border-radius: 999px;', ' color: #9ca3af;', ' font-size: 10px;', ' line-height: 1.7;', '}', '.ltv-op-tag.hit { color: #7dd3fc; border-color: rgba(0, 204, 255, .45); background: rgba(0, 204, 255, .1); }', '.ltv-op-del {', ' flex: none;', ' min-height: 28px;', ' padding: 3px 10px;', ' border: 1px solid #333;', ' border-radius: 7px;', ' background: #1a1a1a;', ' color: #9ca3af;', ' font-size: 11px;', ' font-family: inherit;', ' cursor: pointer;', '}', '.ltv-op-del:hover { border-color: #ef4444; color: #fca5a5; }', '.ltv-op-hint {', ' padding: 8px 12px;', ' border-top: 1px solid #232323;', ' background: rgba(252, 211, 77, .04);', ' color: #fcd34d;', ' font-size: 11px;', ' line-height: 1.6;', '}', '.ltv-op-advanced {', ' display: flex;', ' flex-direction: column;', ' gap: 12px;', ' margin-top: 16px;', ' padding: 12px;', ' border: 1px solid #262626;', ' border-radius: 10px;', ' background: #161616;', '}', '.ltv-op-field { display: flex; align-items: center; gap: 8px; }', '.ltv-op-field label { flex: none; color: #9ca3af; font-size: 12px; }', '.ltv-op-field input {', ' width: 74px;', ' min-height: 32px;', ' padding: 3px 8px;', ' border: 1px solid #333;', ' border-radius: 7px;', ' background: #0d0d0d;', ' color: #e5e7eb;', ' font-size: 12px;', ' font-family: inherit;', ' text-align: center;', '}', '.ltv-op-field .ltv-op-action { margin-left: auto; min-height: 32px; }', '.ltv-op-switch { display: flex; align-items: center; gap: 10px; cursor: pointer; user-select: none; }', '.ltv-op-switch input { position: absolute; width: 0; height: 0; opacity: 0; }', '.ltv-op-switch-track {', ' position: relative;', ' flex: none;', ' width: 34px;', ' height: 20px;', ' border-radius: 999px;', ' background: #333;', ' transition: background .15s ease;', '}', '.ltv-op-switch-track::after {', ' content: "";', ' position: absolute;', ' top: 2px;', ' left: 2px;', ' width: 16px;', ' height: 16px;', ' border-radius: 50%;', ' background: #9ca3af;', ' transition: transform .15s ease, background .15s ease;', '}', '.ltv-op-switch input:checked + .ltv-op-switch-track { background: rgba(0, 204, 255, .32); }', '.ltv-op-switch input:checked + .ltv-op-switch-track::after { transform: translateX(14px); background: #00ccff; }', '.ltv-op-switch-text { color: #d1d5db; font-size: 12px; line-height: 1.5; }', '.ltv-op-switch-text small { display: block; color: #6b7280; font-size: 10px; line-height: 1.5; }', '.ltv-op-status { margin-top: 12px; color: #7dd3fc; font-size: 11px; line-height: 1.6; min-height: 14px; }', '.ltv-op-tip { margin-top: 10px; color: #6b7280; font-size: 10px; line-height: 1.6; }', '.ltv-resume-toast {', ' position: absolute;', ' left: 12px;', ' bottom: 72px;', ' z-index: 26;', ' max-width: min(360px, calc(100% - 24px));', ' padding: 10px 12px;', ' border-radius: 10px;', ' background: rgba(16, 16, 16, .94);', ' border: 1px solid rgba(0, 204, 255, .4);', ' box-shadow: 0 10px 30px rgba(0, 0, 0, .5);', ' color: #e5e7eb;', ' font-size: 12px;', ' line-height: 1.5;', ' font-family: inherit;', '}', '.ltv-resume-text { margin-bottom: 8px; }', '.ltv-resume-actions { display: flex; align-items: center; gap: 6px; }', '.ltv-resume-actions button {', ' min-height: 28px;', ' padding: 3px 10px;', ' border-radius: 6px;', ' font-size: 11px;', ' font-family: inherit;', ' cursor: pointer;', ' touch-action: manipulation;', '}', '.ltv-resume-primary { background: #00a3cc; border: 1px solid #00a3cc; color: #001318; font-weight: 600; }', '.ltv-resume-secondary { background: #1a1a1a; border: 1px solid #333; color: #d1d5db; }', '.ltv-resume-close { margin-left: auto; background: none; border: 0; color: #9ca3af; font-size: 14px; padding: 0 4px; }', '.ltv-player-notice {', ' position: absolute;', ' left: 50%;', ' bottom: 72px;', ' transform: translateX(-50%);', ' z-index: 27;', ' padding: 7px 12px;', ' border-radius: 999px;', ' background: rgba(0, 0, 0, .86);', ' border: 1px solid rgba(255, 255, 255, .14);', ' color: #e5e7eb;', ' font-size: 12px;', ' font-family: inherit;', ' pointer-events: none;', '}', '@media (max-width: 640px) {', ' .ltv-player-status { top: 8px; left: 8px; font-size: 10px; padding: 3px 7px; max-width: calc(100% - 92px); }', ' .ltv-player-fav { top: 8px; right: 8px; min-height: 26px; font-size: 11px; padding: 2px 8px; }', ' .ltv-player-tools { left: 8px; bottom: 54px; }', ' .ltv-op-skip { min-height: 30px; font-size: 11px; padding: 2px 9px; }', ' .ltv-op-config { width: 30px; height: 30px; }', ' .ltv-op-float { left: 12px; bottom: calc(14px + env(safe-area-inset-bottom)); min-height: 36px; font-size: 13px; }', ' #ltv-op-overlay { align-items: flex-end; padding: 0; }', ' .ltv-op-panel { width: 100%; max-height: 88vh; border-radius: 16px 16px 0 0; border-bottom: 0; }', ' .ltv-op-head { padding: 14px 16px 10px; }', ' .ltv-op-body { padding: 12px 16px calc(16px + env(safe-area-inset-bottom)); }', ' .ltv-op-actions { grid-template-columns: 1fr; }', ' .ltv-op-action { min-height: 40px; }', ' .ltv-resume-toast { bottom: 60px; left: 8px; font-size: 11px; }', '}' ].join('\n'); (document.head || document.documentElement).appendChild(style); } function boot() { if (!isSearchPage()) return; const element = document.querySelector('#results'); if (!element) { waitForResults(); return; } if (resultsEl === element && document.getElementById(TOOLBAR_ID)) { render(false); return; } if (resultsEl && resultsEl !== element) teardown(); resultsEl = element; setup(); } function startUrlWatch() { if (urlTimer) return; urlTimer = setInterval(function () { const currentUrl = location.href; if (currentUrl !== lastUrl) { lastUrl = currentUrl; if (isSearchPage()) { // 新版站点在同一页面内用 pushState 切换搜索词, // 保持工具栏和观察器,避免每次搜索都整块重建 if (resultsEl && resultsEl.isConnected) { if (!document.getElementById(TOOLBAR_ID)) setup(); else render(true); } else { teardown(); boot(); } } else { teardown(); } updateHomeEntry(); return; } if (!isSearchPage()) { if (resultsEl) teardown(); updateHomeEntry(); return; } removeHomeEntry(); const element = document.querySelector('#results'); if (element && element !== resultsEl) { teardown(); resultsEl = element; setup(); return; } if (resultsEl && !document.getElementById(TOOLBAR_ID)) { ensureToolbar(); render(true); } }, 1200); } initPlayerFeatures(); if (IS_TOP_FRAME) { // 搜索净化、主页入口、WebDAV 同步只在顶层窗口运行, // iframe 里只保留播放页功能,避免重复轮询和重复 UI。 initSourceManager(); initSync(); installMobilePlayerBridge(); installHistoryClickFallback(); startUrlWatch(); updateHomeEntry(); if (isSearchPage()) boot(); } })();